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
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
|
//! Repository pattern for file database operations.
use chrono::Utc;
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;
use super::models::{
CheckpointPatch, CheckpointPatchInfo, Contract, ContractChatConversation,
ContractChatMessageRecord, ContractEvent, ContractRepository, ContractSummary,
ContractTypeTemplateRecord, ConversationMessage, ConversationSnapshot,
CreateContractRequest, CreateFileRequest, CreateTaskRequest,
CreateTemplateRequest, Daemon, DaemonTaskAssignment, DaemonWithCapacity,
DeliverableDefinition, Directive, DirectiveStep, DirectiveSummary,
CreateDirectiveRequest, CreateDirectiveStepRequest, DirectiveGoalHistory,
UpdateDirectiveRequest, UpdateDirectiveStepRequest,
CreateOrderRequest, Order, UpdateOrderRequest,
CreateDirectiveOrderGroupRequest, DirectiveOrderGroup, UpdateDirectiveOrderGroupRequest,
File, FileSummary, FileVersion, HistoryEvent, HistoryQueryFilters,
MeshChatConversation, MeshChatMessageRecord, PhaseChangeResult, PhaseConfig,
PhaseDefinition, SupervisorHeartbeatRecord, SupervisorState,
Task, TaskCheckpoint, TaskEvent, TaskSummary, UpdateContractRequest,
UpdateFileRequest, UpdateTaskRequest, UpdateTemplateRequest,
UserSetting,
};
/// Repository error types.
#[derive(Debug)]
pub enum RepositoryError {
/// Database error
Database(sqlx::Error),
/// Version conflict (optimistic locking failure)
VersionConflict {
/// The version the client expected
expected: i32,
/// The actual current version in the database
actual: i32,
},
}
impl From<sqlx::Error> for RepositoryError {
fn from(e: sqlx::Error) -> Self {
RepositoryError::Database(e)
}
}
impl std::fmt::Display for RepositoryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RepositoryError::Database(e) => write!(f, "Database error: {}", e),
RepositoryError::VersionConflict { expected, actual } => {
write!(
f,
"Version conflict: expected {}, actual {}",
expected, actual
)
}
}
}
}
impl std::error::Error for RepositoryError {}
/// Generate a default name based on current timestamp.
fn generate_default_name() -> String {
let now = Utc::now();
now.format("Recording - %b %d %Y %H:%M:%S").to_string()
}
/// Internal request for creating files without contract association (e.g., audio transcription).
/// User-facing file creation should use CreateFileRequest which requires contract_id.
pub struct InternalCreateFileRequest {
pub name: Option<String>,
pub description: Option<String>,
pub transcript: Vec<super::models::TranscriptEntry>,
pub location: Option<String>,
}
/// Create a new file record (internal use, no contract required).
/// For user-facing file creation, use create_file_for_owner which requires a contract.
pub async fn create_file(pool: &PgPool, req: InternalCreateFileRequest) -> Result<File, sqlx::Error> {
let name = req.name.unwrap_or_else(generate_default_name);
let transcript_json = serde_json::to_value(&req.transcript).unwrap_or_default();
let body_json = serde_json::to_value::<Vec<super::models::BodyElement>>(vec![]).unwrap();
sqlx::query_as::<_, File>(
r#"
INSERT INTO files (name, description, transcript, location, summary, body)
VALUES ($1, $2, $3, $4, NULL, $5)
RETURNING id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
"#,
)
.bind(&name)
.bind(&req.description)
.bind(&transcript_json)
.bind(&req.location)
.bind(&body_json)
.fetch_one(pool)
.await
}
/// Get a file by ID.
pub async fn get_file(pool: &PgPool, id: Uuid) -> Result<Option<File>, sqlx::Error> {
sqlx::query_as::<_, File>(
r#"
SELECT id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
FROM files
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await
}
/// List all files, ordered by created_at DESC.
pub async fn list_files(pool: &PgPool) -> Result<Vec<File>, sqlx::Error> {
sqlx::query_as::<_, File>(
r#"
SELECT id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
FROM files
ORDER BY created_at DESC
"#,
)
.fetch_all(pool)
.await
}
/// Update a file by ID with optimistic locking.
///
/// If `req.version` is provided, the update will only succeed if the current
/// version matches. Returns `RepositoryError::VersionConflict` if there's a mismatch.
///
/// If `req.version` is None (e.g., internal system updates), version checking is skipped.
pub async fn update_file(
pool: &PgPool,
id: Uuid,
req: UpdateFileRequest,
) -> Result<Option<File>, RepositoryError> {
// Get the existing file first
let existing = get_file(pool, id).await?;
let Some(existing) = existing else {
return Ok(None);
};
// Check version if provided (optimistic locking)
if let Some(expected_version) = req.version {
if existing.version != expected_version {
return Err(RepositoryError::VersionConflict {
expected: expected_version,
actual: existing.version,
});
}
}
// Apply updates
let name = req.name.unwrap_or(existing.name);
let description = req.description.or(existing.description);
let transcript = req.transcript.unwrap_or(existing.transcript);
let transcript_json = serde_json::to_value(&transcript).unwrap_or_default();
let summary = req.summary.or(existing.summary);
let body = req.body.unwrap_or(existing.body);
let body_json = serde_json::to_value(&body).unwrap_or_default();
// Update with version check in WHERE clause for race condition safety
let result = if req.version.is_some() {
sqlx::query_as::<_, File>(
r#"
UPDATE files
SET name = $2, description = $3, transcript = $4, summary = $5, body = $6, updated_at = NOW()
WHERE id = $1 AND version = $7
RETURNING id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
"#,
)
.bind(id)
.bind(&name)
.bind(&description)
.bind(&transcript_json)
.bind(&summary)
.bind(&body_json)
.bind(req.version.unwrap())
.fetch_optional(pool)
.await?
} else {
// No version check for internal updates
sqlx::query_as::<_, File>(
r#"
UPDATE files
SET name = $2, description = $3, transcript = $4, summary = $5, body = $6, updated_at = NOW()
WHERE id = $1
RETURNING id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
"#,
)
.bind(id)
.bind(&name)
.bind(&description)
.bind(&transcript_json)
.bind(&summary)
.bind(&body_json)
.fetch_optional(pool)
.await?
};
// If versioned update returned None, there was a race condition
if result.is_none() && req.version.is_some() {
// Re-fetch to get the actual version
if let Some(current) = get_file(pool, id).await? {
return Err(RepositoryError::VersionConflict {
expected: req.version.unwrap(),
actual: current.version,
});
}
}
Ok(result)
}
/// Delete a file by ID.
pub async fn delete_file(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM files
WHERE id = $1
"#,
)
.bind(id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Count total files.
pub async fn count_files(pool: &PgPool) -> Result<i64, sqlx::Error> {
let result: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM files")
.fetch_one(pool)
.await?;
Ok(result.0)
}
// =============================================================================
// Owner-Scoped File Functions
// =============================================================================
/// Create a new file record for a specific owner.
/// Files must belong to a contract - the contract_id is required and the phase is looked up.
pub async fn create_file_for_owner(
pool: &PgPool,
owner_id: Uuid,
req: CreateFileRequest,
) -> Result<File, sqlx::Error> {
let name = req.name.unwrap_or_else(generate_default_name);
let transcript_json = serde_json::to_value(&req.transcript).unwrap_or_default();
// Use body from request (may be empty or contain template elements)
let body_json = serde_json::to_value(&req.body).unwrap_or_default();
// Use provided contract_phase, or look up from contract's current phase
let contract_phase: Option<String> = if req.contract_phase.is_some() {
req.contract_phase
} else {
sqlx::query_scalar(
"SELECT phase FROM contracts WHERE id = $1 AND owner_id = $2",
)
.bind(req.contract_id)
.bind(owner_id)
.fetch_optional(pool)
.await?
};
sqlx::query_as::<_, File>(
r#"
INSERT INTO files (owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, repo_file_path)
VALUES ($1, $2, $3, $4, $5, $6, $7, NULL, $8, $9)
RETURNING id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
"#,
)
.bind(owner_id)
.bind(req.contract_id)
.bind(&contract_phase)
.bind(&name)
.bind(&req.description)
.bind(&transcript_json)
.bind(&req.location)
.bind(&body_json)
.bind(&req.repo_file_path)
.fetch_one(pool)
.await
}
/// Get a file by ID, scoped to owner.
pub async fn get_file_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<Option<File>, sqlx::Error> {
sqlx::query_as::<_, File>(
r#"
SELECT id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
FROM files
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// List all files for an owner, ordered by created_at DESC.
pub async fn list_files_for_owner(pool: &PgPool, owner_id: Uuid) -> Result<Vec<File>, sqlx::Error> {
sqlx::query_as::<_, File>(
r#"
SELECT id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
FROM files
WHERE owner_id = $1
ORDER BY created_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Database row type for file summary with contract info
#[derive(Debug, sqlx::FromRow)]
struct FileSummaryRow {
id: Uuid,
contract_id: Option<Uuid>,
contract_name: Option<String>,
contract_phase: Option<String>,
name: String,
description: Option<String>,
#[sqlx(json)]
transcript: Vec<crate::db::models::TranscriptEntry>,
version: i32,
repo_file_path: Option<String>,
repo_sync_status: Option<String>,
created_at: chrono::DateTime<chrono::Utc>,
updated_at: chrono::DateTime<chrono::Utc>,
}
/// List file summaries for an owner with contract info (joined).
pub async fn list_file_summaries_for_owner(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<FileSummary>, sqlx::Error> {
let rows = sqlx::query_as::<_, FileSummaryRow>(
r#"
SELECT
f.id, f.contract_id, c.name as contract_name, f.contract_phase,
f.name, f.description, f.transcript, f.version,
f.repo_file_path, f.repo_sync_status, f.created_at, f.updated_at
FROM files f
LEFT JOIN contracts c ON f.contract_id = c.id
WHERE f.owner_id = $1
ORDER BY f.created_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await?;
Ok(rows
.into_iter()
.map(|row| {
let duration = row
.transcript
.iter()
.map(|t| t.end)
.fold(0.0_f32, f32::max);
FileSummary {
id: row.id,
contract_id: row.contract_id,
contract_name: row.contract_name,
contract_phase: row.contract_phase,
name: row.name,
description: row.description,
transcript_count: row.transcript.len(),
duration: if duration > 0.0 { Some(duration) } else { None },
version: row.version,
repo_file_path: row.repo_file_path,
repo_sync_status: row.repo_sync_status,
created_at: row.created_at,
updated_at: row.updated_at,
}
})
.collect())
}
/// Update a file by ID with optimistic locking, scoped to owner.
pub async fn update_file_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
req: UpdateFileRequest,
) -> Result<Option<File>, RepositoryError> {
// Get the existing file first (scoped to owner)
let existing = get_file_for_owner(pool, id, owner_id).await?;
let Some(existing) = existing else {
return Ok(None);
};
// Check version if provided (optimistic locking)
if let Some(expected_version) = req.version {
if existing.version != expected_version {
return Err(RepositoryError::VersionConflict {
expected: expected_version,
actual: existing.version,
});
}
}
// Apply updates
let name = req.name.unwrap_or(existing.name);
let description = req.description.or(existing.description);
let transcript = req.transcript.unwrap_or(existing.transcript);
let transcript_json = serde_json::to_value(&transcript).unwrap_or_default();
let summary = req.summary.or(existing.summary);
let body = req.body.unwrap_or(existing.body);
let body_json = serde_json::to_value(&body).unwrap_or_default();
// Update with version check in WHERE clause for race condition safety
let result = if req.version.is_some() {
sqlx::query_as::<_, File>(
r#"
UPDATE files
SET name = $3, description = $4, transcript = $5, summary = $6, body = $7, updated_at = NOW()
WHERE id = $1 AND owner_id = $2 AND version = $8
RETURNING id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
"#,
)
.bind(id)
.bind(owner_id)
.bind(&name)
.bind(&description)
.bind(&transcript_json)
.bind(&summary)
.bind(&body_json)
.bind(req.version.unwrap())
.fetch_optional(pool)
.await?
} else {
// No version check for internal updates
sqlx::query_as::<_, File>(
r#"
UPDATE files
SET name = $3, description = $4, transcript = $5, summary = $6, body = $7, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
"#,
)
.bind(id)
.bind(owner_id)
.bind(&name)
.bind(&description)
.bind(&transcript_json)
.bind(&summary)
.bind(&body_json)
.fetch_optional(pool)
.await?
};
// If versioned update returned None, there was a race condition
if result.is_none() && req.version.is_some() {
// Re-fetch to get the actual version
if let Some(current) = get_file_for_owner(pool, id, owner_id).await? {
return Err(RepositoryError::VersionConflict {
expected: req.version.unwrap(),
actual: current.version,
});
}
}
Ok(result)
}
/// Delete a file by ID, scoped to owner.
pub async fn delete_file_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM files
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
// =============================================================================
// Version History Functions
// =============================================================================
/// Set the version source for the current transaction.
/// This is used by the trigger to record who made the change.
pub async fn set_version_source(pool: &PgPool, source: &str) -> Result<(), sqlx::Error> {
sqlx::query(&format!("SET LOCAL app.version_source = '{}'", source))
.execute(pool)
.await?;
Ok(())
}
/// Set the change description for the current transaction.
pub async fn set_change_description(pool: &PgPool, description: &str) -> Result<(), sqlx::Error> {
// Escape single quotes for SQL
let escaped = description.replace('\'', "''");
sqlx::query(&format!("SET LOCAL app.change_description = '{}'", escaped))
.execute(pool)
.await?;
Ok(())
}
/// List all versions of a file, ordered by version DESC.
pub async fn list_file_versions(pool: &PgPool, file_id: Uuid) -> Result<Vec<FileVersion>, sqlx::Error> {
// First get the current version from the files table
let current = get_file(pool, file_id).await?;
let mut versions = sqlx::query_as::<_, FileVersion>(
r#"
SELECT id, file_id, version, name, description, summary, body, source, change_description, created_at
FROM file_versions
WHERE file_id = $1
ORDER BY version DESC
"#,
)
.bind(file_id)
.fetch_all(pool)
.await?;
// Add the current version as the first entry if it exists
if let Some(file) = current {
let current_version = FileVersion {
id: file.id,
file_id: file.id,
version: file.version,
name: file.name,
description: file.description,
summary: file.summary,
body: file.body,
source: "user".to_string(), // Current version source
change_description: None,
created_at: file.updated_at,
};
versions.insert(0, current_version);
}
Ok(versions)
}
/// Get a specific version of a file.
pub async fn get_file_version(
pool: &PgPool,
file_id: Uuid,
version: i32,
) -> Result<Option<FileVersion>, sqlx::Error> {
// First check if this is the current version
if let Some(file) = get_file(pool, file_id).await? {
if file.version == version {
return Ok(Some(FileVersion {
id: file.id,
file_id: file.id,
version: file.version,
name: file.name,
description: file.description,
summary: file.summary,
body: file.body,
source: "user".to_string(),
change_description: None,
created_at: file.updated_at,
}));
}
}
// Otherwise, look in the versions table
sqlx::query_as::<_, FileVersion>(
r#"
SELECT id, file_id, version, name, description, summary, body, source, change_description, created_at
FROM file_versions
WHERE file_id = $1 AND version = $2
"#,
)
.bind(file_id)
.bind(version)
.fetch_optional(pool)
.await
}
/// Restore a file to a previous version.
/// This creates a new version with the content from the target version.
pub async fn restore_file_version(
pool: &PgPool,
file_id: Uuid,
target_version: i32,
current_version: i32,
) -> Result<Option<File>, RepositoryError> {
// Get the target version content
let target = get_file_version(pool, file_id, target_version).await?;
let Some(target) = target else {
return Ok(None);
};
// Set version source and description for the trigger
set_version_source(pool, "system").await?;
set_change_description(pool, &format!("Restored from version {}", target_version)).await?;
// Update the file with the target version's content
// This will trigger the save_file_version trigger to save the current state first
let update_req = UpdateFileRequest {
name: Some(target.name),
description: target.description,
transcript: None,
summary: target.summary,
body: Some(target.body),
version: Some(current_version),
repo_file_path: None,
};
update_file(pool, file_id, update_req).await
}
/// Count versions for a file.
pub async fn count_file_versions(pool: &PgPool, file_id: Uuid) -> Result<i64, sqlx::Error> {
let result: (i64,) = sqlx::query_as(
"SELECT COUNT(*) + 1 FROM file_versions WHERE file_id = $1", // +1 for current version
)
.bind(file_id)
.fetch_one(pool)
.await?;
Ok(result.0)
}
// =============================================================================
// Task Functions
// =============================================================================
/// Create a new task.
///
/// If creating a subtask (parent_task_id is set) and repository settings are not provided,
/// the subtask will inherit repository_url, base_branch, target_branch, merge_mode,
/// and target_repo_path from the parent task. Depth is calculated from parent and limited
/// to max 1 (2 levels: orchestrator at depth 0, subtasks at depth 1).
///
/// NOTE: completion_action is NOT inherited - subtasks should not auto-merge unless
/// explicitly configured. The supervisor controls when completion steps happen.
///
/// Task spawning is now controlled by supervisors at the application level.
/// Depth is no longer constrained in the database.
pub async fn create_task(pool: &PgPool, req: CreateTaskRequest) -> Result<Task, sqlx::Error> {
// Calculate depth and inherit settings from parent if applicable
let (depth, contract_id, repo_url, base_branch, target_branch, merge_mode, target_repo_path, completion_action) =
if let Some(parent_id) = req.parent_task_id {
// Fetch parent task to get depth and inherit settings
let parent = get_task(pool, parent_id).await?
.ok_or_else(|| sqlx::Error::RowNotFound)?;
let new_depth = parent.depth + 1;
// Subtasks inherit contract_id from parent (or use request contract_id if parent has none)
let contract_id = parent.contract_id.or(req.contract_id);
// Inherit repo settings if not provided
let repo_url = req.repository_url.clone().or(parent.repository_url);
let base_branch = req.base_branch.clone().or(parent.base_branch);
let target_branch = req.target_branch.clone().or(parent.target_branch);
let merge_mode = req.merge_mode.clone().or(parent.merge_mode);
let target_repo_path = req.target_repo_path.clone().or(parent.target_repo_path);
// NOTE: completion_action is NOT inherited - subtasks should not auto-merge.
// The supervisor integrates subtask work from their worktrees.
let completion_action = req.completion_action.clone();
(new_depth, contract_id, repo_url, base_branch, target_branch, merge_mode, target_repo_path, completion_action)
} else {
// Top-level task: depth 0, use contract_id from request (may be None for branched tasks)
(
0,
req.contract_id,
req.repository_url.clone(),
req.base_branch.clone(),
req.target_branch.clone(),
req.merge_mode.clone(),
req.target_repo_path.clone(),
req.completion_action.clone(),
)
};
let copy_files_json = req.copy_files.as_ref().map(|f| serde_json::to_value(f).unwrap_or_default());
sqlx::query_as::<_, Task>(
r#"
INSERT INTO tasks (
contract_id, parent_task_id, depth, name, description, plan, priority,
is_supervisor, repository_url, base_branch, target_branch, merge_mode,
target_repo_path, completion_action, continue_from_task_id, copy_files,
branched_from_task_id, conversation_state, supervisor_worktree_task_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
RETURNING *
"#,
)
.bind(contract_id)
.bind(req.parent_task_id)
.bind(depth)
.bind(&req.name)
.bind(&req.description)
.bind(&req.plan)
.bind(req.priority)
.bind(req.is_supervisor)
.bind(&repo_url)
.bind(&base_branch)
.bind(&target_branch)
.bind(&merge_mode)
.bind(&target_repo_path)
.bind(&completion_action)
.bind(&req.continue_from_task_id)
.bind(©_files_json)
.bind(&req.branched_from_task_id)
.bind(&req.conversation_history)
.bind(&req.supervisor_worktree_task_id)
.fetch_one(pool)
.await
}
/// Get a task by ID.
pub async fn get_task(pool: &PgPool, id: Uuid) -> Result<Option<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
SELECT *
FROM tasks
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await
}
/// List all top-level tasks (no parent), ordered by created_at DESC.
/// Hidden tasks are excluded by default.
pub async fn list_tasks(pool: &PgPool) -> Result<Vec<TaskSummary>, sqlx::Error> {
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.parent_task_id IS NULL AND COALESCE(t.hidden, false) = false
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.fetch_all(pool)
.await
}
/// List subtasks of a parent task.
pub async fn list_subtasks(pool: &PgPool, parent_id: Uuid) -> Result<Vec<TaskSummary>, sqlx::Error> {
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.parent_task_id = $1
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.bind(parent_id)
.fetch_all(pool)
.await
}
/// List all tasks in a contract (for supervisor tree view).
pub async fn list_tasks_by_contract(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
SELECT * FROM tasks
WHERE contract_id = $1 AND owner_id = $2
ORDER BY is_supervisor DESC, depth ASC, created_at ASC
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get pending tasks for a contract (non-supervisor tasks only).
/// Includes tasks that were interrupted (retry candidates).
/// Prioritizes interrupted tasks and excludes those that exceeded max_retries.
pub async fn get_pending_tasks_for_contract(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
SELECT t.* FROM tasks t
WHERE t.contract_id = $1 AND t.owner_id = $2
AND t.status = 'pending'
AND t.retry_count < t.max_retries
AND t.is_supervisor = false
ORDER BY
t.interrupted_at DESC NULLS LAST,
t.priority DESC,
t.created_at ASC
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get all contracts that have pending tasks awaiting retry.
/// Returns tuples of (contract_id, owner_id) for contracts with retryable tasks.
pub async fn get_all_pending_task_contracts(
pool: &PgPool,
) -> Result<Vec<(Uuid, Uuid)>, sqlx::Error> {
sqlx::query_as::<_, (Uuid, Uuid)>(
r#"
SELECT DISTINCT t.contract_id, t.owner_id
FROM tasks t
WHERE t.contract_id IS NOT NULL
AND t.status = 'pending'
AND t.retry_count < t.max_retries
AND t.is_supervisor = false
ORDER BY t.owner_id, t.contract_id
"#,
)
.fetch_all(pool)
.await
}
/// Mark a task as pending for retry after daemon failure.
/// Increments retry count and adds the failed daemon to exclusion list.
pub async fn mark_task_for_retry(
pool: &PgPool,
task_id: Uuid,
failed_daemon_id: Uuid,
) -> Result<Option<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET status = 'pending',
daemon_id = NULL,
retry_count = retry_count + 1,
failed_daemon_ids = array_append(COALESCE(failed_daemon_ids, '{}'), $2),
last_active_daemon_id = $2,
interrupted_at = NOW(),
error_message = 'Daemon disconnected, awaiting retry',
updated_at = NOW()
WHERE id = $1
AND retry_count < max_retries
RETURNING *
"#,
)
.bind(task_id)
.bind(failed_daemon_id)
.fetch_optional(pool)
.await
}
/// Mark a task as permanently failed (exceeded retry limit).
pub async fn mark_task_permanently_failed(
pool: &PgPool,
task_id: Uuid,
failed_daemon_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE tasks
SET status = 'failed',
daemon_id = NULL,
retry_count = retry_count + 1,
failed_daemon_ids = array_append(COALESCE(failed_daemon_ids, '{}'), $2),
last_active_daemon_id = $2,
error_message = 'Task failed: exceeded maximum retry attempts',
updated_at = NOW()
WHERE id = $1
"#,
)
.bind(task_id)
.bind(failed_daemon_id)
.execute(pool)
.await?;
Ok(())
}
/// Update a task by ID with optimistic locking.
pub async fn update_task(
pool: &PgPool,
id: Uuid,
req: UpdateTaskRequest,
) -> Result<Option<Task>, RepositoryError> {
// Get the existing task first
let existing = get_task(pool, id).await?;
let Some(existing) = existing else {
return Ok(None);
};
// Check version if provided (optimistic locking)
if let Some(expected_version) = req.version {
if existing.version != expected_version {
return Err(RepositoryError::VersionConflict {
expected: expected_version,
actual: existing.version,
});
}
}
// Apply updates
let name = req.name.unwrap_or(existing.name);
let description = req.description.or(existing.description);
let plan = req.plan.unwrap_or(existing.plan);
let status = req.status.unwrap_or(existing.status);
let priority = req.priority.unwrap_or(existing.priority);
let progress_summary = req.progress_summary.or(existing.progress_summary);
let last_output = req.last_output.or(existing.last_output);
let error_message = req.error_message.or(existing.error_message);
let merge_mode = req.merge_mode.or(existing.merge_mode);
let pr_url = req.pr_url.or(existing.pr_url);
let target_repo_path = req.target_repo_path.or(existing.target_repo_path);
let completion_action = req.completion_action.or(existing.completion_action);
// Handle clear_daemon_id: if true, set to NULL; otherwise use provided value or keep existing
let daemon_id = if req.clear_daemon_id {
None
} else {
req.daemon_id.or(existing.daemon_id)
};
// Update with version check in WHERE clause for race condition safety
let result = if req.version.is_some() {
sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET name = $2, description = $3, plan = $4, status = $5, priority = $6,
progress_summary = $7, last_output = $8, error_message = $9,
merge_mode = $10, pr_url = $11, daemon_id = $12,
target_repo_path = $13, completion_action = $14, updated_at = NOW()
WHERE id = $1 AND version = $15
RETURNING *
"#,
)
.bind(id)
.bind(&name)
.bind(&description)
.bind(&plan)
.bind(&status)
.bind(priority)
.bind(&progress_summary)
.bind(&last_output)
.bind(&error_message)
.bind(&merge_mode)
.bind(&pr_url)
.bind(daemon_id)
.bind(&target_repo_path)
.bind(&completion_action)
.bind(req.version.unwrap())
.fetch_optional(pool)
.await?
} else {
sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET name = $2, description = $3, plan = $4, status = $5, priority = $6,
progress_summary = $7, last_output = $8, error_message = $9,
merge_mode = $10, pr_url = $11, daemon_id = $12,
target_repo_path = $13, completion_action = $14, updated_at = NOW()
WHERE id = $1
RETURNING *
"#,
)
.bind(id)
.bind(&name)
.bind(&description)
.bind(&plan)
.bind(&status)
.bind(priority)
.bind(&progress_summary)
.bind(&last_output)
.bind(&error_message)
.bind(&merge_mode)
.bind(&pr_url)
.bind(daemon_id)
.bind(&target_repo_path)
.bind(&completion_action)
.fetch_optional(pool)
.await?
};
// If versioned update returned None, there was a race condition
if result.is_none() && req.version.is_some() {
if let Some(current) = get_task(pool, id).await? {
return Err(RepositoryError::VersionConflict {
expected: req.version.unwrap(),
actual: current.version,
});
}
}
Ok(result)
}
/// Delete a task by ID.
pub async fn delete_task(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM tasks
WHERE id = $1
"#,
)
.bind(id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Count total tasks.
pub async fn count_tasks(pool: &PgPool) -> Result<i64, sqlx::Error> {
let result: (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM tasks WHERE parent_task_id IS NULL",
)
.fetch_one(pool)
.await?;
Ok(result.0)
}
// =============================================================================
// Owner-Scoped Task Functions
// =============================================================================
/// Create a new task for a specific owner.
pub async fn create_task_for_owner(
pool: &PgPool,
owner_id: Uuid,
req: CreateTaskRequest,
) -> Result<Task, sqlx::Error> {
// Calculate depth and inherit settings from parent if applicable
let (depth, contract_id, repo_url, base_branch, target_branch, merge_mode, target_repo_path, completion_action) =
if let Some(parent_id) = req.parent_task_id {
// Fetch parent task to get depth and inherit settings (must belong to same owner)
let parent = get_task_for_owner(pool, parent_id, owner_id).await?
.ok_or_else(|| sqlx::Error::RowNotFound)?;
let new_depth = parent.depth + 1;
// Validate max depth
if new_depth >= 2 {
return Err(sqlx::Error::Protocol(format!(
"Maximum task depth exceeded. Cannot create subtask at depth {} (max is 1). Subtasks cannot have children.",
new_depth
)));
}
// Subtasks inherit contract_id from parent (or use request contract_id if parent has none)
let contract_id = parent.contract_id.or(req.contract_id);
// Inherit repo settings if not provided
let repo_url = req.repository_url.clone().or(parent.repository_url);
let base_branch = req.base_branch.clone().or(parent.base_branch);
let target_branch = req.target_branch.clone().or(parent.target_branch);
let merge_mode = req.merge_mode.clone().or(parent.merge_mode);
let target_repo_path = req.target_repo_path.clone().or(parent.target_repo_path);
// NOTE: completion_action is NOT inherited - subtasks should not auto-merge.
// The orchestrator integrates subtask work from their worktrees.
let completion_action = req.completion_action.clone();
(new_depth, contract_id, repo_url, base_branch, target_branch, merge_mode, target_repo_path, completion_action)
} else {
// Top-level task: depth 0, use contract_id from request (may be None for branched tasks)
(
0,
req.contract_id,
req.repository_url.clone(),
req.base_branch.clone(),
req.target_branch.clone(),
req.merge_mode.clone(),
req.target_repo_path.clone(),
req.completion_action.clone(),
)
};
let copy_files_json = req.copy_files.as_ref().map(|f| serde_json::to_value(f).unwrap_or_default());
sqlx::query_as::<_, Task>(
r#"
INSERT INTO tasks (
owner_id, contract_id, parent_task_id, depth, name, description, plan, priority,
is_supervisor, repository_url, base_branch, target_branch, merge_mode,
target_repo_path, completion_action, continue_from_task_id, copy_files,
branched_from_task_id, conversation_state, supervisor_worktree_task_id,
directive_id, directive_step_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)
RETURNING *
"#,
)
.bind(owner_id)
.bind(contract_id)
.bind(req.parent_task_id)
.bind(depth)
.bind(&req.name)
.bind(&req.description)
.bind(&req.plan)
.bind(req.priority)
.bind(req.is_supervisor)
.bind(&repo_url)
.bind(&base_branch)
.bind(&target_branch)
.bind(&merge_mode)
.bind(&target_repo_path)
.bind(&completion_action)
.bind(&req.continue_from_task_id)
.bind(©_files_json)
.bind(&req.branched_from_task_id)
.bind(&req.conversation_history)
.bind(&req.supervisor_worktree_task_id)
.bind(&req.directive_id)
.bind(&req.directive_step_id)
.fetch_one(pool)
.await
}
/// Get a task by ID, scoped to owner.
pub async fn get_task_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<Option<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
SELECT *
FROM tasks
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// List all top-level tasks (no parent) for an owner, ordered by created_at DESC.
/// Hidden tasks are excluded by default.
pub async fn list_tasks_for_owner(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<TaskSummary>, sqlx::Error> {
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.owner_id = $1 AND t.parent_task_id IS NULL AND COALESCE(t.hidden, false) = false
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// List subtasks of a parent task, scoped to owner.
pub async fn list_subtasks_for_owner(
pool: &PgPool,
parent_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<TaskSummary>, sqlx::Error> {
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.owner_id = $1 AND t.parent_task_id = $2
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.bind(owner_id)
.bind(parent_id)
.fetch_all(pool)
.await
}
/// Update a task by ID with optimistic locking, scoped to owner.
pub async fn update_task_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
req: UpdateTaskRequest,
) -> Result<Option<Task>, RepositoryError> {
// Get the existing task first (scoped to owner)
let existing = get_task_for_owner(pool, id, owner_id).await?;
let Some(existing) = existing else {
return Ok(None);
};
// Check version if provided (optimistic locking)
if let Some(expected_version) = req.version {
if existing.version != expected_version {
return Err(RepositoryError::VersionConflict {
expected: expected_version,
actual: existing.version,
});
}
}
// Apply updates
let name = req.name.unwrap_or(existing.name);
let description = req.description.or(existing.description);
let plan = req.plan.unwrap_or(existing.plan);
let status = req.status.unwrap_or(existing.status);
let priority = req.priority.unwrap_or(existing.priority);
let progress_summary = req.progress_summary.or(existing.progress_summary);
let last_output = req.last_output.or(existing.last_output);
let error_message = req.error_message.or(existing.error_message);
let merge_mode = req.merge_mode.or(existing.merge_mode);
let pr_url = req.pr_url.or(existing.pr_url);
let repository_url = req.repository_url.or(existing.repository_url);
let target_repo_path = req.target_repo_path.or(existing.target_repo_path);
let completion_action = req.completion_action.or(existing.completion_action);
let hidden = req.hidden.unwrap_or(existing.hidden);
let daemon_id = if req.clear_daemon_id {
None
} else {
req.daemon_id.or(existing.daemon_id)
};
// Update with version check in WHERE clause for race condition safety
let result = if req.version.is_some() {
sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET name = $3, description = $4, plan = $5, status = $6, priority = $7,
progress_summary = $8, last_output = $9, error_message = $10,
merge_mode = $11, pr_url = $12, daemon_id = $13,
target_repo_path = $14, completion_action = $15, repository_url = $16,
hidden = $17, updated_at = NOW()
WHERE id = $1 AND owner_id = $2 AND version = $18
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(&name)
.bind(&description)
.bind(&plan)
.bind(&status)
.bind(priority)
.bind(&progress_summary)
.bind(&last_output)
.bind(&error_message)
.bind(&merge_mode)
.bind(&pr_url)
.bind(daemon_id)
.bind(&target_repo_path)
.bind(&completion_action)
.bind(&repository_url)
.bind(hidden)
.bind(req.version.unwrap())
.fetch_optional(pool)
.await?
} else {
sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET name = $3, description = $4, plan = $5, status = $6, priority = $7,
progress_summary = $8, last_output = $9, error_message = $10,
merge_mode = $11, pr_url = $12, daemon_id = $13,
target_repo_path = $14, completion_action = $15, repository_url = $16,
hidden = $17, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(&name)
.bind(&description)
.bind(&plan)
.bind(&status)
.bind(priority)
.bind(&progress_summary)
.bind(&last_output)
.bind(&error_message)
.bind(&merge_mode)
.bind(&pr_url)
.bind(daemon_id)
.bind(&target_repo_path)
.bind(&completion_action)
.bind(&repository_url)
.bind(hidden)
.fetch_optional(pool)
.await?
};
// If versioned update returned None, there was a race condition
if result.is_none() && req.version.is_some() {
if let Some(current) = get_task_for_owner(pool, id, owner_id).await? {
return Err(RepositoryError::VersionConflict {
expected: req.version.unwrap(),
actual: current.version,
});
}
}
Ok(result)
}
/// Delete a task by ID, scoped to owner.
pub async fn delete_task_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM tasks
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Update task status and record event.
pub async fn update_task_status(
pool: &PgPool,
id: Uuid,
new_status: &str,
event_data: Option<serde_json::Value>,
) -> Result<Option<Task>, sqlx::Error> {
// Get existing status
let existing = get_task(pool, id).await?;
let Some(existing) = existing else {
return Ok(None);
};
let previous_status = existing.status.clone();
// Update task status
let task = sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET status = $2, updated_at = NOW(),
started_at = CASE WHEN $2 = 'running' AND started_at IS NULL THEN NOW() ELSE started_at END,
completed_at = CASE WHEN $2 IN ('done', 'failed', 'merged') THEN NOW() ELSE completed_at END
WHERE id = $1
RETURNING *
"#,
)
.bind(id)
.bind(new_status)
.fetch_optional(pool)
.await?;
// Record event
if task.is_some() {
let _ = create_task_event(
pool,
id,
"status_change",
Some(&previous_status),
Some(new_status),
event_data,
)
.await;
}
Ok(task)
}
// =============================================================================
// Task Event Functions
// =============================================================================
/// Create a task event.
pub async fn create_task_event(
pool: &PgPool,
task_id: Uuid,
event_type: &str,
previous_status: Option<&str>,
new_status: Option<&str>,
event_data: Option<serde_json::Value>,
) -> Result<TaskEvent, sqlx::Error> {
sqlx::query_as::<_, TaskEvent>(
r#"
INSERT INTO task_events (task_id, event_type, previous_status, new_status, event_data)
VALUES ($1, $2, $3, $4, $5)
RETURNING *
"#,
)
.bind(task_id)
.bind(event_type)
.bind(previous_status)
.bind(new_status)
.bind(event_data)
.fetch_one(pool)
.await
}
/// List events for a task.
pub async fn list_task_events(
pool: &PgPool,
task_id: Uuid,
limit: Option<i64>,
) -> Result<Vec<TaskEvent>, sqlx::Error> {
let limit = limit.unwrap_or(100);
sqlx::query_as::<_, TaskEvent>(
r#"
SELECT *
FROM task_events
WHERE task_id = $1
ORDER BY created_at DESC
LIMIT $2
"#,
)
.bind(task_id)
.bind(limit)
.fetch_all(pool)
.await
}
// =============================================================================
// Daemon Functions
// =============================================================================
/// Register a new daemon connection.
pub async fn register_daemon(
pool: &PgPool,
owner_id: Uuid,
connection_id: &str,
hostname: Option<&str>,
machine_id: Option<&str>,
max_concurrent_tasks: i32,
) -> Result<Daemon, sqlx::Error> {
sqlx::query_as::<_, Daemon>(
r#"
INSERT INTO daemons (owner_id, connection_id, hostname, machine_id, max_concurrent_tasks)
VALUES ($1, $2, $3, $4, $5)
RETURNING *
"#,
)
.bind(owner_id)
.bind(connection_id)
.bind(hostname)
.bind(machine_id)
.bind(max_concurrent_tasks)
.fetch_one(pool)
.await
}
/// Get a daemon by ID.
pub async fn get_daemon(pool: &PgPool, id: Uuid) -> Result<Option<Daemon>, sqlx::Error> {
sqlx::query_as::<_, Daemon>(
r#"
SELECT *
FROM daemons
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await
}
/// Get a daemon by connection ID.
pub async fn get_daemon_by_connection(
pool: &PgPool,
connection_id: &str,
) -> Result<Option<Daemon>, sqlx::Error> {
sqlx::query_as::<_, Daemon>(
r#"
SELECT *
FROM daemons
WHERE connection_id = $1
"#,
)
.bind(connection_id)
.fetch_optional(pool)
.await
}
/// List all daemons.
pub async fn list_daemons(pool: &PgPool) -> Result<Vec<Daemon>, sqlx::Error> {
sqlx::query_as::<_, Daemon>(
r#"
SELECT *
FROM daemons
ORDER BY connected_at DESC
"#,
)
.fetch_all(pool)
.await
}
/// List daemons for a specific owner.
pub async fn list_daemons_for_owner(pool: &PgPool, owner_id: Uuid) -> Result<Vec<Daemon>, sqlx::Error> {
sqlx::query_as::<_, Daemon>(
r#"
SELECT *
FROM daemons
WHERE owner_id = $1
ORDER BY connected_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get a daemon by ID for a specific owner.
pub async fn get_daemon_for_owner(pool: &PgPool, id: Uuid, owner_id: Uuid) -> Result<Option<Daemon>, sqlx::Error> {
sqlx::query_as::<_, Daemon>(
r#"
SELECT *
FROM daemons
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Update daemon heartbeat.
pub async fn update_daemon_heartbeat(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE daemons
SET last_heartbeat_at = NOW(), status = 'connected'
WHERE id = $1
"#,
)
.bind(id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Update daemon status.
pub async fn update_daemon_status(
pool: &PgPool,
id: Uuid,
status: &str,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE daemons
SET status = $2,
disconnected_at = CASE WHEN $2 = 'disconnected' THEN NOW() ELSE disconnected_at END
WHERE id = $1
"#,
)
.bind(id)
.bind(status)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Mark daemon as disconnected by connection_id.
pub async fn disconnect_daemon_by_connection(
pool: &PgPool,
connection_id: &str,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE daemons
SET status = 'disconnected',
disconnected_at = NOW()
WHERE connection_id = $1
"#,
)
.bind(connection_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Update daemon task count.
pub async fn update_daemon_task_count(
pool: &PgPool,
id: Uuid,
delta: i32,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE daemons
SET current_task_count = GREATEST(0, current_task_count + $2)
WHERE id = $1
"#,
)
.bind(id)
.bind(delta)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Delete a daemon by ID.
pub async fn delete_daemon(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM daemons
WHERE id = $1
"#,
)
.bind(id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Delete a daemon by connection ID.
pub async fn delete_daemon_by_connection(
pool: &PgPool,
connection_id: &str,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM daemons
WHERE connection_id = $1
"#,
)
.bind(connection_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Count connected daemons.
pub async fn count_daemons(pool: &PgPool) -> Result<i64, sqlx::Error> {
let result: (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM daemons WHERE status = 'connected'",
)
.fetch_one(pool)
.await?;
Ok(result.0)
}
/// Delete stale daemons that haven't sent a heartbeat within the timeout.
/// Returns the number of deleted daemons.
pub async fn delete_stale_daemons(
pool: &PgPool,
timeout_seconds: i64,
) -> Result<u64, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM daemons
WHERE last_heartbeat_at < NOW() - INTERVAL '1 second' * $1
"#,
)
.bind(timeout_seconds)
.execute(pool)
.await?;
Ok(result.rows_affected())
}
// =============================================================================
// Sibling Awareness Functions
// =============================================================================
/// List sibling tasks (tasks with the same parent, excluding the given task).
pub async fn list_sibling_tasks(
pool: &PgPool,
task_id: Uuid,
parent_id: Option<Uuid>,
) -> Result<Vec<TaskSummary>, sqlx::Error> {
match parent_id {
Some(parent) => {
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.parent_task_id = $1 AND t.id != $2
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.bind(parent)
.bind(task_id)
.fetch_all(pool)
.await
}
None => {
// Top-level tasks (no parent) - siblings are other top-level tasks
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.parent_task_id IS NULL AND t.id != $1
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.bind(task_id)
.fetch_all(pool)
.await
}
}
}
/// Get running sibling tasks (for context injection).
pub async fn get_running_siblings(
pool: &PgPool,
owner_id: Uuid,
task_id: Uuid,
parent_id: Option<Uuid>,
) -> Result<Vec<Task>, sqlx::Error> {
match parent_id {
Some(parent) => {
sqlx::query_as::<_, Task>(
r#"
SELECT *
FROM tasks t
WHERE t.owner_id = $1
AND t.parent_task_id = $2
AND t.id != $3
AND t.status = 'running'
ORDER BY t.priority DESC
"#,
)
.bind(owner_id)
.bind(parent)
.bind(task_id)
.fetch_all(pool)
.await
}
None => {
sqlx::query_as::<_, Task>(
r#"
SELECT *
FROM tasks t
WHERE t.owner_id = $1
AND t.parent_task_id IS NULL
AND t.id != $2
AND t.status = 'running'
ORDER BY t.priority DESC
"#,
)
.bind(owner_id)
.bind(task_id)
.fetch_all(pool)
.await
}
}
}
/// Get task with its siblings for context awareness.
pub async fn get_task_with_siblings(
pool: &PgPool,
id: Uuid,
) -> Result<Option<(Task, Vec<TaskSummary>)>, sqlx::Error> {
let task = get_task(pool, id).await?;
let Some(task) = task else {
return Ok(None);
};
let siblings = list_sibling_tasks(pool, id, task.parent_task_id).await?;
Ok(Some((task, siblings)))
}
// =============================================================================
// Task Output Persistence Functions
// =============================================================================
/// Save task output to the database.
/// This stores output in the task_events table with event_type='output'.
pub async fn save_task_output(
pool: &PgPool,
task_id: Uuid,
message_type: &str,
content: &str,
tool_name: Option<&str>,
tool_input: Option<serde_json::Value>,
is_error: Option<bool>,
cost_usd: Option<f64>,
duration_ms: Option<u64>,
) -> Result<TaskEvent, sqlx::Error> {
let event_data = serde_json::json!({
"messageType": message_type,
"content": content,
"toolName": tool_name,
"toolInput": tool_input,
"isError": is_error,
"costUsd": cost_usd,
"durationMs": duration_ms,
});
create_task_event(pool, task_id, "output", None, None, Some(event_data)).await
}
/// Get task output from the database.
/// Retrieves all output events for a task, ordered by creation time.
pub async fn get_task_output(
pool: &PgPool,
task_id: Uuid,
limit: Option<i64>,
) -> Result<Vec<TaskEvent>, sqlx::Error> {
let limit = limit.unwrap_or(1000);
sqlx::query_as::<_, TaskEvent>(
r#"
SELECT *
FROM task_events
WHERE task_id = $1 AND event_type = 'output'
ORDER BY created_at ASC
LIMIT $2
"#,
)
.bind(task_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Update task completion status with error message.
/// Sets the task status to 'done' or 'failed' and records completion time.
pub async fn complete_task(
pool: &PgPool,
task_id: Uuid,
success: bool,
error_message: Option<&str>,
) -> Result<Option<Task>, sqlx::Error> {
let status = if success { "done" } else { "failed" };
let task = sqlx::query_as::<_, Task>(
r#"
UPDATE tasks
SET status = $2,
error_message = COALESCE($3, error_message),
completed_at = NOW(),
updated_at = NOW()
WHERE id = $1
RETURNING *
"#,
)
.bind(task_id)
.bind(status)
.bind(error_message)
.fetch_optional(pool)
.await?;
// Record completion event
if task.is_some() {
let event_data = serde_json::json!({
"success": success,
"errorMessage": error_message,
});
let _ = create_task_event(
pool,
task_id,
"complete",
Some("running"),
Some(status),
Some(event_data),
)
.await;
}
Ok(task)
}
// =============================================================================
// Mesh Chat History Functions
// =============================================================================
/// Get or create the active conversation for an owner.
pub async fn get_or_create_active_conversation(
pool: &PgPool,
owner_id: Uuid,
) -> Result<MeshChatConversation, sqlx::Error> {
// Try to get existing active conversation for this owner
let existing = sqlx::query_as::<_, MeshChatConversation>(
r#"
SELECT *
FROM mesh_chat_conversations
WHERE is_active = true AND owner_id = $1
LIMIT 1
"#,
)
.bind(owner_id)
.fetch_optional(pool)
.await?;
if let Some(conv) = existing {
return Ok(conv);
}
// Create new conversation
sqlx::query_as::<_, MeshChatConversation>(
r#"
INSERT INTO mesh_chat_conversations (owner_id, is_active)
VALUES ($1, true)
RETURNING *
"#,
)
.bind(owner_id)
.fetch_one(pool)
.await
}
/// List messages for a conversation.
pub async fn list_chat_messages(
pool: &PgPool,
conversation_id: Uuid,
limit: Option<i32>,
) -> Result<Vec<MeshChatMessageRecord>, sqlx::Error> {
let limit = limit.unwrap_or(100);
sqlx::query_as::<_, MeshChatMessageRecord>(
r#"
SELECT *
FROM mesh_chat_messages
WHERE conversation_id = $1
ORDER BY created_at ASC
LIMIT $2
"#,
)
.bind(conversation_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Add a message to a conversation.
#[allow(clippy::too_many_arguments)]
pub async fn add_chat_message(
pool: &PgPool,
conversation_id: Uuid,
role: &str,
content: &str,
context_type: &str,
context_task_id: Option<Uuid>,
tool_calls: Option<serde_json::Value>,
pending_questions: Option<serde_json::Value>,
) -> Result<MeshChatMessageRecord, sqlx::Error> {
sqlx::query_as::<_, MeshChatMessageRecord>(
r#"
INSERT INTO mesh_chat_messages
(conversation_id, role, content, context_type, context_task_id, tool_calls, pending_questions)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING *
"#,
)
.bind(conversation_id)
.bind(role)
.bind(content)
.bind(context_type)
.bind(context_task_id)
.bind(tool_calls)
.bind(pending_questions)
.fetch_one(pool)
.await
}
/// Clear conversation (archive existing and create new).
pub async fn clear_conversation(pool: &PgPool, owner_id: Uuid) -> Result<MeshChatConversation, sqlx::Error> {
// Mark existing as inactive for this owner
sqlx::query(
r#"
UPDATE mesh_chat_conversations
SET is_active = false, updated_at = NOW()
WHERE is_active = true AND owner_id = $1
"#,
)
.bind(owner_id)
.execute(pool)
.await?;
// Create new active conversation
get_or_create_active_conversation(pool, owner_id).await
}
// =============================================================================
// Contract Chat History Functions
// =============================================================================
/// Get or create the active conversation for a contract.
pub async fn get_or_create_contract_conversation(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<ContractChatConversation, sqlx::Error> {
// Try to get existing active conversation for this contract
let existing = sqlx::query_as::<_, ContractChatConversation>(
r#"
SELECT *
FROM contract_chat_conversations
WHERE is_active = true AND contract_id = $1 AND owner_id = $2
LIMIT 1
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_optional(pool)
.await?;
if let Some(conv) = existing {
return Ok(conv);
}
// Create new conversation
sqlx::query_as::<_, ContractChatConversation>(
r#"
INSERT INTO contract_chat_conversations (contract_id, owner_id, is_active)
VALUES ($1, $2, true)
RETURNING *
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_one(pool)
.await
}
/// List messages for a contract conversation.
pub async fn list_contract_chat_messages(
pool: &PgPool,
conversation_id: Uuid,
limit: Option<i32>,
) -> Result<Vec<ContractChatMessageRecord>, sqlx::Error> {
let limit = limit.unwrap_or(100);
sqlx::query_as::<_, ContractChatMessageRecord>(
r#"
SELECT *
FROM contract_chat_messages
WHERE conversation_id = $1
ORDER BY created_at ASC
LIMIT $2
"#,
)
.bind(conversation_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Add a message to a contract conversation.
pub async fn add_contract_chat_message(
pool: &PgPool,
conversation_id: Uuid,
role: &str,
content: &str,
tool_calls: Option<serde_json::Value>,
pending_questions: Option<serde_json::Value>,
) -> Result<ContractChatMessageRecord, sqlx::Error> {
sqlx::query_as::<_, ContractChatMessageRecord>(
r#"
INSERT INTO contract_chat_messages
(conversation_id, role, content, tool_calls, pending_questions)
VALUES ($1, $2, $3, $4, $5)
RETURNING *
"#,
)
.bind(conversation_id)
.bind(role)
.bind(content)
.bind(tool_calls)
.bind(pending_questions)
.fetch_one(pool)
.await
}
/// Clear contract conversation (archive existing and create new).
pub async fn clear_contract_conversation(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<ContractChatConversation, sqlx::Error> {
// Mark existing as inactive for this contract
sqlx::query(
r#"
UPDATE contract_chat_conversations
SET is_active = false, updated_at = NOW()
WHERE is_active = true AND contract_id = $1 AND owner_id = $2
"#,
)
.bind(contract_id)
.bind(owner_id)
.execute(pool)
.await?;
// Create new active conversation
get_or_create_contract_conversation(pool, contract_id, owner_id).await
}
// =============================================================================
// Contract Type Template Functions (Owner-Scoped)
// =============================================================================
/// Create a new contract type template for a specific owner.
pub async fn create_template_for_owner(
pool: &PgPool,
owner_id: Uuid,
req: CreateTemplateRequest,
) -> Result<ContractTypeTemplateRecord, sqlx::Error> {
sqlx::query_as::<_, ContractTypeTemplateRecord>(
r#"
INSERT INTO contract_type_templates (owner_id, name, description, phases, default_phase, deliverables)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *
"#,
)
.bind(owner_id)
.bind(&req.name)
.bind(&req.description)
.bind(serde_json::to_value(&req.phases).unwrap_or_default())
.bind(&req.default_phase)
.bind(match &req.deliverables {
Some(d) => serde_json::to_value(d).ok(),
None => None,
})
.fetch_one(pool)
.await
}
/// Get a contract type template by ID, scoped to owner.
pub async fn get_template_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<Option<ContractTypeTemplateRecord>, sqlx::Error> {
sqlx::query_as::<_, ContractTypeTemplateRecord>(
r#"
SELECT *
FROM contract_type_templates
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Get a contract type template by ID (internal use, no owner scoping).
pub async fn get_template_by_id(
pool: &PgPool,
id: Uuid,
) -> Result<Option<ContractTypeTemplateRecord>, sqlx::Error> {
sqlx::query_as::<_, ContractTypeTemplateRecord>(
r#"
SELECT *
FROM contract_type_templates
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await
}
/// List all contract type templates for an owner, ordered by name.
pub async fn list_templates_for_owner(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<ContractTypeTemplateRecord>, sqlx::Error> {
sqlx::query_as::<_, ContractTypeTemplateRecord>(
r#"
SELECT *
FROM contract_type_templates
WHERE owner_id = $1
ORDER BY name ASC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Update a contract type template for an owner.
pub async fn update_template_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
req: UpdateTemplateRequest,
) -> Result<Option<ContractTypeTemplateRecord>, RepositoryError> {
// Build dynamic update query
let mut query = String::from("UPDATE contract_type_templates SET updated_at = NOW()");
let mut param_idx = 3; // $1 = id, $2 = owner_id
if req.name.is_some() {
query.push_str(&format!(", name = ${}", param_idx));
param_idx += 1;
}
if req.description.is_some() {
query.push_str(&format!(", description = ${}", param_idx));
param_idx += 1;
}
if req.phases.is_some() {
query.push_str(&format!(", phases = ${}", param_idx));
param_idx += 1;
}
if req.default_phase.is_some() {
query.push_str(&format!(", default_phase = ${}", param_idx));
param_idx += 1;
}
if req.deliverables.is_some() {
query.push_str(&format!(", deliverables = ${}", param_idx));
param_idx += 1;
}
// Optimistic locking
if req.version.is_some() {
query.push_str(&format!(", version = version + 1 WHERE id = $1 AND owner_id = $2 AND version = ${}", param_idx));
} else {
query.push_str(", version = version + 1 WHERE id = $1 AND owner_id = $2");
}
query.push_str(" RETURNING *");
let mut sql_query = sqlx::query_as::<_, ContractTypeTemplateRecord>(&query);
sql_query = sql_query.bind(id).bind(owner_id);
if let Some(ref name) = req.name {
sql_query = sql_query.bind(name);
}
if let Some(ref description) = req.description {
sql_query = sql_query.bind(description);
}
if let Some(ref phases) = req.phases {
sql_query = sql_query.bind(serde_json::to_value(phases).unwrap_or_default());
}
if let Some(ref default_phase) = req.default_phase {
sql_query = sql_query.bind(default_phase);
}
if let Some(ref deliverables) = req.deliverables {
sql_query = sql_query.bind(serde_json::to_value(deliverables).unwrap_or_default());
}
if let Some(version) = req.version {
sql_query = sql_query.bind(version);
}
match sql_query.fetch_optional(pool).await {
Ok(result) => {
if result.is_none() && req.version.is_some() {
// Check if it's a version conflict
if let Some(current) = get_template_for_owner(pool, id, owner_id).await? {
return Err(RepositoryError::VersionConflict {
expected: req.version.unwrap(),
actual: current.version,
});
}
}
Ok(result)
}
Err(e) => Err(RepositoryError::Database(e)),
}
}
/// Delete a contract type template for an owner.
pub async fn delete_template_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM contract_type_templates
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Helper function to build PhaseConfig from a template.
pub fn build_phase_config_from_template(template: &ContractTypeTemplateRecord) -> PhaseConfig {
PhaseConfig {
phases: template.phases.clone(),
default_phase: template.default_phase.clone(),
deliverables: template.deliverables.clone().unwrap_or_default(),
}
}
/// Helper function to build PhaseConfig for built-in contract types.
pub fn build_phase_config_for_builtin(contract_type: &str) -> PhaseConfig {
match contract_type {
"simple" => PhaseConfig {
phases: vec![
PhaseDefinition { id: "plan".to_string(), name: "Plan".to_string(), order: 0 },
PhaseDefinition { id: "execute".to_string(), name: "Execute".to_string(), order: 1 },
],
default_phase: "plan".to_string(),
deliverables: [
("plan".to_string(), vec![DeliverableDefinition {
id: "plan-document".to_string(),
name: "Plan".to_string(),
priority: "required".to_string(),
}]),
("execute".to_string(), vec![DeliverableDefinition {
id: "pull-request".to_string(),
name: "Pull Request".to_string(),
priority: "required".to_string(),
}]),
].into_iter().collect(),
},
"specification" => PhaseConfig {
phases: vec![
PhaseDefinition { id: "research".to_string(), name: "Research".to_string(), order: 0 },
PhaseDefinition { id: "specify".to_string(), name: "Specify".to_string(), order: 1 },
PhaseDefinition { id: "plan".to_string(), name: "Plan".to_string(), order: 2 },
PhaseDefinition { id: "execute".to_string(), name: "Execute".to_string(), order: 3 },
PhaseDefinition { id: "review".to_string(), name: "Review".to_string(), order: 4 },
],
default_phase: "research".to_string(),
deliverables: [
("research".to_string(), vec![DeliverableDefinition {
id: "research-notes".to_string(),
name: "Research Notes".to_string(),
priority: "required".to_string(),
}]),
("specify".to_string(), vec![DeliverableDefinition {
id: "requirements-document".to_string(),
name: "Requirements Document".to_string(),
priority: "required".to_string(),
}]),
("plan".to_string(), vec![DeliverableDefinition {
id: "plan-document".to_string(),
name: "Plan".to_string(),
priority: "required".to_string(),
}]),
("execute".to_string(), vec![DeliverableDefinition {
id: "pull-request".to_string(),
name: "Pull Request".to_string(),
priority: "required".to_string(),
}]),
("review".to_string(), vec![DeliverableDefinition {
id: "release-notes".to_string(),
name: "Release Notes".to_string(),
priority: "required".to_string(),
}]),
].into_iter().collect(),
},
"execute" | _ => PhaseConfig {
phases: vec![
PhaseDefinition { id: "execute".to_string(), name: "Execute".to_string(), order: 0 },
],
default_phase: "execute".to_string(),
deliverables: std::collections::HashMap::new(),
},
}
}
// =============================================================================
// Contract Functions (Owner-Scoped)
// =============================================================================
/// Create a new contract for a specific owner.
/// Supports both built-in contract types (simple, specification, execute) and custom templates.
pub async fn create_contract_for_owner(
pool: &PgPool,
owner_id: Uuid,
req: CreateContractRequest,
) -> Result<Contract, sqlx::Error> {
// Determine phase configuration based on template_id or contract_type
let (phase_config, contract_type_str, default_phase): (PhaseConfig, String, String) =
if let Some(template_id) = req.template_id {
// Look up the custom template
let template = get_template_by_id(pool, template_id)
.await?
.ok_or_else(|| {
sqlx::Error::Protocol(format!("Template not found: {}", template_id))
})?;
let config = build_phase_config_from_template(&template);
let default = config.default_phase.clone();
// For custom templates, store the template name as the contract_type
(config, template.name.clone(), default)
} else {
// Use built-in contract type
let contract_type = req.contract_type.as_deref().unwrap_or("simple");
// Validate contract type
let valid_types = ["simple", "specification", "execute"];
if !valid_types.contains(&contract_type) {
return Err(sqlx::Error::Protocol(format!(
"Invalid contract_type '{}'. Must be one of: {} or provide a template_id",
contract_type,
valid_types.join(", ")
)));
}
let config = build_phase_config_for_builtin(contract_type);
let default = config.default_phase.clone();
(config, contract_type.to_string(), default)
};
// Get valid phase IDs from the configuration
let valid_phase_ids: Vec<String> = phase_config.phases.iter().map(|p| p.id.clone()).collect();
// Use provided initial_phase or default based on contract type/template
let phase = req.initial_phase.as_deref().unwrap_or(&default_phase);
// Validate the phase is valid for this contract type/template
if !valid_phase_ids.contains(&phase.to_string()) {
return Err(sqlx::Error::Protocol(format!(
"Invalid initial_phase '{}' for contract type '{}'. Must be one of: {}",
phase,
contract_type_str,
valid_phase_ids.join(", ")
)));
}
let autonomous_loop = req.autonomous_loop.unwrap_or(false);
let phase_guard = req.phase_guard.unwrap_or(false);
let local_only = req.local_only.unwrap_or(false);
let auto_merge_local = req.auto_merge_local.unwrap_or(false);
// Serialize phase_config to JSON
let phase_config_json = serde_json::to_value(&phase_config).ok();
sqlx::query_as::<_, Contract>(
r#"
INSERT INTO contracts (owner_id, name, description, contract_type, phase, autonomous_loop, phase_guard, local_only, auto_merge_local, phase_config)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING *
"#,
)
.bind(owner_id)
.bind(&req.name)
.bind(&req.description)
.bind(&contract_type_str)
.bind(phase)
.bind(autonomous_loop)
.bind(phase_guard)
.bind(local_only)
.bind(auto_merge_local)
.bind(phase_config_json)
.fetch_one(pool)
.await
}
/// Get a contract by ID, scoped to owner.
pub async fn get_contract_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<Option<Contract>, sqlx::Error> {
sqlx::query_as::<_, Contract>(
r#"
SELECT *
FROM contracts
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// List all contracts for an owner, ordered by created_at DESC.
pub async fn list_contracts_for_owner(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<ContractSummary>, sqlx::Error> {
sqlx::query_as::<_, ContractSummary>(
r#"
SELECT
c.id, c.name, c.description, c.contract_type, c.phase, c.status,
c.supervisor_task_id, c.local_only, c.auto_merge_local, c.version, c.created_at,
(SELECT COUNT(*) FROM files WHERE contract_id = c.id) as file_count,
(SELECT COUNT(*) FROM tasks WHERE contract_id = c.id) as task_count,
(SELECT COUNT(*) FROM contract_repositories WHERE contract_id = c.id) as repository_count
FROM contracts c
WHERE c.owner_id = $1
ORDER BY c.created_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get contract summary by ID.
pub async fn get_contract_summary_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<Option<ContractSummary>, sqlx::Error> {
sqlx::query_as::<_, ContractSummary>(
r#"
SELECT
c.id, c.name, c.description, c.contract_type, c.phase, c.status,
c.supervisor_task_id, c.local_only, c.auto_merge_local, c.version, c.created_at,
(SELECT COUNT(*) FROM files WHERE contract_id = c.id) as file_count,
(SELECT COUNT(*) FROM tasks WHERE contract_id = c.id) as task_count,
(SELECT COUNT(*) FROM contract_repositories WHERE contract_id = c.id) as repository_count
FROM contracts c
WHERE c.id = $1 AND c.owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Update a contract by ID with optimistic locking, scoped to owner.
pub async fn update_contract_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
req: UpdateContractRequest,
) -> Result<Option<Contract>, RepositoryError> {
let existing = get_contract_for_owner(pool, id, owner_id).await?;
let Some(existing) = existing else {
return Ok(None);
};
// Check version if provided (optimistic locking)
if let Some(expected_version) = req.version {
if existing.version != expected_version {
return Err(RepositoryError::VersionConflict {
expected: expected_version,
actual: existing.version,
});
}
}
// Apply updates
let name = req.name.unwrap_or(existing.name);
let description = req.description.or(existing.description);
let phase = req.phase.unwrap_or(existing.phase);
let status = req.status.unwrap_or(existing.status);
let supervisor_task_id = req.supervisor_task_id.or(existing.supervisor_task_id);
let autonomous_loop = req.autonomous_loop.unwrap_or(existing.autonomous_loop);
let phase_guard = req.phase_guard.unwrap_or(existing.phase_guard);
let local_only = req.local_only.unwrap_or(existing.local_only);
let auto_merge_local = req.auto_merge_local.unwrap_or(existing.auto_merge_local);
let result = if req.version.is_some() {
sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET name = $3, description = $4, phase = $5, status = $6,
supervisor_task_id = $7, autonomous_loop = $8, phase_guard = $9, local_only = $10, auto_merge_local = $11, version = version + 1, updated_at = NOW()
WHERE id = $1 AND owner_id = $2 AND version = $12
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(&name)
.bind(&description)
.bind(&phase)
.bind(&status)
.bind(supervisor_task_id)
.bind(autonomous_loop)
.bind(phase_guard)
.bind(local_only)
.bind(auto_merge_local)
.bind(req.version.unwrap())
.fetch_optional(pool)
.await?
} else {
sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET name = $3, description = $4, phase = $5, status = $6,
supervisor_task_id = $7, autonomous_loop = $8, phase_guard = $9, local_only = $10, auto_merge_local = $11, version = version + 1, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(&name)
.bind(&description)
.bind(&phase)
.bind(&status)
.bind(supervisor_task_id)
.bind(autonomous_loop)
.bind(phase_guard)
.bind(local_only)
.bind(auto_merge_local)
.fetch_optional(pool)
.await?
};
// If versioned update returned None, there was a race condition
if result.is_none() && req.version.is_some() {
if let Some(current) = get_contract_for_owner(pool, id, owner_id).await? {
return Err(RepositoryError::VersionConflict {
expected: req.version.unwrap(),
actual: current.version,
});
}
}
Ok(result)
}
/// Delete a contract by ID, scoped to owner.
pub async fn delete_contract_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM contracts
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Change contract phase and record event.
///
/// This is the simple version without version checking. Use `change_contract_phase_with_version`
/// for explicit version conflict detection.
pub async fn change_contract_phase_for_owner(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
new_phase: &str,
) -> Result<Option<Contract>, sqlx::Error> {
// Get current phase
let existing = get_contract_for_owner(pool, id, owner_id).await?;
let Some(existing) = existing else {
return Ok(None);
};
let previous_phase = existing.phase.clone();
// Update phase
let contract = sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET phase = $3, version = version + 1, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(new_phase)
.fetch_optional(pool)
.await?;
// Record event
if contract.is_some() {
sqlx::query(
r#"
INSERT INTO contract_events (contract_id, event_type, previous_phase, new_phase)
VALUES ($1, 'phase_change', $2, $3)
"#,
)
.bind(id)
.bind(&previous_phase)
.bind(new_phase)
.execute(pool)
.await?;
}
Ok(contract)
}
/// Change contract phase with explicit version checking for conflict detection.
///
/// Uses `SELECT ... FOR UPDATE` to lock the row and prevent race conditions.
/// Returns `PhaseChangeResult::VersionConflict` if the expected version doesn't match.
pub async fn change_contract_phase_with_version(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
new_phase: &str,
expected_version: Option<i32>,
) -> Result<PhaseChangeResult, sqlx::Error> {
// Start a transaction to ensure atomicity with row locking
let mut tx = pool.begin().await?;
// Lock the row with SELECT FOR UPDATE and get current state
let existing: Option<Contract> = sqlx::query_as::<_, Contract>(
r#"
SELECT *
FROM contracts
WHERE id = $1 AND owner_id = $2
FOR UPDATE
"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(&mut *tx)
.await?;
let Some(existing) = existing else {
tx.rollback().await?;
return Ok(PhaseChangeResult::NotFound);
};
// Check version if provided (optimistic locking)
if let Some(expected) = expected_version {
if existing.version != expected {
tx.rollback().await?;
return Ok(PhaseChangeResult::VersionConflict {
expected,
actual: existing.version,
current_phase: existing.phase,
});
}
}
// Validate the phase transition is allowed
let valid_phases = existing.valid_phase_ids();
if !valid_phases.contains(&new_phase.to_string()) {
tx.rollback().await?;
return Ok(PhaseChangeResult::ValidationFailed {
reason: format!(
"Invalid phase '{}' for contract type '{}'",
new_phase, existing.contract_type
),
missing_requirements: vec![format!(
"Phase must be one of: {}",
valid_phases.join(", ")
)],
});
}
let previous_phase = existing.phase.clone();
// Update phase with version increment
let contract = sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET phase = $3, version = version + 1, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(new_phase)
.fetch_one(&mut *tx)
.await?;
// Record event
sqlx::query(
r#"
INSERT INTO contract_events (contract_id, event_type, previous_phase, new_phase)
VALUES ($1, 'phase_change', $2, $3)
"#,
)
.bind(id)
.bind(&previous_phase)
.bind(new_phase)
.execute(&mut *tx)
.await?;
// Commit the transaction
tx.commit().await?;
Ok(PhaseChangeResult::Success(contract))
}
// =============================================================================
// Contract Repository Functions
// =============================================================================
/// List repositories for a contract.
pub async fn list_contract_repositories(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Vec<ContractRepository>, sqlx::Error> {
sqlx::query_as::<_, ContractRepository>(
r#"
SELECT *
FROM contract_repositories
WHERE contract_id = $1
ORDER BY is_primary DESC, created_at ASC
"#,
)
.bind(contract_id)
.fetch_all(pool)
.await
}
/// Add a remote repository to a contract.
pub async fn add_remote_repository(
pool: &PgPool,
contract_id: Uuid,
name: &str,
repository_url: &str,
is_primary: bool,
) -> Result<ContractRepository, sqlx::Error> {
// If is_primary, clear other primaries first
if is_primary {
sqlx::query(
r#"
UPDATE contract_repositories
SET is_primary = false, updated_at = NOW()
WHERE contract_id = $1 AND is_primary = true
"#,
)
.bind(contract_id)
.execute(pool)
.await?;
}
sqlx::query_as::<_, ContractRepository>(
r#"
INSERT INTO contract_repositories (contract_id, name, repository_url, source_type, status, is_primary)
VALUES ($1, $2, $3, 'remote', 'ready', $4)
RETURNING *
"#,
)
.bind(contract_id)
.bind(name)
.bind(repository_url)
.bind(is_primary)
.fetch_one(pool)
.await
}
/// Add a local repository to a contract.
pub async fn add_local_repository(
pool: &PgPool,
contract_id: Uuid,
name: &str,
local_path: &str,
is_primary: bool,
) -> Result<ContractRepository, sqlx::Error> {
// If is_primary, clear other primaries first
if is_primary {
sqlx::query(
r#"
UPDATE contract_repositories
SET is_primary = false, updated_at = NOW()
WHERE contract_id = $1 AND is_primary = true
"#,
)
.bind(contract_id)
.execute(pool)
.await?;
}
sqlx::query_as::<_, ContractRepository>(
r#"
INSERT INTO contract_repositories (contract_id, name, local_path, source_type, status, is_primary)
VALUES ($1, $2, $3, 'local', 'ready', $4)
RETURNING *
"#,
)
.bind(contract_id)
.bind(name)
.bind(local_path)
.bind(is_primary)
.fetch_one(pool)
.await
}
/// Create a managed repository (daemon will create it).
pub async fn create_managed_repository(
pool: &PgPool,
contract_id: Uuid,
name: &str,
is_primary: bool,
) -> Result<ContractRepository, sqlx::Error> {
// If is_primary, clear other primaries first
if is_primary {
sqlx::query(
r#"
UPDATE contract_repositories
SET is_primary = false, updated_at = NOW()
WHERE contract_id = $1 AND is_primary = true
"#,
)
.bind(contract_id)
.execute(pool)
.await?;
}
sqlx::query_as::<_, ContractRepository>(
r#"
INSERT INTO contract_repositories (contract_id, name, source_type, status, is_primary)
VALUES ($1, $2, 'managed', 'pending', $3)
RETURNING *
"#,
)
.bind(contract_id)
.bind(name)
.bind(is_primary)
.fetch_one(pool)
.await
}
/// Delete a repository from a contract.
pub async fn delete_contract_repository(
pool: &PgPool,
repo_id: Uuid,
contract_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM contract_repositories
WHERE id = $1 AND contract_id = $2
"#,
)
.bind(repo_id)
.bind(contract_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Set a repository as primary (and clear others).
pub async fn set_repository_primary(
pool: &PgPool,
repo_id: Uuid,
contract_id: Uuid,
) -> Result<bool, sqlx::Error> {
// Clear other primaries
sqlx::query(
r#"
UPDATE contract_repositories
SET is_primary = false, updated_at = NOW()
WHERE contract_id = $1 AND is_primary = true
"#,
)
.bind(contract_id)
.execute(pool)
.await?;
// Set this one as primary
let result = sqlx::query(
r#"
UPDATE contract_repositories
SET is_primary = true, updated_at = NOW()
WHERE id = $1 AND contract_id = $2
"#,
)
.bind(repo_id)
.bind(contract_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Update managed repository status (used by daemon).
pub async fn update_managed_repository_status(
pool: &PgPool,
repo_id: Uuid,
status: &str,
repository_url: Option<&str>,
) -> Result<Option<ContractRepository>, sqlx::Error> {
sqlx::query_as::<_, ContractRepository>(
r#"
UPDATE contract_repositories
SET status = $2, repository_url = COALESCE($3, repository_url), updated_at = NOW()
WHERE id = $1
RETURNING *
"#,
)
.bind(repo_id)
.bind(status)
.bind(repository_url)
.fetch_optional(pool)
.await
}
// =============================================================================
// Contract Task Association Functions
// =============================================================================
/// Add a task to a contract.
pub async fn add_task_to_contract(
pool: &PgPool,
contract_id: Uuid,
task_id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE tasks
SET contract_id = $2, updated_at = NOW()
WHERE id = $1 AND owner_id = $3
"#,
)
.bind(task_id)
.bind(contract_id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Remove a task from a contract.
pub async fn remove_task_from_contract(
pool: &PgPool,
contract_id: Uuid,
task_id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE tasks
SET contract_id = NULL, updated_at = NOW()
WHERE id = $1 AND contract_id = $2 AND owner_id = $3
"#,
)
.bind(task_id)
.bind(contract_id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// List files in a contract.
pub async fn list_files_in_contract(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<FileSummary>, sqlx::Error> {
// Use a manual query since FileSummary doesn't have a FromRow derive with all the computed fields
let files = sqlx::query_as::<_, File>(
r#"
SELECT id, owner_id, contract_id, contract_phase, name, description, transcript, location, summary, body, version, repo_file_path, repo_synced_at, repo_sync_status, created_at, updated_at
FROM files
WHERE contract_id = $1 AND owner_id = $2
ORDER BY created_at DESC
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_all(pool)
.await?;
Ok(files.into_iter().map(FileSummary::from).collect())
}
/// List tasks in a contract.
pub async fn list_tasks_in_contract(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<TaskSummary>, sqlx::Error> {
sqlx::query_as::<_, TaskSummary>(
r#"
SELECT
t.id, t.contract_id, c.name as contract_name, c.phase as contract_phase,
c.status as contract_status,
t.parent_task_id, t.depth, t.name, t.status, t.priority,
t.progress_summary,
(SELECT COUNT(*) FROM tasks WHERE parent_task_id = t.id) as subtask_count,
t.version, t.is_supervisor, COALESCE(t.hidden, false) as hidden, t.created_at, t.updated_at
FROM tasks t
LEFT JOIN contracts c ON t.contract_id = c.id
WHERE t.contract_id = $1 AND t.owner_id = $2
ORDER BY t.priority DESC, t.created_at DESC
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Minimal task info for worktree cleanup operations.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct TaskWorktreeInfo {
pub id: Uuid,
pub daemon_id: Option<Uuid>,
pub overlay_path: Option<String>,
/// If set, this task shares the worktree of the specified supervisor task.
/// Should NOT have its worktree deleted during cleanup.
pub supervisor_worktree_task_id: Option<Uuid>,
}
/// List tasks in a contract with their daemon/worktree info.
/// Used for cleaning up worktrees when a contract is completed or deleted.
pub async fn list_contract_tasks_with_worktree_info(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Vec<TaskWorktreeInfo>, sqlx::Error> {
sqlx::query_as::<_, TaskWorktreeInfo>(
r#"
SELECT id, daemon_id, overlay_path, supervisor_worktree_task_id
FROM tasks
WHERE contract_id = $1 AND (daemon_id IS NOT NULL OR overlay_path IS NOT NULL)
"#,
)
.bind(contract_id)
.fetch_all(pool)
.await
}
// =============================================================================
// Contract Events
// =============================================================================
/// List events for a contract.
pub async fn list_contract_events(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Vec<ContractEvent>, sqlx::Error> {
sqlx::query_as::<_, ContractEvent>(
r#"
SELECT *
FROM contract_events
WHERE contract_id = $1
ORDER BY created_at DESC
"#,
)
.bind(contract_id)
.fetch_all(pool)
.await
}
/// Record a contract event.
pub async fn record_contract_event(
pool: &PgPool,
contract_id: Uuid,
event_type: &str,
event_data: Option<serde_json::Value>,
) -> Result<ContractEvent, sqlx::Error> {
sqlx::query_as::<_, ContractEvent>(
r#"
INSERT INTO contract_events (contract_id, event_type, event_data)
VALUES ($1, $2, $3)
RETURNING *
"#,
)
.bind(contract_id)
.bind(event_type)
.bind(event_data)
.fetch_one(pool)
.await
}
// ============================================================================
// Task Checkpoints
// ============================================================================
/// Create a checkpoint for a task.
pub async fn create_task_checkpoint(
pool: &PgPool,
task_id: Uuid,
commit_sha: &str,
branch_name: &str,
message: &str,
files_changed: Option<serde_json::Value>,
lines_added: Option<i32>,
lines_removed: Option<i32>,
) -> Result<TaskCheckpoint, sqlx::Error> {
// Get current checkpoint count and increment
let checkpoint_number: i32 = sqlx::query_scalar(
"SELECT COALESCE(MAX(checkpoint_number), 0) + 1 FROM task_checkpoints WHERE task_id = $1",
)
.bind(task_id)
.fetch_one(pool)
.await?;
// Update task's checkpoint tracking
sqlx::query(
r#"
UPDATE tasks
SET last_checkpoint_sha = $1,
checkpoint_count = $2,
checkpoint_message = $3,
updated_at = NOW()
WHERE id = $4
"#,
)
.bind(commit_sha)
.bind(checkpoint_number)
.bind(message)
.bind(task_id)
.execute(pool)
.await?;
sqlx::query_as::<_, TaskCheckpoint>(
r#"
INSERT INTO task_checkpoints (
task_id, checkpoint_number, commit_sha, branch_name, message,
files_changed, lines_added, lines_removed
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *
"#,
)
.bind(task_id)
.bind(checkpoint_number)
.bind(commit_sha)
.bind(branch_name)
.bind(message)
.bind(files_changed)
.bind(lines_added)
.bind(lines_removed)
.fetch_one(pool)
.await
}
/// Get a checkpoint by ID.
pub async fn get_task_checkpoint(
pool: &PgPool,
id: Uuid,
) -> Result<Option<TaskCheckpoint>, sqlx::Error> {
sqlx::query_as::<_, TaskCheckpoint>("SELECT * FROM task_checkpoints WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await
}
/// Get a checkpoint by commit SHA.
pub async fn get_task_checkpoint_by_sha(
pool: &PgPool,
commit_sha: &str,
) -> Result<Option<TaskCheckpoint>, sqlx::Error> {
sqlx::query_as::<_, TaskCheckpoint>("SELECT * FROM task_checkpoints WHERE commit_sha = $1")
.bind(commit_sha)
.fetch_optional(pool)
.await
}
/// List checkpoints for a task.
pub async fn list_task_checkpoints(
pool: &PgPool,
task_id: Uuid,
) -> Result<Vec<TaskCheckpoint>, sqlx::Error> {
sqlx::query_as::<_, TaskCheckpoint>(
"SELECT * FROM task_checkpoints WHERE task_id = $1 ORDER BY checkpoint_number DESC",
)
.bind(task_id)
.fetch_all(pool)
.await
}
// ============================================================================
// Supervisor State
// ============================================================================
/// Create or update supervisor state for a contract.
pub async fn upsert_supervisor_state(
pool: &PgPool,
contract_id: Uuid,
task_id: Uuid,
conversation_history: serde_json::Value,
pending_task_ids: &[Uuid],
phase: &str,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
INSERT INTO supervisor_states (contract_id, task_id, conversation_history, pending_task_ids, phase, last_activity)
VALUES ($1, $2, $3, $4, $5, NOW())
ON CONFLICT (contract_id) DO UPDATE SET
task_id = EXCLUDED.task_id,
conversation_history = EXCLUDED.conversation_history,
pending_task_ids = EXCLUDED.pending_task_ids,
phase = EXCLUDED.phase,
last_activity = NOW(),
updated_at = NOW()
RETURNING *
"#,
)
.bind(contract_id)
.bind(task_id)
.bind(conversation_history)
.bind(pending_task_ids)
.bind(phase)
.fetch_one(pool)
.await
}
/// Get supervisor state for a contract.
pub async fn get_supervisor_state(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Option<SupervisorState>, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>("SELECT * FROM supervisor_states WHERE contract_id = $1")
.bind(contract_id)
.fetch_optional(pool)
.await
}
/// Get supervisor state by task ID.
pub async fn get_supervisor_state_by_task(
pool: &PgPool,
task_id: Uuid,
) -> Result<Option<SupervisorState>, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>("SELECT * FROM supervisor_states WHERE task_id = $1")
.bind(task_id)
.fetch_optional(pool)
.await
}
/// Update supervisor conversation history.
pub async fn update_supervisor_conversation(
pool: &PgPool,
contract_id: Uuid,
conversation_history: serde_json::Value,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET conversation_history = $1,
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(conversation_history)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Update supervisor pending tasks.
pub async fn update_supervisor_pending_tasks(
pool: &PgPool,
contract_id: Uuid,
pending_task_ids: &[Uuid],
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET pending_task_ids = $1,
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(pending_task_ids)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Update supervisor state with detailed activity tracking.
/// Called at key save points: LLM response, task spawn, question asked, phase change.
pub async fn update_supervisor_detailed_state(
pool: &PgPool,
contract_id: Uuid,
state: &str,
current_activity: Option<&str>,
progress: i32,
error_message: Option<&str>,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET state = $1,
current_activity = $2,
progress = $3,
error_message = $4,
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $5
RETURNING *
"#,
)
.bind(state)
.bind(current_activity)
.bind(progress)
.bind(error_message)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Add a spawned task ID to the supervisor's list.
pub async fn add_supervisor_spawned_task(
pool: &PgPool,
contract_id: Uuid,
task_id: Uuid,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET spawned_task_ids = array_append(spawned_task_ids, $1),
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(task_id)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Add a pending question to the supervisor state.
pub async fn add_supervisor_pending_question(
pool: &PgPool,
contract_id: Uuid,
question: serde_json::Value,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET pending_questions = pending_questions || $1::jsonb,
state = 'waiting_for_user',
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(question)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Remove a pending question by ID.
pub async fn remove_supervisor_pending_question(
pool: &PgPool,
contract_id: Uuid,
question_id: Uuid,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET pending_questions = (
SELECT COALESCE(jsonb_agg(elem), '[]'::jsonb)
FROM jsonb_array_elements(pending_questions) elem
WHERE (elem->>'id')::uuid != $1
),
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(question_id)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Comprehensive state save - used at major save points.
pub async fn save_supervisor_state_full(
pool: &PgPool,
contract_id: Uuid,
task_id: Uuid,
conversation_history: serde_json::Value,
pending_task_ids: &[Uuid],
phase: &str,
state: &str,
current_activity: Option<&str>,
progress: i32,
error_message: Option<&str>,
spawned_task_ids: &[Uuid],
pending_questions: serde_json::Value,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
INSERT INTO supervisor_states (
contract_id, task_id, conversation_history, pending_task_ids, phase,
state, current_activity, progress, error_message, spawned_task_ids,
pending_questions, last_activity
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW())
ON CONFLICT (contract_id) DO UPDATE SET
task_id = EXCLUDED.task_id,
conversation_history = EXCLUDED.conversation_history,
pending_task_ids = EXCLUDED.pending_task_ids,
phase = EXCLUDED.phase,
state = EXCLUDED.state,
current_activity = EXCLUDED.current_activity,
progress = EXCLUDED.progress,
error_message = EXCLUDED.error_message,
spawned_task_ids = EXCLUDED.spawned_task_ids,
pending_questions = EXCLUDED.pending_questions,
last_activity = NOW(),
updated_at = NOW()
RETURNING *
"#,
)
.bind(contract_id)
.bind(task_id)
.bind(conversation_history)
.bind(pending_task_ids)
.bind(phase)
.bind(state)
.bind(current_activity)
.bind(progress)
.bind(error_message)
.bind(spawned_task_ids)
.bind(pending_questions)
.fetch_one(pool)
.await
}
/// Mark supervisor as restored from a crash/interruption.
pub async fn mark_supervisor_restored(
pool: &PgPool,
contract_id: Uuid,
restoration_source: &str,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET restoration_count = restoration_count + 1,
last_restored_at = NOW(),
restoration_source = $1,
state = 'initializing',
error_message = NULL,
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(restoration_source)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Get supervisors with pending questions (for re-delivery after restoration).
pub async fn get_supervisors_with_pending_questions(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<SupervisorState>, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
SELECT ss.*
FROM supervisor_states ss
JOIN contracts c ON c.id = ss.contract_id
WHERE c.owner_id = $1
AND ss.pending_questions != '[]'::jsonb
AND c.status = 'active'
ORDER BY ss.last_activity DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get supervisor state with full details for restoration.
/// Includes validation info.
pub async fn get_supervisor_state_for_restoration(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Option<SupervisorState>, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
SELECT * FROM supervisor_states WHERE contract_id = $1
"#,
)
.bind(contract_id)
.fetch_optional(pool)
.await
}
/// Validate spawned tasks are in expected states.
/// Returns map of task_id -> (status, updated_at).
pub async fn validate_spawned_tasks(
pool: &PgPool,
task_ids: &[Uuid],
) -> Result<std::collections::HashMap<Uuid, (String, chrono::DateTime<Utc>)>, sqlx::Error> {
use sqlx::Row;
let rows = sqlx::query(
r#"
SELECT id, status, updated_at
FROM tasks
WHERE id = ANY($1)
"#,
)
.bind(task_ids)
.fetch_all(pool)
.await?;
let mut result = std::collections::HashMap::new();
for row in rows {
let id: Uuid = row.get("id");
let status: String = row.get("status");
let updated_at: chrono::DateTime<Utc> = row.get("updated_at");
result.insert(id, (status, updated_at));
}
Ok(result)
}
/// Update supervisor state when phase changes.
pub async fn update_supervisor_phase(
pool: &PgPool,
contract_id: Uuid,
new_phase: &str,
) -> Result<SupervisorState, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET phase = $1,
state = 'working',
current_activity = 'Phase changed to ' || $1,
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $2
RETURNING *
"#,
)
.bind(new_phase)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Update supervisor state on heartbeat (lightweight update).
pub async fn update_supervisor_heartbeat_state(
pool: &PgPool,
contract_id: Uuid,
state: &str,
current_activity: Option<&str>,
progress: i32,
pending_task_ids: &[Uuid],
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE supervisor_states
SET state = $1,
current_activity = $2,
progress = $3,
pending_task_ids = $4,
last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $5
"#,
)
.bind(state)
.bind(current_activity)
.bind(progress)
.bind(pending_task_ids)
.bind(contract_id)
.execute(pool)
.await?;
Ok(())
}
// ============================================================================
// Supervisor Heartbeats
// ============================================================================
/// Record a supervisor heartbeat.
/// This creates a historical record for monitoring and dead supervisor detection.
pub async fn create_supervisor_heartbeat(
pool: &PgPool,
supervisor_task_id: Uuid,
contract_id: Uuid,
state: &str,
phase: &str,
current_activity: Option<&str>,
progress: i32,
pending_task_ids: &[Uuid],
) -> Result<SupervisorHeartbeatRecord, sqlx::Error> {
sqlx::query_as::<_, SupervisorHeartbeatRecord>(
r#"
INSERT INTO supervisor_heartbeats (
supervisor_task_id, contract_id, state, phase, current_activity, progress, pending_task_ids, timestamp
)
VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
RETURNING *
"#,
)
.bind(supervisor_task_id)
.bind(contract_id)
.bind(state)
.bind(phase)
.bind(current_activity)
.bind(progress)
.bind(pending_task_ids)
.fetch_one(pool)
.await
}
/// Get the latest heartbeat for a supervisor task.
pub async fn get_latest_supervisor_heartbeat(
pool: &PgPool,
supervisor_task_id: Uuid,
) -> Result<Option<SupervisorHeartbeatRecord>, sqlx::Error> {
sqlx::query_as::<_, SupervisorHeartbeatRecord>(
r#"
SELECT * FROM supervisor_heartbeats
WHERE supervisor_task_id = $1
ORDER BY timestamp DESC
LIMIT 1
"#,
)
.bind(supervisor_task_id)
.fetch_optional(pool)
.await
}
/// Get recent heartbeats for a supervisor task.
pub async fn get_supervisor_heartbeats(
pool: &PgPool,
supervisor_task_id: Uuid,
limit: i64,
) -> Result<Vec<SupervisorHeartbeatRecord>, sqlx::Error> {
sqlx::query_as::<_, SupervisorHeartbeatRecord>(
r#"
SELECT * FROM supervisor_heartbeats
WHERE supervisor_task_id = $1
ORDER BY timestamp DESC
LIMIT $2
"#,
)
.bind(supervisor_task_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Get recent heartbeats for a contract.
pub async fn get_contract_supervisor_heartbeats(
pool: &PgPool,
contract_id: Uuid,
limit: i64,
) -> Result<Vec<SupervisorHeartbeatRecord>, sqlx::Error> {
sqlx::query_as::<_, SupervisorHeartbeatRecord>(
r#"
SELECT * FROM supervisor_heartbeats
WHERE contract_id = $1
ORDER BY timestamp DESC
LIMIT $2
"#,
)
.bind(contract_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Delete old heartbeats beyond the TTL (24 hours by default).
/// Returns the number of deleted records.
pub async fn cleanup_old_heartbeats(
pool: &PgPool,
ttl_hours: i64,
) -> Result<u64, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM supervisor_heartbeats
WHERE timestamp < NOW() - ($1 || ' hours')::INTERVAL
"#,
)
.bind(ttl_hours.to_string())
.execute(pool)
.await?;
Ok(result.rows_affected())
}
/// Find supervisors that have not sent a heartbeat within the timeout period.
/// Returns list of (supervisor_task_id, contract_id, last_heartbeat_timestamp).
pub async fn find_stale_supervisors(
pool: &PgPool,
timeout_seconds: i64,
) -> Result<Vec<(Uuid, Uuid, chrono::DateTime<Utc>)>, sqlx::Error> {
let rows = sqlx::query(
r#"
WITH latest_heartbeats AS (
SELECT DISTINCT ON (supervisor_task_id)
supervisor_task_id,
contract_id,
timestamp
FROM supervisor_heartbeats
ORDER BY supervisor_task_id, timestamp DESC
)
SELECT
lh.supervisor_task_id,
lh.contract_id,
lh.timestamp
FROM latest_heartbeats lh
JOIN tasks t ON t.id = lh.supervisor_task_id
WHERE t.status = 'running'
AND lh.timestamp < NOW() - ($1 || ' seconds')::INTERVAL
"#,
)
.bind(timeout_seconds.to_string())
.fetch_all(pool)
.await?;
let mut result = Vec::new();
for row in rows {
use sqlx::Row;
let supervisor_task_id: Uuid = row.get("supervisor_task_id");
let contract_id: Uuid = row.get("contract_id");
let timestamp: chrono::DateTime<Utc> = row.get("timestamp");
result.push((supervisor_task_id, contract_id, timestamp));
}
Ok(result)
}
// ============================================================================
// Contract Supervisor
// ============================================================================
/// Update contract's supervisor task ID.
pub async fn update_contract_supervisor(
pool: &PgPool,
contract_id: Uuid,
supervisor_task_id: Uuid,
) -> Result<Contract, sqlx::Error> {
sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET supervisor_task_id = $1,
updated_at = NOW()
WHERE id = $2
RETURNING *
"#,
)
.bind(supervisor_task_id)
.bind(contract_id)
.fetch_one(pool)
.await
}
/// Mark a deliverable as complete for a specific phase.
/// Uses JSONB operations to append the deliverable_id to the phase's array.
pub async fn mark_deliverable_complete(
pool: &PgPool,
contract_id: Uuid,
phase: &str,
deliverable_id: &str,
) -> Result<Contract, sqlx::Error> {
// Use jsonb_set to add the deliverable to the phase's array
// If the phase key doesn't exist, create an empty array first
// COALESCE handles the case where the phase array doesn't exist yet
sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET completed_deliverables = jsonb_set(
completed_deliverables,
ARRAY[$2::text],
COALESCE(completed_deliverables->$2, '[]'::jsonb) || to_jsonb($3::text),
true
),
updated_at = NOW()
WHERE id = $1
AND NOT (COALESCE(completed_deliverables->$2, '[]'::jsonb) ? $3)
RETURNING *
"#,
)
.bind(contract_id)
.bind(phase)
.bind(deliverable_id)
.fetch_one(pool)
.await
}
/// Clear all completed deliverables for a specific phase.
/// Used when phase changes or deliverables need to be reset.
pub async fn clear_phase_deliverables(
pool: &PgPool,
contract_id: Uuid,
phase: &str,
) -> Result<Contract, sqlx::Error> {
sqlx::query_as::<_, Contract>(
r#"
UPDATE contracts
SET completed_deliverables = completed_deliverables - $2,
updated_at = NOW()
WHERE id = $1
RETURNING *
"#,
)
.bind(contract_id)
.bind(phase)
.fetch_one(pool)
.await
}
/// Get the supervisor task for a contract.
pub async fn get_contract_supervisor_task(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Option<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
SELECT t.* FROM tasks t
JOIN contracts c ON c.supervisor_task_id = t.id
WHERE c.id = $1
"#,
)
.bind(contract_id)
.fetch_optional(pool)
.await
}
// ============================================================================
// Task Tree Queries
// ============================================================================
/// Get full task tree for a contract.
pub async fn get_contract_task_tree(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Vec<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
WITH RECURSIVE task_tree AS (
-- Base case: root tasks (no parent)
SELECT * FROM tasks
WHERE contract_id = $1 AND parent_task_id IS NULL
UNION ALL
-- Recursive case: children of current level
SELECT t.* FROM tasks t
JOIN task_tree tt ON t.parent_task_id = tt.id
)
SELECT * FROM task_tree
ORDER BY depth, created_at
"#,
)
.bind(contract_id)
.fetch_all(pool)
.await
}
/// Get task tree from a specific root task.
pub async fn get_task_tree(pool: &PgPool, root_task_id: Uuid) -> Result<Vec<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
WITH RECURSIVE task_tree AS (
-- Base case: the root task
SELECT * FROM tasks WHERE id = $1
UNION ALL
-- Recursive case: children of current level
SELECT t.* FROM tasks t
JOIN task_tree tt ON t.parent_task_id = tt.id
)
SELECT * FROM task_tree
ORDER BY depth, created_at
"#,
)
.bind(root_task_id)
.fetch_all(pool)
.await
}
// ============================================================================
// Daemon Selection
// ============================================================================
/// Get daemons with capacity info for selection.
pub async fn get_available_daemons(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<DaemonWithCapacity>, sqlx::Error> {
sqlx::query_as::<_, DaemonWithCapacity>(
r#"
SELECT id, owner_id, connection_id, hostname, machine_id,
max_concurrent_tasks, current_task_count,
capacity_score, task_queue_length, supports_migration,
status, last_heartbeat_at, connected_at
FROM daemons
WHERE owner_id = $1 AND status = 'connected'
ORDER BY
COALESCE(capacity_score, 100) DESC,
(max_concurrent_tasks - current_task_count) DESC,
COALESCE(task_queue_length, 0) ASC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get daemons with capacity info for selection, excluding specified daemon IDs.
/// Used for task retry to avoid reassigning to daemons that have already failed.
pub async fn get_available_daemons_excluding(
pool: &PgPool,
owner_id: Uuid,
exclude_daemon_ids: &[Uuid],
) -> Result<Vec<DaemonWithCapacity>, sqlx::Error> {
sqlx::query_as::<_, DaemonWithCapacity>(
r#"
SELECT id, owner_id, connection_id, hostname, machine_id,
max_concurrent_tasks, current_task_count,
capacity_score, task_queue_length, supports_migration,
status, last_heartbeat_at, connected_at
FROM daemons
WHERE owner_id = $1
AND status = 'connected'
AND id != ALL($2)
ORDER BY
COALESCE(capacity_score, 100) DESC,
(max_concurrent_tasks - current_task_count) DESC,
COALESCE(task_queue_length, 0) ASC
"#,
)
.bind(owner_id)
.bind(exclude_daemon_ids)
.fetch_all(pool)
.await
}
/// Create a daemon task assignment.
pub async fn create_daemon_task_assignment(
pool: &PgPool,
daemon_id: Uuid,
task_id: Uuid,
) -> Result<DaemonTaskAssignment, sqlx::Error> {
sqlx::query_as::<_, DaemonTaskAssignment>(
r#"
INSERT INTO daemon_task_assignments (daemon_id, task_id)
VALUES ($1, $2)
RETURNING *
"#,
)
.bind(daemon_id)
.bind(task_id)
.fetch_one(pool)
.await
}
/// Update daemon task assignment status.
pub async fn update_daemon_task_assignment_status(
pool: &PgPool,
task_id: Uuid,
status: &str,
) -> Result<DaemonTaskAssignment, sqlx::Error> {
sqlx::query_as::<_, DaemonTaskAssignment>(
r#"
UPDATE daemon_task_assignments
SET status = $1
WHERE task_id = $2
RETURNING *
"#,
)
.bind(status)
.bind(task_id)
.fetch_one(pool)
.await
}
/// Get daemon task assignment for a task.
pub async fn get_daemon_task_assignment(
pool: &PgPool,
task_id: Uuid,
) -> Result<Option<DaemonTaskAssignment>, sqlx::Error> {
sqlx::query_as::<_, DaemonTaskAssignment>(
"SELECT * FROM daemon_task_assignments WHERE task_id = $1",
)
.bind(task_id)
.fetch_optional(pool)
.await
}
// ============================================================================
// Repository History Functions
// ============================================================================
use super::models::RepositoryHistoryEntry;
/// List all repository history entries for an owner, ordered by use_count DESC, last_used_at DESC.
pub async fn list_repository_history_for_owner(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<RepositoryHistoryEntry>, sqlx::Error> {
sqlx::query_as::<_, RepositoryHistoryEntry>(
r#"
SELECT id, owner_id, name, repository_url, local_path, source_type, use_count, last_used_at, created_at
FROM repository_history
WHERE owner_id = $1
ORDER BY use_count DESC, last_used_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get repository suggestions for an owner, optionally filtered by source type and query.
pub async fn get_repository_suggestions(
pool: &PgPool,
owner_id: Uuid,
source_type: Option<&str>,
query: Option<&str>,
limit: i32,
) -> Result<Vec<RepositoryHistoryEntry>, sqlx::Error> {
// Build query dynamically based on filters
let mut sql = String::from(
r#"
SELECT id, owner_id, name, repository_url, local_path, source_type, use_count, last_used_at, created_at
FROM repository_history
WHERE owner_id = $1
"#,
);
let mut param_idx = 2;
if source_type.is_some() {
sql.push_str(&format!(" AND source_type = ${}", param_idx));
param_idx += 1;
}
if query.is_some() {
sql.push_str(&format!(
" AND (LOWER(name) LIKE ${} OR LOWER(COALESCE(repository_url, '')) LIKE ${} OR LOWER(COALESCE(local_path, '')) LIKE ${})",
param_idx, param_idx, param_idx
));
param_idx += 1;
}
sql.push_str(&format!(
" ORDER BY use_count DESC, last_used_at DESC LIMIT ${}",
param_idx
));
// Build and execute query with the appropriate bindings
let mut query_builder = sqlx::query_as::<_, RepositoryHistoryEntry>(&sql).bind(owner_id);
if let Some(st) = source_type {
query_builder = query_builder.bind(st);
}
if let Some(q) = query {
let search_pattern = format!("%{}%", q.to_lowercase());
query_builder = query_builder.bind(search_pattern);
}
query_builder = query_builder.bind(limit);
query_builder.fetch_all(pool).await
}
/// Add or update a repository history entry.
/// If an entry with the same URL (for remote) or path (for local) already exists,
/// increment use_count and update last_used_at and name.
/// Otherwise, create a new entry.
pub async fn add_or_update_repository_history(
pool: &PgPool,
owner_id: Uuid,
name: &str,
repository_url: Option<&str>,
local_path: Option<&str>,
source_type: &str,
) -> Result<RepositoryHistoryEntry, sqlx::Error> {
// Use UPSERT (INSERT ... ON CONFLICT)
if source_type == "remote" {
let url = repository_url.ok_or_else(|| {
sqlx::Error::Protocol("repository_url required for remote type".to_string())
})?;
sqlx::query_as::<_, RepositoryHistoryEntry>(
r#"
INSERT INTO repository_history (owner_id, name, repository_url, local_path, source_type, use_count, last_used_at)
VALUES ($1, $2, $3, NULL, $4, 1, NOW())
ON CONFLICT (owner_id, repository_url) WHERE source_type = 'remote' AND repository_url IS NOT NULL
DO UPDATE SET
name = EXCLUDED.name,
use_count = repository_history.use_count + 1,
last_used_at = NOW()
RETURNING id, owner_id, name, repository_url, local_path, source_type, use_count, last_used_at, created_at
"#,
)
.bind(owner_id)
.bind(name)
.bind(url)
.bind(source_type)
.fetch_one(pool)
.await
} else if source_type == "local" {
let path = local_path.ok_or_else(|| {
sqlx::Error::Protocol("local_path required for local type".to_string())
})?;
sqlx::query_as::<_, RepositoryHistoryEntry>(
r#"
INSERT INTO repository_history (owner_id, name, repository_url, local_path, source_type, use_count, last_used_at)
VALUES ($1, $2, NULL, $3, $4, 1, NOW())
ON CONFLICT (owner_id, local_path) WHERE source_type = 'local' AND local_path IS NOT NULL
DO UPDATE SET
name = EXCLUDED.name,
use_count = repository_history.use_count + 1,
last_used_at = NOW()
RETURNING id, owner_id, name, repository_url, local_path, source_type, use_count, last_used_at, created_at
"#,
)
.bind(owner_id)
.bind(name)
.bind(path)
.bind(source_type)
.fetch_one(pool)
.await
} else {
Err(sqlx::Error::Protocol(format!(
"Invalid source_type: {}",
source_type
)))
}
}
/// Delete a repository history entry.
/// Returns true if an entry was deleted, false if not found.
pub async fn delete_repository_history(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM repository_history
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
// ============================================================================
// Conversation Snapshots
// ============================================================================
/// Create a new conversation snapshot
pub async fn create_conversation_snapshot(
pool: &PgPool,
task_id: Uuid,
checkpoint_id: Option<Uuid>,
snapshot_type: &str,
message_count: i32,
conversation_state: serde_json::Value,
metadata: Option<serde_json::Value>,
) -> Result<ConversationSnapshot, sqlx::Error> {
sqlx::query_as::<_, ConversationSnapshot>(
r#"
INSERT INTO conversation_snapshots (task_id, checkpoint_id, snapshot_type, message_count, conversation_state, metadata)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *
"#
)
.bind(task_id)
.bind(checkpoint_id)
.bind(snapshot_type)
.bind(message_count)
.bind(conversation_state)
.bind(metadata)
.fetch_one(pool)
.await
}
/// Get a conversation snapshot by ID
pub async fn get_conversation_snapshot(
pool: &PgPool,
id: Uuid,
) -> Result<Option<ConversationSnapshot>, sqlx::Error> {
sqlx::query_as::<_, ConversationSnapshot>(
"SELECT * FROM conversation_snapshots WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
}
/// Get conversation snapshot at a specific checkpoint
pub async fn get_conversation_at_checkpoint(
pool: &PgPool,
checkpoint_id: Uuid,
) -> Result<Option<ConversationSnapshot>, sqlx::Error> {
sqlx::query_as::<_, ConversationSnapshot>(
"SELECT * FROM conversation_snapshots WHERE checkpoint_id = $1 ORDER BY created_at DESC LIMIT 1"
)
.bind(checkpoint_id)
.fetch_optional(pool)
.await
}
/// List conversation snapshots for a task
pub async fn list_conversation_snapshots(
pool: &PgPool,
task_id: Uuid,
limit: Option<i32>,
) -> Result<Vec<ConversationSnapshot>, sqlx::Error> {
let limit = limit.unwrap_or(100);
sqlx::query_as::<_, ConversationSnapshot>(
"SELECT * FROM conversation_snapshots WHERE task_id = $1 ORDER BY created_at DESC LIMIT $2"
)
.bind(task_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Delete conversation snapshots older than retention period
pub async fn cleanup_old_snapshots(
pool: &PgPool,
retention_days: i32,
) -> Result<u64, sqlx::Error> {
let result = sqlx::query(
"DELETE FROM conversation_snapshots WHERE created_at < NOW() - INTERVAL '1 day' * $1"
)
.bind(retention_days)
.execute(pool)
.await?;
Ok(result.rows_affected())
}
// ============================================================================
// History Events
// ============================================================================
/// Record a new history event
#[allow(clippy::too_many_arguments)]
pub async fn record_history_event(
pool: &PgPool,
owner_id: Uuid,
contract_id: Option<Uuid>,
task_id: Option<Uuid>,
event_type: &str,
event_subtype: Option<&str>,
phase: Option<&str>,
event_data: serde_json::Value,
) -> Result<HistoryEvent, sqlx::Error> {
sqlx::query_as::<_, HistoryEvent>(
r#"
INSERT INTO history_events (owner_id, contract_id, task_id, event_type, event_subtype, phase, event_data)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING *
"#
)
.bind(owner_id)
.bind(contract_id)
.bind(task_id)
.bind(event_type)
.bind(event_subtype)
.bind(phase)
.bind(event_data)
.fetch_one(pool)
.await
}
/// Get contract history timeline
pub async fn get_contract_history(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
filters: &HistoryQueryFilters,
) -> Result<(Vec<HistoryEvent>, i64), sqlx::Error> {
let limit = filters.limit.unwrap_or(100);
let mut query = String::from(
"SELECT * FROM history_events WHERE contract_id = $1 AND owner_id = $2"
);
let mut count_query = String::from(
"SELECT COUNT(*) FROM history_events WHERE contract_id = $1 AND owner_id = $2"
);
let mut param_count = 2;
if filters.phase.is_some() {
param_count += 1;
query.push_str(&format!(" AND phase = ${}" , param_count));
count_query.push_str(&format!(" AND phase = ${}", param_count));
}
if filters.from.is_some() {
param_count += 1;
query.push_str(&format!(" AND created_at >= ${}", param_count));
count_query.push_str(&format!(" AND created_at >= ${}", param_count));
}
if filters.to.is_some() {
param_count += 1;
query.push_str(&format!(" AND created_at <= ${}", param_count));
count_query.push_str(&format!(" AND created_at <= ${}", param_count));
}
query.push_str(" ORDER BY created_at DESC");
query.push_str(&format!(" LIMIT {}", limit));
// Build and execute the query dynamically
let mut q = sqlx::query_as::<_, HistoryEvent>(&query)
.bind(contract_id)
.bind(owner_id);
if let Some(ref phase) = filters.phase {
q = q.bind(phase);
}
if let Some(ref from) = filters.from {
q = q.bind(from);
}
if let Some(ref to) = filters.to {
q = q.bind(to);
}
let events = q.fetch_all(pool).await?;
// Get total count
let mut cq = sqlx::query_scalar::<_, i64>(&count_query)
.bind(contract_id)
.bind(owner_id);
if let Some(ref phase) = filters.phase {
cq = cq.bind(phase);
}
if let Some(ref from) = filters.from {
cq = cq.bind(from);
}
if let Some(ref to) = filters.to {
cq = cq.bind(to);
}
let count = cq.fetch_one(pool).await?;
Ok((events, count))
}
/// Get task history
pub async fn get_task_history(
pool: &PgPool,
task_id: Uuid,
owner_id: Uuid,
filters: &HistoryQueryFilters,
) -> Result<(Vec<HistoryEvent>, i64), sqlx::Error> {
let limit = filters.limit.unwrap_or(100);
let events = sqlx::query_as::<_, HistoryEvent>(
r#"
SELECT * FROM history_events
WHERE task_id = $1 AND owner_id = $2
ORDER BY created_at DESC
LIMIT $3
"#
)
.bind(task_id)
.bind(owner_id)
.bind(limit)
.fetch_all(pool)
.await?;
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM history_events WHERE task_id = $1 AND owner_id = $2"
)
.bind(task_id)
.bind(owner_id)
.fetch_one(pool)
.await?;
Ok((events, count))
}
/// Get unified timeline for an owner
pub async fn get_timeline(
pool: &PgPool,
owner_id: Uuid,
filters: &HistoryQueryFilters,
) -> Result<(Vec<HistoryEvent>, i64), sqlx::Error> {
let limit = filters.limit.unwrap_or(100);
let events = sqlx::query_as::<_, HistoryEvent>(
r#"
SELECT * FROM history_events
WHERE owner_id = $1
ORDER BY created_at DESC
LIMIT $2
"#
)
.bind(owner_id)
.bind(limit)
.fetch_all(pool)
.await?;
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM history_events WHERE owner_id = $1"
)
.bind(owner_id)
.fetch_one(pool)
.await?;
Ok((events, count))
}
// ============================================================================
// Task Conversation Retrieval
// ============================================================================
// Helper struct for parsing task output events
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TaskOutputEvent {
message_type: String,
content: Option<String>,
tool_name: Option<String>,
tool_input: Option<serde_json::Value>,
is_error: Option<bool>,
cost_usd: Option<f32>,
}
/// Get task conversation messages (reconstructed from task_events)
pub async fn get_task_conversation(
pool: &PgPool,
task_id: Uuid,
include_tool_calls: bool,
include_tool_results: bool,
limit: Option<i32>,
) -> Result<Vec<ConversationMessage>, sqlx::Error> {
let limit = limit.unwrap_or(1000);
// Get output events that represent conversation turns
let events = sqlx::query_as::<_, TaskEvent>(
r#"
SELECT * FROM task_events
WHERE task_id = $1 AND event_type = 'output'
ORDER BY created_at ASC
LIMIT $2
"#
)
.bind(task_id)
.bind(limit)
.fetch_all(pool)
.await?;
// Convert task events to conversation messages
let mut messages = Vec::new();
for event in events {
if let Some(data) = event.event_data {
// Parse the event data to extract message info
if let Ok(output) = serde_json::from_value::<TaskOutputEvent>(data.clone()) {
let should_include = match output.message_type.as_str() {
"tool_use" => include_tool_calls,
"tool_result" => include_tool_results,
_ => true,
};
if should_include {
messages.push(ConversationMessage {
id: event.id.to_string(),
role: match output.message_type.as_str() {
"assistant" => "assistant".to_string(),
"tool_use" => "assistant".to_string(),
"tool_result" => "tool".to_string(),
"system" => "system".to_string(),
"error" => "system".to_string(),
_ => "user".to_string(),
},
content: output.content.unwrap_or_default(),
timestamp: event.created_at,
tool_calls: None,
tool_name: output.tool_name,
tool_input: output.tool_input,
tool_result: None,
is_error: output.is_error,
token_count: None,
cost_usd: output.cost_usd.map(|c| c as f64),
});
}
}
}
}
Ok(messages)
}
/// Get supervisor conversation (from supervisor_states)
pub async fn get_supervisor_conversation_full(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Option<SupervisorState>, sqlx::Error> {
get_supervisor_state(pool, contract_id).await
}
// =============================================================================
// Anonymous Task Cleanup Functions
// =============================================================================
/// Delete stale anonymous tasks (tasks with contract_id = NULL) that:
/// - Are in a terminal state (done, failed, merged)
/// - Are older than the specified number of days
///
/// Returns the number of deleted tasks.
pub async fn cleanup_stale_anonymous_tasks(
pool: &PgPool,
max_age_days: i32,
) -> Result<i64, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM tasks
WHERE contract_id IS NULL
AND status IN ('done', 'failed', 'merged')
AND created_at < NOW() - INTERVAL '1 day' * $1
"#,
)
.bind(max_age_days)
.execute(pool)
.await?;
Ok(result.rows_affected() as i64)
}
// ============================================================================
// Checkpoint Patches (for task recovery)
// ============================================================================
/// Create a checkpoint patch for task recovery.
pub async fn create_checkpoint_patch(
pool: &PgPool,
task_id: Uuid,
checkpoint_id: Option<Uuid>,
base_commit_sha: &str,
patch_data: &[u8],
files_count: i32,
ttl_hours: i64,
) -> Result<CheckpointPatch, sqlx::Error> {
sqlx::query_as::<_, CheckpointPatch>(
r#"
INSERT INTO checkpoint_patches (
task_id, checkpoint_id, base_commit_sha, patch_data,
patch_size_bytes, files_count, expires_at
)
VALUES ($1, $2, $3, $4, $5, $6, NOW() + INTERVAL '1 hour' * $7)
RETURNING *
"#,
)
.bind(task_id)
.bind(checkpoint_id)
.bind(base_commit_sha)
.bind(patch_data)
.bind(patch_data.len() as i32)
.bind(files_count)
.bind(ttl_hours)
.fetch_one(pool)
.await
}
/// Get the latest checkpoint patch for a task.
pub async fn get_latest_checkpoint_patch(
pool: &PgPool,
task_id: Uuid,
) -> Result<Option<CheckpointPatch>, sqlx::Error> {
sqlx::query_as::<_, CheckpointPatch>(
r#"
SELECT * FROM checkpoint_patches
WHERE task_id = $1 AND expires_at > NOW()
ORDER BY created_at DESC
LIMIT 1
"#,
)
.bind(task_id)
.fetch_optional(pool)
.await
}
/// Get a checkpoint patch by ID.
pub async fn get_checkpoint_patch(
pool: &PgPool,
id: Uuid,
) -> Result<Option<CheckpointPatch>, sqlx::Error> {
sqlx::query_as::<_, CheckpointPatch>(
"SELECT * FROM checkpoint_patches WHERE id = $1",
)
.bind(id)
.fetch_optional(pool)
.await
}
/// List all checkpoint patches for a task (without patch data for efficiency).
pub async fn list_checkpoint_patches(
pool: &PgPool,
task_id: Uuid,
) -> Result<Vec<CheckpointPatchInfo>, sqlx::Error> {
sqlx::query_as::<_, CheckpointPatchInfo>(
r#"
SELECT id, task_id, checkpoint_id, base_commit_sha,
patch_size_bytes, files_count, created_at, expires_at
FROM checkpoint_patches
WHERE task_id = $1
ORDER BY created_at DESC
"#,
)
.bind(task_id)
.fetch_all(pool)
.await
}
/// Delete expired checkpoint patches.
/// Returns the number of deleted patches.
pub async fn cleanup_expired_checkpoint_patches(
pool: &PgPool,
) -> Result<i64, sqlx::Error> {
let result = sqlx::query("DELETE FROM checkpoint_patches WHERE expires_at < NOW()")
.execute(pool)
.await?;
Ok(result.rows_affected() as i64)
}
/// Delete all checkpoint patches for a task.
pub async fn delete_checkpoint_patches_for_task(
pool: &PgPool,
task_id: Uuid,
) -> Result<i64, sqlx::Error> {
let result = sqlx::query("DELETE FROM checkpoint_patches WHERE task_id = $1")
.bind(task_id)
.execute(pool)
.await?;
Ok(result.rows_affected() as i64)
}
// =============================================================================
// Red Team Notifications
// =============================================================================
// =============================================================================
// Supervisor Status API Helpers
// =============================================================================
/// Get supervisor status for a contract.
/// Returns combined information from supervisor_states and tasks tables.
pub async fn get_supervisor_status(
pool: &PgPool,
contract_id: Uuid,
owner_id: Uuid,
) -> Result<Option<SupervisorStatusInfo>, sqlx::Error> {
// Query to get supervisor status by joining supervisor_states with tasks
sqlx::query_as::<_, SupervisorStatusInfo>(
r#"
SELECT
ss.task_id,
COALESCE(t.status, 'unknown') as supervisor_state,
ss.phase,
t.progress_summary as current_activity,
ss.pending_task_ids,
ss.last_activity as last_heartbeat,
t.status as task_status,
t.daemon_id IS NOT NULL as is_running
FROM supervisor_states ss
JOIN tasks t ON t.id = ss.task_id
WHERE ss.contract_id = $1
AND t.owner_id = $2
"#,
)
.bind(contract_id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Internal struct to hold supervisor status query result
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct SupervisorStatusInfo {
pub task_id: Uuid,
pub supervisor_state: String,
pub phase: String,
pub current_activity: Option<String>,
#[sqlx(try_from = "Vec<Uuid>")]
pub pending_task_ids: Vec<Uuid>,
pub last_heartbeat: chrono::DateTime<chrono::Utc>,
pub task_status: String,
pub is_running: bool,
}
/// Get supervisor activity history from history_events table.
/// This provides a timeline of supervisor activities that can serve as "heartbeats".
pub async fn get_supervisor_activity_history(
pool: &PgPool,
contract_id: Uuid,
limit: i32,
offset: i32,
) -> Result<Vec<SupervisorActivityEntry>, sqlx::Error> {
sqlx::query_as::<_, SupervisorActivityEntry>(
r#"
SELECT
created_at as timestamp,
COALESCE(event_subtype, 'activity') as state,
event_data->>'activity' as activity,
(event_data->>'progress')::INTEGER as progress,
COALESCE(phase, 'unknown') as phase,
CASE
WHEN event_data->'pending_task_ids' IS NOT NULL
THEN ARRAY(SELECT jsonb_array_elements_text(event_data->'pending_task_ids'))::UUID[]
ELSE ARRAY[]::UUID[]
END as pending_task_ids
FROM history_events
WHERE contract_id = $1
AND event_type IN ('supervisor', 'phase', 'task')
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
"#,
)
.bind(contract_id)
.bind(limit)
.bind(offset)
.fetch_all(pool)
.await
}
/// Internal struct to hold supervisor activity entry
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct SupervisorActivityEntry {
pub timestamp: chrono::DateTime<chrono::Utc>,
pub state: String,
pub activity: Option<String>,
pub progress: Option<i32>,
pub phase: String,
#[sqlx(try_from = "Vec<Uuid>")]
pub pending_task_ids: Vec<Uuid>,
}
/// Count total supervisor activity history entries for a contract.
pub async fn count_supervisor_activity_history(
pool: &PgPool,
contract_id: Uuid,
) -> Result<i64, sqlx::Error> {
let result: (i64,) = sqlx::query_as(
r#"
SELECT COUNT(*)
FROM history_events
WHERE contract_id = $1
AND event_type IN ('supervisor', 'phase', 'task')
"#,
)
.bind(contract_id)
.fetch_one(pool)
.await?;
Ok(result.0)
}
/// Update supervisor state last_activity timestamp.
/// This acts as a "sync" operation to refresh the supervisor's heartbeat.
pub async fn sync_supervisor_state(
pool: &PgPool,
contract_id: Uuid,
) -> Result<Option<SupervisorState>, sqlx::Error> {
sqlx::query_as::<_, SupervisorState>(
r#"
UPDATE supervisor_states
SET last_activity = NOW(),
updated_at = NOW()
WHERE contract_id = $1
RETURNING *
"#,
)
.bind(contract_id)
.fetch_optional(pool)
.await
}
// =============================================================================
// Helper Functions
// =============================================================================
/// Helper to truncate string to max length
#[allow(dead_code)]
fn truncate_string(s: &str, max_len: usize) -> String {
if s.len() <= max_len {
s.to_string()
} else {
format!("{}...", &s[..max_len - 3])
}
}
// =============================================================================
// Directive CRUD
// =============================================================================
/// Create a new directive for an owner.
pub async fn create_directive_for_owner(
pool: &PgPool,
owner_id: Uuid,
req: CreateDirectiveRequest,
) -> Result<Directive, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"
INSERT INTO directives (owner_id, title, goal, repository_url, local_path, base_branch, reconcile_mode)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING *
"#,
)
.bind(owner_id)
.bind(&req.title)
.bind(&req.goal)
.bind(&req.repository_url)
.bind(&req.local_path)
.bind(&req.base_branch)
.bind(req.reconcile_mode.as_deref().unwrap_or("auto"))
.fetch_one(pool)
.await
}
/// Get a single directive for an owner.
pub async fn get_directive_for_owner(
pool: &PgPool,
owner_id: Uuid,
id: Uuid,
) -> Result<Option<Directive>, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"SELECT * FROM directives WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Get a directive with all its steps.
pub async fn get_directive_with_steps_for_owner(
pool: &PgPool,
owner_id: Uuid,
id: Uuid,
) -> Result<Option<(Directive, Vec<DirectiveStep>)>, sqlx::Error> {
let directive = sqlx::query_as::<_, Directive>(
r#"SELECT * FROM directives WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await?;
match directive {
Some(d) => {
let steps = list_directive_steps(pool, d.id).await?;
Ok(Some((d, steps)))
}
None => Ok(None),
}
}
/// List all directives for an owner with step counts.
pub async fn list_directives_for_owner(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<DirectiveSummary>, sqlx::Error> {
sqlx::query_as::<_, DirectiveSummary>(
r#"
SELECT
d.id, d.owner_id, d.title, d.goal, d.status, d.repository_url,
d.orchestrator_task_id, d.pr_url, d.completion_task_id,
d.reconcile_mode,
d.version, d.created_at, d.updated_at,
COALESCE(s.total_steps, 0) as total_steps,
COALESCE(s.completed_steps, 0) as completed_steps,
COALESCE(s.running_steps, 0) as running_steps,
COALESCE(s.failed_steps, 0) as failed_steps
FROM directives d
LEFT JOIN LATERAL (
SELECT
COUNT(*) as total_steps,
COUNT(*) FILTER (WHERE status = 'completed') as completed_steps,
COUNT(*) FILTER (WHERE status = 'running') as running_steps,
COUNT(*) FILTER (WHERE status = 'failed') as failed_steps
FROM directive_steps
WHERE directive_id = d.id
) s ON true
WHERE d.owner_id = $1
ORDER BY d.created_at DESC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Update a directive with optimistic locking.
pub async fn update_directive_for_owner(
pool: &PgPool,
owner_id: Uuid,
id: Uuid,
req: UpdateDirectiveRequest,
) -> Result<Option<Directive>, RepositoryError> {
let current = sqlx::query_as::<_, Directive>(
r#"SELECT * FROM directives WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
.map_err(RepositoryError::Database)?;
let current = match current {
Some(c) => c,
None => return Ok(None),
};
if let Some(expected_version) = req.version {
if expected_version != current.version {
return Err(RepositoryError::VersionConflict {
expected: expected_version,
actual: current.version,
});
}
}
let title = req.title.as_deref().unwrap_or(¤t.title);
let goal = req.goal.as_deref().unwrap_or(¤t.goal);
let goal_changed = goal != current.goal;
let status = req.status.as_deref().unwrap_or(¤t.status);
let repository_url = req.repository_url.as_deref().or(current.repository_url.as_deref());
let local_path = req.local_path.as_deref().or(current.local_path.as_deref());
let base_branch = req.base_branch.as_deref().or(current.base_branch.as_deref());
let orchestrator_task_id = req.orchestrator_task_id.or(current.orchestrator_task_id);
let pr_url = req.pr_url.as_deref().or(current.pr_url.as_deref());
let pr_branch = req.pr_branch.as_deref().or(current.pr_branch.as_deref());
let reconcile_mode = req.reconcile_mode.clone().unwrap_or_else(|| current.reconcile_mode.clone());
let result = sqlx::query_as::<_, Directive>(
r#"
UPDATE directives
SET title = $3, goal = $4, status = $5, repository_url = $6, local_path = $7,
base_branch = $8, orchestrator_task_id = $9, pr_url = $10, pr_branch = $11,
reconcile_mode = $12,
goal_updated_at = CASE WHEN $13 THEN NOW() ELSE goal_updated_at END,
version = version + 1, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(title)
.bind(goal)
.bind(status)
.bind(repository_url)
.bind(local_path)
.bind(base_branch)
.bind(orchestrator_task_id)
.bind(pr_url)
.bind(pr_branch)
.bind(reconcile_mode)
.bind(goal_changed)
.fetch_optional(pool)
.await
.map_err(RepositoryError::Database)?;
Ok(result)
}
/// Delete a directive for an owner.
pub async fn delete_directive_for_owner(
pool: &PgPool,
owner_id: Uuid,
id: Uuid,
) -> Result<bool, sqlx::Error> {
// Delete all tasks associated with this directive
sqlx::query(
r#"DELETE FROM tasks WHERE directive_id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
let result = sqlx::query(
r#"DELETE FROM directives WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Clean up terminal tasks associated with a directive.
///
/// Deletes tasks in terminal states (completed, failed, merged, done, interrupted)
/// that belong to this directive, excluding tasks currently referenced by
/// `completion_task_id` or `orchestrator_task_id` on the directive.
/// NULLs out `task_id` on directive_steps for deleted tasks.
pub async fn cleanup_directive_tasks(
pool: &PgPool,
owner_id: Uuid,
directive_id: Uuid,
) -> Result<i64, sqlx::Error> {
// NULL out task_id on steps that reference terminal tasks we're about to delete
sqlx::query(
r#"
UPDATE directive_steps
SET task_id = NULL
WHERE directive_id = $1
AND task_id IS NOT NULL
AND task_id IN (
SELECT t.id FROM tasks t
WHERE t.directive_id = $1
AND t.owner_id = $2
AND t.status IN ('completed', 'failed', 'merged', 'done', 'interrupted')
AND t.id NOT IN (
SELECT COALESCE(d.completion_task_id, '00000000-0000-0000-0000-000000000000')
FROM directives d WHERE d.id = $1
UNION
SELECT COALESCE(d.orchestrator_task_id, '00000000-0000-0000-0000-000000000000')
FROM directives d WHERE d.id = $1
)
)
"#,
)
.bind(directive_id)
.bind(owner_id)
.execute(pool)
.await?;
// Delete terminal tasks not currently referenced by the directive
let result = sqlx::query(
r#"
DELETE FROM tasks
WHERE directive_id = $1
AND owner_id = $2
AND status IN ('completed', 'failed', 'merged', 'done', 'interrupted')
AND id NOT IN (
SELECT COALESCE(d.completion_task_id, '00000000-0000-0000-0000-000000000000')
FROM directives d WHERE d.id = $1
UNION
SELECT COALESCE(d.orchestrator_task_id, '00000000-0000-0000-0000-000000000000')
FROM directives d WHERE d.id = $1
)
"#,
)
.bind(directive_id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() as i64)
}
// =============================================================================
// Directive Completion Helpers
// =============================================================================
/// Row type for completed step tasks.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct CompletedStepTask {
pub step_id: Uuid,
pub step_name: String,
pub task_id: Uuid,
pub task_name: String,
}
/// Row type for directive completion task status check.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct DirectiveCompletionCheck {
pub directive_id: Uuid,
pub owner_id: Uuid,
pub completion_task_id: Uuid,
pub task_status: String,
pub pr_url: Option<String>,
pub task_name: String,
}
/// Get idle directives that need a completion task spawned.
/// Conditions: status = 'idle', no completion_task_id, has repository_url,
/// and has at least one completed step with a task_id.
pub async fn get_idle_directives_needing_completion(
pool: &PgPool,
) -> Result<Vec<Directive>, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"
SELECT d.*
FROM directives d
WHERE d.status = 'idle'
AND d.completion_task_id IS NULL
AND d.pr_branch IS NULL
AND d.repository_url IS NOT NULL
AND EXISTS (
SELECT 1 FROM directive_steps ds
WHERE ds.directive_id = d.id
AND ds.status = 'completed'
AND ds.task_id IS NOT NULL
)
"#,
)
.fetch_all(pool)
.await
}
/// Get directives that attempted completion (pr_branch set) but have no PR URL yet
/// and no active completion task. These need a verification task spawned.
pub async fn get_directives_needing_verification(
pool: &PgPool,
) -> Result<Vec<Directive>, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"
SELECT d.*
FROM directives d
WHERE d.status = 'idle'
AND d.pr_branch IS NOT NULL
AND d.pr_url IS NULL
AND d.completion_task_id IS NULL
AND d.repository_url IS NOT NULL
"#,
)
.fetch_all(pool)
.await
}
/// Get directives with active completion tasks, joined with task status.
pub async fn get_completion_tasks_to_check(
pool: &PgPool,
) -> Result<Vec<DirectiveCompletionCheck>, sqlx::Error> {
sqlx::query_as::<_, DirectiveCompletionCheck>(
r#"
SELECT d.id as directive_id, d.owner_id, d.completion_task_id, t.status as task_status, d.pr_url, t.name as task_name
FROM directives d
JOIN tasks t ON t.id = d.completion_task_id
WHERE d.completion_task_id IS NOT NULL
"#,
)
.fetch_all(pool)
.await
}
/// Atomically claim a directive for completion by setting a placeholder completion_task_id.
/// Returns true if the claim was successful (no other task already claimed it).
pub async fn claim_directive_for_completion(
pool: &PgPool,
directive_id: Uuid,
task_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"UPDATE directives SET completion_task_id = $2, updated_at = NOW()
WHERE id = $1 AND completion_task_id IS NULL"#,
)
.bind(directive_id)
.bind(task_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Assign a completion task to a directive (unconditional update).
pub async fn assign_completion_task(
pool: &PgPool,
directive_id: Uuid,
task_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"UPDATE directives SET completion_task_id = $2, updated_at = NOW() WHERE id = $1"#,
)
.bind(directive_id)
.bind(task_id)
.execute(pool)
.await?;
Ok(())
}
/// Clear the completion task from a directive.
pub async fn clear_completion_task(
pool: &PgPool,
directive_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"UPDATE directives SET completion_task_id = NULL, updated_at = NOW() WHERE id = $1"#,
)
.bind(directive_id)
.execute(pool)
.await?;
Ok(())
}
/// Get completed step tasks for a directive (steps that have completed with an assigned task).
pub async fn get_completed_step_tasks(
pool: &PgPool,
directive_id: Uuid,
) -> Result<Vec<CompletedStepTask>, sqlx::Error> {
sqlx::query_as::<_, CompletedStepTask>(
r#"
SELECT ds.id as step_id, ds.name as step_name, ds.task_id, t.name as task_name
FROM directive_steps ds
JOIN tasks t ON t.id = ds.task_id
WHERE ds.directive_id = $1
AND ds.status = 'completed'
AND ds.task_id IS NOT NULL
ORDER BY ds.order_index, ds.created_at
"#,
)
.bind(directive_id)
.fetch_all(pool)
.await
}
/// Get the task ID of the most recently completed step for a directive.
/// Used as a fallback `continue_from_task_id` when dispatching new-generation steps
/// that have no explicit dependencies and no PR branch to continue from.
pub async fn get_last_completed_step_task_id(
pool: &PgPool,
directive_id: Uuid,
) -> Result<Option<Uuid>, sqlx::Error> {
let row: Option<(Uuid,)> = sqlx::query_as(
r#"
SELECT ds.task_id
FROM directive_steps ds
WHERE ds.directive_id = $1
AND ds.status = 'completed'
AND ds.task_id IS NOT NULL
ORDER BY ds.updated_at DESC
LIMIT 1
"#,
)
.bind(directive_id)
.fetch_optional(pool)
.await?;
Ok(row.map(|r| r.0))
}
// =============================================================================
// Directive Step CRUD
// =============================================================================
/// Get a single directive step by ID.
pub async fn get_directive_step(
pool: &PgPool,
step_id: Uuid,
) -> Result<Option<DirectiveStep>, sqlx::Error> {
sqlx::query_as::<_, DirectiveStep>(
r#"SELECT * FROM directive_steps WHERE id = $1"#,
)
.bind(step_id)
.fetch_optional(pool)
.await
}
/// List all steps for a directive, ordered by order_index.
pub async fn list_directive_steps(
pool: &PgPool,
directive_id: Uuid,
) -> Result<Vec<DirectiveStep>, sqlx::Error> {
sqlx::query_as::<_, DirectiveStep>(
r#"
SELECT * FROM directive_steps
WHERE directive_id = $1
ORDER BY order_index, created_at
"#,
)
.bind(directive_id)
.fetch_all(pool)
.await
}
/// Create a single directive step.
pub async fn create_directive_step(
pool: &PgPool,
directive_id: Uuid,
req: CreateDirectiveStepRequest,
) -> Result<DirectiveStep, sqlx::Error> {
let generation = req.generation.unwrap_or(1);
let order_id = req.order_id;
let contract_type = req.contract_type.clone();
let step = sqlx::query_as::<_, DirectiveStep>(
r#"
INSERT INTO directive_steps (directive_id, name, description, task_plan, depends_on, order_index, generation, contract_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *
"#,
)
.bind(directive_id)
.bind(&req.name)
.bind(&req.description)
.bind(&req.task_plan)
.bind(&req.depends_on)
.bind(req.order_index)
.bind(generation)
.bind(&contract_type)
.fetch_one(pool)
.await?;
// If an order_id was provided, auto-link the order to this step
if let Some(oid) = order_id {
sqlx::query(
r#"UPDATE orders SET directive_step_id = $1, updated_at = NOW() WHERE id = $2"#,
)
.bind(step.id)
.bind(oid)
.execute(pool)
.await?;
}
Ok(step)
}
/// Batch create multiple directive steps.
pub async fn batch_create_directive_steps(
pool: &PgPool,
directive_id: Uuid,
steps: Vec<CreateDirectiveStepRequest>,
) -> Result<Vec<DirectiveStep>, sqlx::Error> {
let mut results = Vec::with_capacity(steps.len());
for req in steps {
let step = create_directive_step(pool, directive_id, req).await?;
results.push(step);
}
Ok(results)
}
/// Update a directive step.
pub async fn update_directive_step(
pool: &PgPool,
step_id: Uuid,
req: UpdateDirectiveStepRequest,
) -> Result<Option<DirectiveStep>, sqlx::Error> {
let current = sqlx::query_as::<_, DirectiveStep>(
r#"SELECT * FROM directive_steps WHERE id = $1"#,
)
.bind(step_id)
.fetch_optional(pool)
.await?;
let current = match current {
Some(c) => c,
None => return Ok(None),
};
let name = req.name.as_deref().unwrap_or(¤t.name);
let description = req.description.as_deref().or(current.description.as_deref());
let task_plan = req.task_plan.as_deref().or(current.task_plan.as_deref());
let depends_on = req.depends_on.as_deref().unwrap_or(¤t.depends_on);
let status = req.status.as_deref().unwrap_or(¤t.status);
let task_id = req.task_id.or(current.task_id);
let order_index = req.order_index.unwrap_or(current.order_index);
// Set started_at when transitioning to running
let started_at = if status == "running" && current.status != "running" {
Some(Utc::now())
} else {
current.started_at
};
// Set completed_at when transitioning to terminal state
let completed_at = if matches!(status, "completed" | "failed" | "skipped")
&& !matches!(current.status.as_str(), "completed" | "failed" | "skipped")
{
Some(Utc::now())
} else {
current.completed_at
};
sqlx::query_as::<_, DirectiveStep>(
r#"
UPDATE directive_steps
SET name = $2, description = $3, task_plan = $4, depends_on = $5,
status = $6, task_id = $7, order_index = $8, started_at = $9, completed_at = $10
WHERE id = $1
RETURNING *
"#,
)
.bind(step_id)
.bind(name)
.bind(description)
.bind(task_plan)
.bind(depends_on)
.bind(status)
.bind(task_id)
.bind(order_index)
.bind(started_at)
.bind(completed_at)
.fetch_optional(pool)
.await
}
/// Delete a directive step.
pub async fn delete_directive_step(
pool: &PgPool,
step_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(r#"DELETE FROM directive_steps WHERE id = $1"#)
.bind(step_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Delete all directive steps that have not started execution (pending, ready, failed, skipped).
/// Completed and running steps are preserved.
/// Returns the number of deleted steps.
pub async fn clear_pending_directive_steps(
pool: &PgPool,
directive_id: Uuid,
) -> Result<u64, sqlx::Error> {
let result = sqlx::query(
r#"DELETE FROM directive_steps
WHERE directive_id = $1
AND status IN ('pending', 'ready', 'failed', 'skipped')"#,
)
.bind(directive_id)
.execute(pool)
.await?;
Ok(result.rows_affected())
}
// =============================================================================
// Directive DAG Progression
// =============================================================================
/// Advance pending steps to ready if all their dependencies are in terminal states.
/// Returns the newly-ready steps.
pub async fn advance_directive_ready_steps(
pool: &PgPool,
directive_id: Uuid,
) -> Result<Vec<DirectiveStep>, sqlx::Error> {
sqlx::query_as::<_, DirectiveStep>(
r#"
UPDATE directive_steps SET status = 'ready'
WHERE directive_id = $1 AND status = 'pending'
AND NOT EXISTS (
SELECT 1 FROM unnest(depends_on) AS dep_id
JOIN directive_steps ds ON ds.id = dep_id
WHERE ds.status NOT IN ('completed', 'skipped')
)
AND NOT EXISTS (
SELECT 1 FROM directive_steps prev
WHERE prev.directive_id = $1
AND prev.order_index < directive_steps.order_index
AND prev.status NOT IN ('completed', 'skipped', 'failed')
)
RETURNING *
"#,
)
.bind(directive_id)
.fetch_all(pool)
.await
}
/// Check if all steps in a directive are in terminal states.
/// If so, set the directive to 'idle' (not completed — directives are ongoing).
/// Returns true if the directive was set to idle.
pub async fn check_directive_idle(
pool: &PgPool,
directive_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE directives SET status = 'idle', updated_at = NOW()
WHERE id = $1 AND status = 'active'
AND NOT EXISTS (
SELECT 1 FROM directive_steps
WHERE directive_id = $1
AND status NOT IN ('completed', 'failed', 'skipped')
)
AND EXISTS (
SELECT 1 FROM directive_steps WHERE directive_id = $1
)
"#,
)
.bind(directive_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Update a directive's goal and bump goal_updated_at.
/// Reactivates idle/paused directives and clears any stale orchestrator task
/// so that replanning triggers on the next tick.
pub async fn update_directive_goal(
pool: &PgPool,
owner_id: Uuid,
directive_id: Uuid,
goal: &str,
) -> Result<Option<Directive>, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"
UPDATE directives
SET goal = $3,
goal_updated_at = NOW(),
status = CASE WHEN status IN ('idle', 'paused') THEN 'active' ELSE status END,
orchestrator_task_id = NULL,
updated_at = NOW(),
version = version + 1
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(directive_id)
.bind(owner_id)
.bind(goal)
.fetch_optional(pool)
.await
}
/// Save a goal to the directive goal history.
pub async fn save_directive_goal_history(
pool: &PgPool,
directive_id: Uuid,
goal: &str,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"INSERT INTO directive_goal_history (directive_id, goal)
VALUES ($1, $2)"#,
)
.bind(directive_id)
.bind(goal)
.execute(pool)
.await?;
Ok(())
}
/// Get recent goal history for a directive (most recent first), limited to limit entries.
pub async fn get_directive_goal_history(
pool: &PgPool,
directive_id: Uuid,
limit: i64,
) -> Result<Vec<DirectiveGoalHistory>, sqlx::Error> {
sqlx::query_as::<_, DirectiveGoalHistory>(
r#"SELECT id, directive_id, goal, created_at
FROM directive_goal_history
WHERE directive_id = $1
ORDER BY created_at DESC
LIMIT $2"#,
)
.bind(directive_id)
.bind(limit)
.fetch_all(pool)
.await
}
/// Set a directive's status (used for start/pause/archive transitions).
pub async fn set_directive_status(
pool: &PgPool,
owner_id: Uuid,
directive_id: Uuid,
status: &str,
) -> Result<Option<Directive>, sqlx::Error> {
let mut query = String::from(
r#"UPDATE directives SET status = $3, updated_at = NOW(), version = version + 1"#,
);
if status == "active" {
query.push_str(", started_at = COALESCE(started_at, NOW())");
}
query.push_str(" WHERE id = $1 AND owner_id = $2 RETURNING *");
sqlx::query_as::<_, Directive>(&query)
.bind(directive_id)
.bind(owner_id)
.bind(status)
.fetch_optional(pool)
.await
}
// =============================================================================
// Directive Orchestrator Queries
// =============================================================================
/// Get active directives that need planning (no steps, no orchestrator task).
pub async fn get_directives_needing_planning(
pool: &PgPool,
) -> Result<Vec<Directive>, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"
SELECT d.* FROM directives d
WHERE d.status = 'active'
AND d.orchestrator_task_id IS NULL
AND NOT EXISTS (
SELECT 1 FROM directive_steps WHERE directive_id = d.id
)
"#,
)
.fetch_all(pool)
.await
}
/// A step joined with minimal directive info for dispatch.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct StepForDispatch {
// Step fields
pub step_id: Uuid,
pub directive_id: Uuid,
pub step_name: String,
pub step_description: Option<String>,
pub task_plan: Option<String>,
pub order_index: i32,
pub generation: i32,
pub depends_on: Vec<Uuid>,
/// Optional contract type — when set, orchestrator creates a contract instead of a task.
pub contract_type: Option<String>,
// Directive fields
pub owner_id: Uuid,
pub directive_title: String,
pub repository_url: Option<String>,
pub base_branch: Option<String>,
/// The directive's PR branch (if a PR has already been created from previous steps).
pub pr_branch: Option<String>,
/// The directive's reconcile mode: "auto", "semi-auto", or "manual".
pub reconcile_mode: String,
}
/// Get ready steps that need task dispatch.
pub async fn get_ready_steps_for_dispatch(
pool: &PgPool,
) -> Result<Vec<StepForDispatch>, sqlx::Error> {
sqlx::query_as::<_, StepForDispatch>(
r#"
SELECT
ds.id AS step_id,
ds.directive_id,
ds.name AS step_name,
ds.description AS step_description,
ds.task_plan,
ds.order_index,
ds.generation,
ds.depends_on,
ds.contract_type,
d.owner_id,
d.title AS directive_title,
d.repository_url,
d.base_branch,
d.pr_branch,
d.reconcile_mode
FROM directive_steps ds
JOIN directives d ON d.id = ds.directive_id
WHERE ds.status = 'ready'
AND ds.task_id IS NULL
AND ds.contract_id IS NULL
AND d.status = 'active'
ORDER BY ds.order_index
"#,
)
.fetch_all(pool)
.await
}
/// Task info for a dependency step (step → linked task).
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct DependencyTaskInfo {
pub step_id: Uuid,
pub task_id: Uuid,
pub task_name: String,
}
/// Resolve dependency step UUIDs to their linked task IDs and names.
/// Returns results in the same order as the input `depends_on` slice.
pub async fn get_step_dependency_tasks(
pool: &PgPool,
depends_on: &[Uuid],
) -> Result<Vec<DependencyTaskInfo>, sqlx::Error> {
if depends_on.is_empty() {
return Ok(vec![]);
}
let rows = sqlx::query_as::<_, DependencyTaskInfo>(
r#"
SELECT ds.id AS step_id, t.id AS task_id, t.name AS task_name
FROM directive_steps ds
JOIN tasks t ON t.id = ds.task_id
WHERE ds.id = ANY($1)
"#,
)
.bind(depends_on)
.fetch_all(pool)
.await?;
// Re-order to match input ordering
let mut ordered = Vec::with_capacity(depends_on.len());
for dep_id in depends_on {
if let Some(row) = rows.iter().find(|r| r.step_id == *dep_id) {
ordered.push(row.clone());
}
}
Ok(ordered)
}
/// A running step joined with its task's current status.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct RunningStepWithTask {
pub step_id: Uuid,
pub directive_id: Uuid,
pub task_id: Uuid,
pub task_status: String,
}
/// Get running steps with their task status for monitoring.
pub async fn get_running_steps_with_tasks(
pool: &PgPool,
) -> Result<Vec<RunningStepWithTask>, sqlx::Error> {
sqlx::query_as::<_, RunningStepWithTask>(
r#"
SELECT
ds.id AS step_id,
ds.directive_id,
ds.task_id AS "task_id!",
t.status AS task_status
FROM directive_steps ds
JOIN tasks t ON t.id = ds.task_id
WHERE ds.status = 'running'
AND ds.task_id IS NOT NULL
AND ds.contract_id IS NULL
"#,
)
.fetch_all(pool)
.await
}
/// A running step backed by a contract, joined with the contract's current status.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct RunningStepWithContract {
pub step_id: Uuid,
pub directive_id: Uuid,
pub contract_id: Uuid,
pub contract_status: String,
pub contract_phase: String,
}
/// Get running steps that are backed by contracts (for contract-based monitoring).
pub async fn get_running_steps_with_contracts(
pool: &PgPool,
) -> Result<Vec<RunningStepWithContract>, sqlx::Error> {
sqlx::query_as::<_, RunningStepWithContract>(
r#"
SELECT
ds.id AS step_id,
ds.directive_id,
ds.contract_id AS "contract_id!",
c.status AS contract_status,
c.phase AS contract_phase
FROM directive_steps ds
JOIN contracts c ON c.id = ds.contract_id
WHERE ds.status = 'running'
AND ds.contract_id IS NOT NULL
"#,
)
.fetch_all(pool)
.await
}
/// An orchestrator task to check (directive with pending planning task).
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct OrchestratorTaskCheck {
pub directive_id: Uuid,
pub orchestrator_task_id: Uuid,
pub task_status: String,
pub owner_id: Uuid,
}
/// Get directives with orchestrator tasks to check completion.
pub async fn get_orchestrator_tasks_to_check(
pool: &PgPool,
) -> Result<Vec<OrchestratorTaskCheck>, sqlx::Error> {
sqlx::query_as::<_, OrchestratorTaskCheck>(
r#"
SELECT
d.id AS directive_id,
d.orchestrator_task_id AS "orchestrator_task_id!",
t.status AS task_status,
d.owner_id
FROM directives d
JOIN tasks t ON t.id = d.orchestrator_task_id
WHERE d.orchestrator_task_id IS NOT NULL
AND d.status = 'active'
"#,
)
.fetch_all(pool)
.await
}
/// Get active directives that need re-planning (goal updated after latest step).
pub async fn get_directives_needing_replanning(
pool: &PgPool,
) -> Result<Vec<Directive>, sqlx::Error> {
sqlx::query_as::<_, Directive>(
r#"
SELECT d.* FROM directives d
WHERE d.status = 'active'
AND d.orchestrator_task_id IS NULL
AND EXISTS (
SELECT 1 FROM directive_steps WHERE directive_id = d.id
)
AND d.goal_updated_at > (
SELECT COALESCE(MAX(ds.created_at), '1970-01-01'::timestamptz)
FROM directive_steps ds WHERE ds.directive_id = d.id
)
"#,
)
.fetch_all(pool)
.await
}
/// Assign a task to a step and set status to running.
pub async fn assign_task_to_step(
pool: &PgPool,
step_id: Uuid,
task_id: Uuid,
) -> Result<Option<DirectiveStep>, sqlx::Error> {
sqlx::query_as::<_, DirectiveStep>(
r#"
UPDATE directive_steps
SET task_id = $2, status = 'running', started_at = NOW()
WHERE id = $1
RETURNING *
"#,
)
.bind(step_id)
.bind(task_id)
.fetch_optional(pool)
.await
}
/// Set the orchestrator_task_id on a directive.
pub async fn assign_orchestrator_task(
pool: &PgPool,
directive_id: Uuid,
task_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE directives
SET orchestrator_task_id = $2, updated_at = NOW()
WHERE id = $1
"#,
)
.bind(directive_id)
.bind(task_id)
.execute(pool)
.await?;
Ok(())
}
/// Clear the orchestrator_task_id on a directive.
pub async fn clear_orchestrator_task(
pool: &PgPool,
directive_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE directives
SET orchestrator_task_id = NULL, updated_at = NOW()
WHERE id = $1
"#,
)
.bind(directive_id)
.execute(pool)
.await?;
Ok(())
}
/// Cancel old planning tasks for a directive.
/// Marks any non-terminal planning/re-planning tasks as interrupted,
/// excluding the given new task. Identifies planning tasks by name prefix
/// ("Plan: " or "Re-plan: ") to avoid cancelling completion/verification tasks.
pub async fn cancel_old_planning_tasks(
pool: &PgPool,
directive_id: Uuid,
exclude_task_id: Uuid,
) -> Result<u64, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE tasks
SET status = 'interrupted',
completed_at = NOW(),
updated_at = NOW()
WHERE directive_id = $1
AND id != $2
AND (name LIKE 'Plan: %' OR name LIKE 'Re-plan: %')
AND status NOT IN ('completed', 'failed', 'merged', 'done', 'interrupted')
"#,
)
.bind(directive_id)
.bind(exclude_task_id)
.execute(pool)
.await?;
Ok(result.rows_affected())
}
/// Link a task to a step without changing step status.
pub async fn link_task_to_step(
pool: &PgPool,
step_id: Uuid,
task_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE directive_steps
SET task_id = $2
WHERE id = $1
"#,
)
.bind(step_id)
.bind(task_id)
.execute(pool)
.await?;
Ok(())
}
/// Link a contract to a directive step.
pub async fn link_contract_to_step(
pool: &PgPool,
step_id: Uuid,
contract_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE directive_steps
SET contract_id = $1
WHERE id = $2
"#,
)
.bind(contract_id)
.bind(step_id)
.execute(pool)
.await?;
Ok(())
}
/// Set a step to 'running' status (after its task has been dispatched).
pub async fn set_step_running(
pool: &PgPool,
step_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE directive_steps
SET status = 'running', started_at = COALESCE(started_at, NOW())
WHERE id = $1
"#,
)
.bind(step_id)
.execute(pool)
.await?;
Ok(())
}
/// Get pending directive tasks (tasks with directive_id that are still pending).
pub async fn get_pending_directive_tasks(
pool: &PgPool,
) -> Result<Vec<Task>, sqlx::Error> {
sqlx::query_as::<_, Task>(
r#"
SELECT * FROM tasks
WHERE directive_id IS NOT NULL
AND status = 'pending'
AND daemon_id IS NULL
ORDER BY created_at
"#,
)
.fetch_all(pool)
.await
}
/// Get the max generation number for steps in a directive.
pub async fn get_directive_max_generation(
pool: &PgPool,
directive_id: Uuid,
) -> Result<i32, sqlx::Error> {
let row: (Option<i32>,) = sqlx::query_as(
r#"SELECT MAX(generation) FROM directive_steps WHERE directive_id = $1"#,
)
.bind(directive_id)
.fetch_one(pool)
.await?;
Ok(row.0.unwrap_or(0))
}
// =============================================================================
// Order CRUD
// =============================================================================
/// Create a new order for the given owner.
pub async fn create_order(
pool: &PgPool,
owner_id: Uuid,
req: CreateOrderRequest,
) -> Result<Order, sqlx::Error> {
let priority = req.priority.as_deref().unwrap_or("medium");
let status = req.status.as_deref().unwrap_or("open");
let order_type = req.order_type.as_deref().unwrap_or("feature");
sqlx::query_as::<_, Order>(
r#"
INSERT INTO orders (owner_id, title, description, priority, status, order_type, labels, directive_id, repository_url, dog_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING *
"#,
)
.bind(owner_id)
.bind(&req.title)
.bind(&req.description)
.bind(priority)
.bind(status)
.bind(order_type)
.bind(&req.labels)
.bind(req.directive_id)
.bind(&req.repository_url)
.bind(req.dog_id)
.fetch_one(pool)
.await
}
/// List orders for the given owner with optional filters.
pub async fn list_orders(
pool: &PgPool,
owner_id: Uuid,
status_filter: Option<&str>,
type_filter: Option<&str>,
priority_filter: Option<&str>,
directive_id_filter: Option<Uuid>,
dog_id_filter: Option<Uuid>,
search_filter: Option<&str>,
) -> Result<Vec<Order>, sqlx::Error> {
// Build dynamic query with optional filters
let mut query = String::from("SELECT * FROM orders WHERE owner_id = $1");
let mut param_idx = 2u32;
if status_filter.is_some() {
query.push_str(&format!(" AND status = ${}", param_idx));
param_idx += 1;
}
if type_filter.is_some() {
query.push_str(&format!(" AND order_type = ${}", param_idx));
param_idx += 1;
}
if priority_filter.is_some() {
query.push_str(&format!(" AND priority = ${}", param_idx));
param_idx += 1;
}
if directive_id_filter.is_some() {
query.push_str(&format!(" AND directive_id = ${}", param_idx));
param_idx += 1;
}
if dog_id_filter.is_some() {
query.push_str(&format!(" AND dog_id = ${}", param_idx));
param_idx += 1;
}
if search_filter.is_some() {
query.push_str(&format!(
" AND (title ILIKE ${p} OR description ILIKE ${p} OR directive_name ILIKE ${p})",
p = param_idx
));
let _ = param_idx; // suppress unused warning
}
query.push_str(" ORDER BY created_at DESC");
let mut q = sqlx::query_as::<_, Order>(&query).bind(owner_id);
if let Some(s) = status_filter {
q = q.bind(s);
}
if let Some(t) = type_filter {
q = q.bind(t);
}
if let Some(p) = priority_filter {
q = q.bind(p);
}
if let Some(d) = directive_id_filter {
q = q.bind(d);
}
if let Some(d) = dog_id_filter {
q = q.bind(d);
}
if let Some(s) = search_filter {
q = q.bind(format!("%{}%", s));
}
q.fetch_all(pool).await
}
/// Get a single order by ID (owner-scoped).
pub async fn get_order(
pool: &PgPool,
owner_id: Uuid,
order_id: Uuid,
) -> Result<Option<Order>, sqlx::Error> {
sqlx::query_as::<_, Order>(
r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#,
)
.bind(order_id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Update an order (owner-scoped). Uses COALESCE pattern to only update provided fields.
pub async fn update_order(
pool: &PgPool,
owner_id: Uuid,
order_id: Uuid,
req: UpdateOrderRequest,
) -> Result<Option<Order>, sqlx::Error> {
let current = sqlx::query_as::<_, Order>(
r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#,
)
.bind(order_id)
.bind(owner_id)
.fetch_optional(pool)
.await?;
let current = match current {
Some(c) => c,
None => return Ok(None),
};
let title = req.title.as_deref().unwrap_or(¤t.title);
let description = req.description.as_deref().or(current.description.as_deref());
let priority = req.priority.as_deref().unwrap_or(¤t.priority);
let status = req.status.as_deref().unwrap_or(¤t.status);
let order_type = req.order_type.as_deref().unwrap_or(¤t.order_type);
let labels = req.labels.as_ref().unwrap_or(¤t.labels);
let directive_id = req.directive_id.or(current.directive_id);
let directive_step_id = req.directive_step_id.or(current.directive_step_id);
let repository_url = req.repository_url.as_deref().or(current.repository_url.as_deref());
let dog_id = req.dog_id.or(current.dog_id);
sqlx::query_as::<_, Order>(
r#"
UPDATE orders
SET title = $3, description = $4, priority = $5, status = $6,
order_type = $7, labels = $8, directive_id = $9, directive_step_id = $10,
repository_url = $11, dog_id = $12, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(order_id)
.bind(owner_id)
.bind(title)
.bind(description)
.bind(priority)
.bind(status)
.bind(order_type)
.bind(labels)
.bind(directive_id)
.bind(directive_step_id)
.bind(repository_url)
.bind(dog_id)
.fetch_optional(pool)
.await
}
/// Delete an order (owner-scoped). Returns true if a row was deleted.
pub async fn delete_order(
pool: &PgPool,
owner_id: Uuid,
order_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"DELETE FROM orders WHERE id = $1 AND owner_id = $2"#,
)
.bind(order_id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Link an order to a directive.
pub async fn link_order_to_directive(
pool: &PgPool,
owner_id: Uuid,
order_id: Uuid,
directive_id: Uuid,
) -> Result<Option<Order>, sqlx::Error> {
sqlx::query_as::<_, Order>(
r#"
UPDATE orders
SET directive_id = $3, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(order_id)
.bind(owner_id)
.bind(directive_id)
.fetch_optional(pool)
.await
}
/// Convert an order to a directive step. Creates a new DirectiveStep from the order's
/// title and description, links the order to the new step, and returns the created step.
/// Uses the order's existing directive_id (which is required for new orders).
pub async fn convert_order_to_step(
pool: &PgPool,
owner_id: Uuid,
order_id: Uuid,
) -> Result<Option<DirectiveStep>, sqlx::Error> {
// Verify the order exists and belongs to this owner
let order = sqlx::query_as::<_, Order>(
r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#,
)
.bind(order_id)
.bind(owner_id)
.fetch_optional(pool)
.await?;
let order = match order {
Some(o) => o,
None => return Ok(None),
};
// Get the directive_id from the order (required for new orders, but legacy data may have NULL)
let directive_id = match order.directive_id {
Some(id) => id,
None => return Ok(None),
};
// Verify the directive exists and belongs to this owner
let directive = sqlx::query_as::<_, Directive>(
r#"SELECT * FROM directives WHERE id = $1 AND owner_id = $2"#,
)
.bind(directive_id)
.bind(owner_id)
.fetch_optional(pool)
.await?;
if directive.is_none() {
return Ok(None);
}
// Get the next order_index for this directive
let max_index: (Option<i32>,) = sqlx::query_as(
r#"SELECT MAX(order_index) FROM directive_steps WHERE directive_id = $1"#,
)
.bind(directive_id)
.fetch_one(pool)
.await?;
let next_index = max_index.0.unwrap_or(-1) + 1;
// Create the directive step from order data
let step = sqlx::query_as::<_, DirectiveStep>(
r#"
INSERT INTO directive_steps (directive_id, name, description, order_index)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
)
.bind(directive_id)
.bind(&order.title)
.bind(&order.description)
.bind(next_index)
.fetch_one(pool)
.await?;
// Link the order to the new step
sqlx::query(
r#"
UPDATE orders
SET directive_step_id = $3, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
"#,
)
.bind(order_id)
.bind(owner_id)
.bind(step.id)
.execute(pool)
.await?;
Ok(Some(step))
}
// =============================================================================
// Order Pickup
// =============================================================================
/// Get available orders for pickup: open orders with no directive assigned
/// OR orders already linked to this specific directive that are not yet done,
/// sorted by priority (critical first) then creation date.
pub async fn get_available_orders_for_pickup(
pool: &PgPool,
owner_id: Uuid,
directive_id: Uuid,
) -> Result<Vec<Order>, sqlx::Error> {
sqlx::query_as::<_, Order>(
r#"
SELECT *
FROM orders
WHERE owner_id = $1
AND status IN ('open', 'in_progress')
AND (directive_id IS NULL OR directive_id = $2)
ORDER BY CASE priority
WHEN 'critical' THEN 0
WHEN 'high' THEN 1
WHEN 'medium' THEN 2
WHEN 'low' THEN 3
ELSE 4
END ASC, created_at ASC
"#,
)
.bind(owner_id)
.bind(directive_id)
.fetch_all(pool)
.await
}
/// Bulk-link orders to a directive by setting directive_id on matching orders.
/// Returns the count of updated rows.
pub async fn bulk_link_orders_to_directive(
pool: &PgPool,
owner_id: Uuid,
order_ids: &[Uuid],
directive_id: Uuid,
) -> Result<i64, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE orders
SET directive_id = $1, updated_at = NOW()
WHERE id = ANY($2)
AND owner_id = $3
"#,
)
.bind(directive_id)
.bind(order_ids)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() as i64)
}
/// Bulk update order status for a set of order IDs.
/// Returns the count of updated rows.
pub async fn bulk_update_order_status(
pool: &PgPool,
owner_id: Uuid,
order_ids: &[Uuid],
status: &str,
) -> Result<i64, sqlx::Error> {
let result = sqlx::query(
r#"UPDATE orders SET status = $1, updated_at = NOW()
WHERE id = ANY($2) AND owner_id = $3"#,
)
.bind(status)
.bind(order_ids)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() as i64)
}
/// Get orders linked to a specific directive step.
pub async fn get_orders_by_step_id(
pool: &PgPool,
step_id: Uuid,
) -> Result<Vec<Order>, sqlx::Error> {
sqlx::query_as::<_, Order>(
r#"SELECT * FROM orders WHERE directive_step_id = $1"#,
)
.bind(step_id)
.fetch_all(pool)
.await
}
/// Reconcile directive orders by checking linked step statuses.
/// - Orders linked to completed steps are marked "done"
/// - Orders linked to running/ready steps are marked "under_review"
/// Returns the count of orders updated.
pub async fn reconcile_directive_orders(
pool: &PgPool,
owner_id: Uuid,
directive_id: Uuid,
) -> Result<i64, sqlx::Error> {
let rows: Vec<(Uuid,)> = sqlx::query_as(
r#"
UPDATE orders o
SET status = CASE
WHEN ds.status = 'completed' THEN 'done'
WHEN ds.status IN ('running', 'ready') THEN 'under_review'
ELSE o.status
END,
updated_at = NOW()
FROM directive_steps ds
WHERE o.directive_step_id = ds.id
AND o.directive_id = $1
AND o.owner_id = $2
AND o.status NOT IN ('done', 'archived')
AND ds.status IN ('completed', 'running', 'ready')
RETURNING o.id
"#,
)
.bind(directive_id)
.bind(owner_id)
.fetch_all(pool)
.await?;
Ok(rows.len() as i64)
}
// =============================================================================
// Directive Order Group (DOG) CRUD
// =============================================================================
/// Create a new Directive Order Group (DOG) for the given owner and directive.
pub async fn create_directive_order_group(
pool: &PgPool,
directive_id: Uuid,
owner_id: Uuid,
req: CreateDirectiveOrderGroupRequest,
) -> Result<DirectiveOrderGroup, sqlx::Error> {
sqlx::query_as::<_, DirectiveOrderGroup>(
r#"
INSERT INTO directive_order_groups (directive_id, owner_id, name, description)
VALUES ($1, $2, $3, $4)
RETURNING *
"#,
)
.bind(directive_id)
.bind(owner_id)
.bind(&req.name)
.bind(&req.description)
.fetch_one(pool)
.await
}
/// List all DOGs for a given directive (owner-scoped).
pub async fn list_directive_order_groups(
pool: &PgPool,
directive_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<DirectiveOrderGroup>, sqlx::Error> {
sqlx::query_as::<_, DirectiveOrderGroup>(
r#"
SELECT * FROM directive_order_groups
WHERE directive_id = $1 AND owner_id = $2
ORDER BY created_at DESC
"#,
)
.bind(directive_id)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get a single DOG by ID (owner-scoped).
pub async fn get_directive_order_group(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<Option<DirectiveOrderGroup>, sqlx::Error> {
sqlx::query_as::<_, DirectiveOrderGroup>(
r#"SELECT * FROM directive_order_groups WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await
}
/// Update a DOG (owner-scoped). Uses fetch-then-update pattern for partial updates.
pub async fn update_directive_order_group(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
req: UpdateDirectiveOrderGroupRequest,
) -> Result<Option<DirectiveOrderGroup>, sqlx::Error> {
let current = sqlx::query_as::<_, DirectiveOrderGroup>(
r#"SELECT * FROM directive_order_groups WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.fetch_optional(pool)
.await?;
let current = match current {
Some(c) => c,
None => return Ok(None),
};
let name = req.name.as_deref().unwrap_or(¤t.name);
let description = req.description.as_deref().or(current.description.as_deref());
let status = req.status.as_deref().unwrap_or(¤t.status);
sqlx::query_as::<_, DirectiveOrderGroup>(
r#"
UPDATE directive_order_groups
SET name = $3, description = $4, status = $5, updated_at = NOW()
WHERE id = $1 AND owner_id = $2
RETURNING *
"#,
)
.bind(id)
.bind(owner_id)
.bind(name)
.bind(description)
.bind(status)
.fetch_optional(pool)
.await
}
/// Delete a DOG (owner-scoped). Returns true if a row was deleted.
pub async fn delete_directive_order_group(
pool: &PgPool,
id: Uuid,
owner_id: Uuid,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"DELETE FROM directive_order_groups WHERE id = $1 AND owner_id = $2"#,
)
.bind(id)
.bind(owner_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// List orders belonging to a specific DOG (owner-scoped).
pub async fn list_orders_by_dog(
pool: &PgPool,
dog_id: Uuid,
owner_id: Uuid,
) -> Result<Vec<Order>, sqlx::Error> {
sqlx::query_as::<_, Order>(
r#"
SELECT * FROM orders
WHERE dog_id = $1 AND owner_id = $2
ORDER BY created_at DESC
"#,
)
.bind(dog_id)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get available orders for pickup filtered to a specific DOG.
/// Like `get_available_orders_for_pickup` but only returns orders belonging to the given DOG.
pub async fn get_available_orders_for_dog_pickup(
pool: &PgPool,
owner_id: Uuid,
directive_id: Uuid,
dog_id: Uuid,
) -> Result<Vec<Order>, sqlx::Error> {
sqlx::query_as::<_, Order>(
r#"
SELECT *
FROM orders
WHERE owner_id = $1
AND dog_id = $3
AND status IN ('open', 'in_progress')
AND (directive_id IS NULL OR directive_id = $2)
ORDER BY CASE priority
WHEN 'critical' THEN 0
WHEN 'high' THEN 1
WHEN 'medium' THEN 2
WHEN 'low' THEN 3
ELSE 4
END ASC, created_at ASC
"#,
)
.bind(owner_id)
.bind(directive_id)
.bind(dog_id)
.fetch_all(pool)
.await
}
// ─── User Settings ───────────────────────────────────────────────────────────
/// Get all settings for a given owner.
pub async fn get_user_settings(
pool: &PgPool,
owner_id: Uuid,
) -> Result<Vec<UserSetting>, sqlx::Error> {
sqlx::query_as::<_, UserSetting>(
r#"
SELECT id, owner_id, key, value, created_at, updated_at
FROM user_settings
WHERE owner_id = $1
ORDER BY key ASC
"#,
)
.bind(owner_id)
.fetch_all(pool)
.await
}
/// Get a single setting by owner and key.
pub async fn get_user_setting(
pool: &PgPool,
owner_id: Uuid,
key: &str,
) -> Result<Option<UserSetting>, sqlx::Error> {
sqlx::query_as::<_, UserSetting>(
r#"
SELECT id, owner_id, key, value, created_at, updated_at
FROM user_settings
WHERE owner_id = $1 AND key = $2
"#,
)
.bind(owner_id)
.bind(key)
.fetch_optional(pool)
.await
}
/// Upsert a user setting (insert or update on conflict).
pub async fn upsert_user_setting(
pool: &PgPool,
owner_id: Uuid,
key: &str,
value: &serde_json::Value,
) -> Result<UserSetting, sqlx::Error> {
sqlx::query_as::<_, UserSetting>(
r#"
INSERT INTO user_settings (owner_id, key, value)
VALUES ($1, $2, $3)
ON CONFLICT (owner_id, key) DO UPDATE
SET value = EXCLUDED.value, updated_at = now()
RETURNING id, owner_id, key, value, created_at, updated_at
"#,
)
.bind(owner_id)
.bind(key)
.bind(value)
.fetch_one(pool)
.await
}
/// Delete a user setting. Returns true if a row was deleted.
pub async fn delete_user_setting(
pool: &PgPool,
owner_id: Uuid,
key: &str,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM user_settings
WHERE owner_id = $1 AND key = $2
"#,
)
.bind(owner_id)
.bind(key)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
|