pulpod 0.0.41

Pulpo daemon — manages agent sessions via tmux/Docker
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
use std::fmt::Write;

use anyhow::Result;
use chrono::{DateTime, Utc};
use pulpo_common::api::ListSessionsQuery;
use pulpo_common::session::{Session, SessionStatus};
use sqlx::{Row, SqlitePool, sqlite::SqliteRow};
use uuid::Uuid;

use pulpo_common::session::InterventionCode;

/// A Web Push subscription stored for sending push notifications.
#[derive(Debug, Clone)]
pub struct PushSubscription {
    pub endpoint: String,
    pub p256dh: String,
    pub auth: String,
}

/// A single intervention event for audit trail purposes.
#[derive(Debug, Clone)]
pub struct InterventionEvent {
    pub id: i64,
    pub session_id: String,
    pub code: Option<InterventionCode>,
    pub reason: String,
    pub created_at: DateTime<Utc>,
}

#[derive(Clone)]
pub struct Store {
    pool: SqlitePool,
    data_dir: String,
}

impl Store {
    pub async fn new(data_dir: &str) -> Result<Self> {
        std::fs::create_dir_all(data_dir)?;
        let db_path = format!("{data_dir}/state.db");
        let url = format!("sqlite:{db_path}?mode=rwc");
        let pool = SqlitePool::connect(&url).await?;
        Ok(Self {
            pool,
            data_dir: data_dir.to_owned(),
        })
    }

    #[allow(clippy::too_many_lines)]
    pub async fn migrate(&self) -> Result<()> {
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS sessions (
                id TEXT PRIMARY KEY,
                name TEXT NOT NULL,
                workdir TEXT NOT NULL,
                provider TEXT NOT NULL,
                prompt TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'creating',
                mode TEXT NOT NULL DEFAULT 'interactive',
                conversation_id TEXT,
                exit_code INTEGER,
                backend_session_id TEXT,
                output_snapshot TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            )",
        )
        .execute(&self.pool)
        .await?;

        // Idempotent migration: add intervention columns if missing
        let has_intervention = sqlx::query_scalar::<_, i32>(
            "SELECT count(*) FROM pragma_table_info('sessions') WHERE name = 'intervention_reason'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_intervention == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN intervention_reason TEXT")
                .execute(&self.pool)
                .await?;
            sqlx::query("ALTER TABLE sessions ADD COLUMN intervention_at TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: last_output_at column
        let has_last_output: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'last_output_at'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_last_output == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN last_output_at TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: idle_since column
        let has_idle_since: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'idle_since'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_idle_since == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN idle_since TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: append-only intervention events table
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS intervention_events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL
            )",
        )
        .execute(&self.pool)
        .await?;

        // Idempotent migration: add intervention_code column to sessions
        let has_intervention_code: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'intervention_code'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_intervention_code == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN intervention_code TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: add code column to intervention_events
        let has_event_code: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('intervention_events') WHERE name = 'code'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_event_code == 0 {
            sqlx::query("ALTER TABLE intervention_events ADD COLUMN code TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Partial unique index: prevent two live sessions with the same name.
        // SQLite enforces this at insert/update time, closing the race window
        // between the application-level check and the actual insert.
        // Drop first to ensure the index definition stays up-to-date.
        sqlx::query("DROP INDEX IF EXISTS idx_sessions_live_name")
            .execute(&self.pool)
            .await?;
        sqlx::query(
            "CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_live_name \
             ON sessions(name) WHERE status IN ('creating', 'active', 'idle', 'ready')",
        )
        .execute(&self.pool)
        .await?;

        // Idempotent migration: metadata + ink columns
        let has_metadata: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'metadata'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_metadata == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN metadata TEXT")
                .execute(&self.pool)
                .await?;
            sqlx::query("ALTER TABLE sessions ADD COLUMN ink TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: command + description columns
        let has_command: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'command'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_command == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN command TEXT DEFAULT ''")
                .execute(&self.pool)
                .await?;
            sqlx::query("ALTER TABLE sessions ADD COLUMN description TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: idle_threshold_secs column
        let has_idle_threshold = sqlx::query_scalar::<_, i32>(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'idle_threshold_secs'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_idle_threshold == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN idle_threshold_secs INTEGER")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: worktree_path column
        let has_worktree_path: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'worktree_path'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_worktree_path == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN worktree_path TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: worktree_branch column
        let has_worktree_branch: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'worktree_branch'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_worktree_branch == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN worktree_branch TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: sandbox column (legacy name, kept for backward compat)
        let has_sandbox: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'sandbox'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_sandbox == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN sandbox INTEGER DEFAULT 0")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: runtime column (replaces sandbox boolean)
        let has_runtime: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'runtime'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_runtime == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN runtime TEXT NOT NULL DEFAULT 'tmux'")
                .execute(&self.pool)
                .await?;
            // Migrate existing data: sandbox=1 → runtime='docker'
            sqlx::query("UPDATE sessions SET runtime = 'docker' WHERE sandbox = 1")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: push subscriptions table for Web Push notifications
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS push_subscriptions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                endpoint TEXT NOT NULL UNIQUE,
                p256dh TEXT NOT NULL,
                auth TEXT NOT NULL,
                created_at TEXT NOT NULL
            )",
        )
        .execute(&self.pool)
        .await?;

        // Idempotent migration: secrets table
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS secrets (
                name TEXT PRIMARY KEY,
                value TEXT NOT NULL,
                created_at TEXT NOT NULL
            )",
        )
        .execute(&self.pool)
        .await?;

        // Idempotent migration: add env column to secrets table
        let has_secret_env: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('secrets') WHERE name = 'env'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_secret_env == 0 {
            sqlx::query("ALTER TABLE secrets ADD COLUMN env TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Set restrictive file permissions on the database file (Unix only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let db_path = format!("{}/state.db", self.data_dir);
            if let Ok(metadata) = std::fs::metadata(&db_path) {
                let mut perms = metadata.permissions();
                perms.set_mode(0o600);
                let _ = std::fs::set_permissions(&db_path, perms);
            }
        }

        // Idempotent migration: schedules table
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS schedules (
                id TEXT PRIMARY KEY,
                name TEXT NOT NULL UNIQUE,
                cron TEXT NOT NULL,
                command TEXT NOT NULL DEFAULT '',
                workdir TEXT NOT NULL,
                target_node TEXT,
                ink TEXT,
                description TEXT,
                enabled INTEGER NOT NULL DEFAULT 1,
                last_run_at TEXT,
                last_session_id TEXT,
                created_at TEXT NOT NULL
            )",
        )
        .execute(&self.pool)
        .await?;

        // Idempotent migration: schedule execution fields (runtime, secrets, worktree, worktree_base)
        for col in &[
            ("runtime", "TEXT"),
            ("secrets", "TEXT NOT NULL DEFAULT '[]'"),
            ("worktree", "INTEGER"),
            ("worktree_base", "TEXT"),
        ] {
            let has: i32 = sqlx::query_scalar(&format!(
                "SELECT COUNT(*) FROM pragma_table_info('schedules') WHERE name = '{}'",
                col.0
            ))
            .fetch_one(&self.pool)
            .await?;
            if has == 0 {
                sqlx::query(&format!(
                    "ALTER TABLE schedules ADD COLUMN {} {}",
                    col.0, col.1
                ))
                .execute(&self.pool)
                .await?;
            }
        }

        // Idempotent migration: git_branch and git_commit columns
        let has_git_branch: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'git_branch'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_git_branch == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN git_branch TEXT")
                .execute(&self.pool)
                .await?;
        }
        // Rename git_sha → git_commit if the old column name exists (from earlier builds)
        let has_git_sha: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'git_sha'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_git_sha > 0 {
            sqlx::query("ALTER TABLE sessions RENAME COLUMN git_sha TO git_commit")
                .execute(&self.pool)
                .await?;
        }
        let has_git_commit: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'git_commit'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_git_commit == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN git_commit TEXT")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: git diff stats and ahead columns
        let has_git_files_changed: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'git_files_changed'",
        )
        .fetch_one(&self.pool)
        .await?;
        if has_git_files_changed == 0 {
            sqlx::query("ALTER TABLE sessions ADD COLUMN git_files_changed INTEGER")
                .execute(&self.pool)
                .await?;
            sqlx::query("ALTER TABLE sessions ADD COLUMN git_insertions INTEGER")
                .execute(&self.pool)
                .await?;
            sqlx::query("ALTER TABLE sessions ADD COLUMN git_deletions INTEGER")
                .execute(&self.pool)
                .await?;
            sqlx::query("ALTER TABLE sessions ADD COLUMN git_ahead INTEGER")
                .execute(&self.pool)
                .await?;
        }

        // Idempotent migration: rename 'killed' status to 'stopped'
        sqlx::query("UPDATE sessions SET status = 'stopped' WHERE status = 'killed'")
            .execute(&self.pool)
            .await?;

        Ok(())
    }

    pub async fn insert_session(&self, session: &Session) -> Result<()> {
        let metadata_json = session
            .metadata
            .as_ref()
            .map(serde_json::to_string)
            .transpose()?;
        let intervention_code_str = session.intervention_code.map(|c| c.to_string());
        let intervention_at_str = session.intervention_at.map(|dt| dt.to_rfc3339());
        let last_output_at_str = session.last_output_at.map(|dt| dt.to_rfc3339());
        let idle_since_str = session.idle_since.map(|dt| dt.to_rfc3339());
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                exit_code, backend_session_id, output_snapshot,
                metadata, ink, command, description,
                intervention_code, intervention_reason, intervention_at,
                last_output_at, idle_since, idle_threshold_secs, worktree_path, worktree_branch,
                git_branch, git_commit, git_files_changed, git_insertions, git_deletions, git_ahead,
                runtime, created_at, updated_at)
             VALUES (?, ?, ?, '', '', ?, '', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(session.id.to_string())
        .bind(&session.name)
        .bind(&session.workdir)
        .bind(session.status.to_string())
        .bind(session.exit_code)
        .bind(&session.backend_session_id)
        .bind(&session.output_snapshot)
        .bind(&metadata_json)
        .bind(&session.ink)
        .bind(&session.command)
        .bind(&session.description)
        .bind(&intervention_code_str)
        .bind(&session.intervention_reason)
        .bind(&intervention_at_str)
        .bind(&last_output_at_str)
        .bind(&idle_since_str)
        .bind(
            session
                .idle_threshold_secs
                .map(|v| i32::try_from(v).unwrap_or(i32::MAX)),
        )
        .bind(&session.worktree_path)
        .bind(&session.worktree_branch)
        .bind(&session.git_branch)
        .bind(&session.git_commit)
        .bind(session.git_files_changed.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(session.git_insertions.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(session.git_deletions.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(session.git_ahead.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(session.runtime.to_string())
        .bind(session.created_at.to_rfc3339())
        .bind(session.updated_at.to_rfc3339())
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn get_session(&self, id_or_name: &str) -> Result<Option<Session>> {
        // Prefer live sessions over terminal ones when multiple share a name.
        // UUID matches are always exact (one result), but name matches may
        // return duplicates (e.g., a "ready" and a "lost" session both named "backbone").
        let row = sqlx::query(
            "SELECT * FROM sessions WHERE id = ? OR name = ? \
             ORDER BY CASE status \
               WHEN 'active' THEN 0 WHEN 'idle' THEN 1 \
               WHEN 'creating' THEN 2 WHEN 'ready' THEN 3 \
               WHEN 'lost' THEN 4 WHEN 'stopped' THEN 5 \
               ELSE 6 END \
             LIMIT 1",
        )
        .bind(id_or_name)
        .bind(id_or_name)
        .fetch_optional(&self.pool)
        .await?;
        row.map(|r| row_to_session(&r)).transpose()
    }

    pub async fn has_active_session_by_name(&self, name: &str) -> Result<bool> {
        self.has_active_session_by_name_excluding(name, None).await
    }

    /// Check for an active session with `name`, optionally excluding a specific session ID.
    pub async fn has_active_session_by_name_excluding(
        &self,
        name: &str,
        exclude_id: Option<&str>,
    ) -> Result<bool> {
        let row = match exclude_id {
            Some(id) => {
                sqlx::query(
                    "SELECT 1 FROM sessions WHERE name = ? AND id != ? AND status IN ('creating', 'active', 'idle', 'ready') LIMIT 1",
                )
                .bind(name)
                .bind(id)
                .fetch_optional(&self.pool)
                .await?
            }
            None => {
                sqlx::query(
                    "SELECT 1 FROM sessions WHERE name = ? AND status IN ('creating', 'active', 'idle', 'ready') LIMIT 1",
                )
                .bind(name)
                .fetch_optional(&self.pool)
                .await?
            }
        };
        Ok(row.is_some())
    }

    pub async fn list_sessions(&self) -> Result<Vec<Session>> {
        let rows = sqlx::query("SELECT * FROM sessions ORDER BY created_at DESC")
            .fetch_all(&self.pool)
            .await?;
        rows.iter().map(row_to_session).collect()
    }

    pub async fn list_sessions_filtered(&self, query: &ListSessionsQuery) -> Result<Vec<Session>> {
        let mut sql = String::from("SELECT * FROM sessions WHERE 1=1");
        let mut binds: Vec<String> = Vec::new();

        if let Some(status) = &query.status {
            let statuses: Vec<&str> = status.split(',').map(str::trim).collect();
            let placeholders: Vec<String> = statuses.iter().map(|_| "?".to_owned()).collect();
            let _ = write!(sql, " AND status IN ({})", placeholders.join(","));
            binds.extend(statuses.iter().map(|s| (*s).to_owned()));
        }

        if let Some(search) = &query.search {
            sql.push_str(" AND (name LIKE ? OR command LIKE ? OR description LIKE ?)");
            let pattern = format!("%{search}%");
            binds.push(pattern.clone());
            binds.push(pattern.clone());
            binds.push(pattern);
        }

        let sort_col = match query.sort.as_deref() {
            Some("name") => "name",
            Some("status") => "status",
            _ => "created_at",
        };
        let order = match query.order.as_deref() {
            Some("asc") => "ASC",
            _ => "DESC",
        };
        let _ = write!(sql, " ORDER BY {sort_col} {order}");

        let mut q = sqlx::query(&sql);
        for bind in &binds {
            q = q.bind(bind);
        }

        let rows = q.fetch_all(&self.pool).await?;
        rows.iter().map(row_to_session).collect()
    }

    pub async fn update_session_git_info(
        &self,
        id: &str,
        branch: Option<&str>,
        commit: Option<&str>,
    ) -> Result<()> {
        sqlx::query(
            "UPDATE sessions SET git_branch = ?, git_commit = ?, updated_at = ? WHERE id = ?",
        )
        .bind(branch)
        .bind(commit)
        .bind(Utc::now().to_rfc3339())
        .bind(id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn update_session_git_diff(
        &self,
        id: &str,
        files_changed: Option<u32>,
        insertions: Option<u32>,
        deletions: Option<u32>,
    ) -> Result<()> {
        sqlx::query(
            "UPDATE sessions SET git_files_changed = ?, git_insertions = ?, git_deletions = ?, updated_at = ? WHERE id = ?",
        )
        .bind(files_changed.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(insertions.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(deletions.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
        .bind(Utc::now().to_rfc3339())
        .bind(id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn update_session_git_ahead(&self, id: &str, ahead: Option<u32>) -> Result<()> {
        sqlx::query("UPDATE sessions SET git_ahead = ?, updated_at = ? WHERE id = ?")
            .bind(ahead.map(|v| i32::try_from(v).unwrap_or(i32::MAX)))
            .bind(Utc::now().to_rfc3339())
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn update_session_status(&self, id: &str, status: SessionStatus) -> Result<()> {
        sqlx::query("UPDATE sessions SET status = ?, updated_at = ? WHERE id = ?")
            .bind(status.to_string())
            .bind(Utc::now().to_rfc3339())
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn delete_session(&self, id: &str) -> Result<()> {
        sqlx::query("DELETE FROM sessions WHERE id = ?")
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Delete all sessions with stopped or lost status. Returns the count deleted.
    pub async fn cleanup_dead_sessions(&self) -> Result<u64> {
        let result = sqlx::query("DELETE FROM sessions WHERE status IN ('stopped', 'lost')")
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected())
    }

    pub const fn pool(&self) -> &SqlitePool {
        &self.pool
    }

    pub fn data_dir(&self) -> &str {
        &self.data_dir
    }

    pub async fn update_session_intervention(
        &self,
        id: &str,
        code: InterventionCode,
        reason: &str,
    ) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        let code_str = code.to_string();
        sqlx::query(
            "UPDATE sessions SET intervention_code = ?, intervention_reason = ?, intervention_at = ?, status = 'stopped', updated_at = ? WHERE id = ?",
        )
        .bind(&code_str)
        .bind(reason)
        .bind(&now)
        .bind(&now)
        .bind(id)
        .execute(&self.pool)
        .await?;
        // Append to audit log
        sqlx::query(
            "INSERT INTO intervention_events (session_id, code, reason, created_at) VALUES (?, ?, ?, ?)",
        )
        .bind(id)
        .bind(&code_str)
        .bind(reason)
        .bind(&now)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn list_intervention_events(
        &self,
        session_id: &str,
    ) -> Result<Vec<InterventionEvent>> {
        let rows = sqlx::query(
            "SELECT id, session_id, code, reason, created_at FROM intervention_events WHERE session_id = ? ORDER BY id ASC",
        )
        .bind(session_id)
        .fetch_all(&self.pool)
        .await?;
        rows.iter().map(row_to_intervention_event).collect()
    }

    pub async fn clear_session_intervention(&self, id: &str) -> Result<()> {
        sqlx::query(
            "UPDATE sessions SET intervention_code = NULL, intervention_reason = NULL, intervention_at = NULL, updated_at = ? WHERE id = ?",
        )
        .bind(Utc::now().to_rfc3339())
        .bind(id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn update_session_output_snapshot(&self, id: &str, snapshot: &str) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        // Only update last_output_at when the output actually changed
        sqlx::query(
            "UPDATE sessions SET output_snapshot = ?,
                last_output_at = CASE WHEN output_snapshot IS NULL OR output_snapshot != ? THEN ? ELSE last_output_at END,
                updated_at = ?
             WHERE id = ?",
        )
        .bind(snapshot)
        .bind(snapshot)
        .bind(&now)
        .bind(&now)
        .bind(id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn update_session_idle_since(&self, id: &str) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        sqlx::query("UPDATE sessions SET idle_since = ?, updated_at = ? WHERE id = ?")
            .bind(&now)
            .bind(&now)
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Update a single key in the session's metadata JSON.
    /// Reads the existing metadata, adds/updates the key, and writes it back.
    pub async fn update_session_metadata_field(
        &self,
        id: &str,
        key: &str,
        value: &str,
    ) -> Result<()> {
        let row = sqlx::query("SELECT metadata FROM sessions WHERE id = ?")
            .bind(id)
            .fetch_one(&self.pool)
            .await?;
        let existing: Option<String> = row.get("metadata");
        let mut map: std::collections::HashMap<String, String> = existing
            .map(|s| serde_json::from_str(&s))
            .transpose()?
            .unwrap_or_default();
        map.insert(key.to_owned(), value.to_owned());
        let json = serde_json::to_string(&map)?;
        sqlx::query("UPDATE sessions SET metadata = ?, updated_at = ? WHERE id = ?")
            .bind(&json)
            .bind(chrono::Utc::now().to_rfc3339())
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Remove a single key from the session's metadata JSON.
    pub async fn remove_session_metadata_field(&self, id: &str, key: &str) -> Result<()> {
        let row = sqlx::query("SELECT metadata FROM sessions WHERE id = ?")
            .bind(id)
            .fetch_one(&self.pool)
            .await?;
        let existing: Option<String> = row.get("metadata");
        let mut map: std::collections::HashMap<String, String> = existing
            .map(|s| serde_json::from_str(&s))
            .transpose()?
            .unwrap_or_default();
        map.remove(key);
        let json = serde_json::to_string(&map)?;
        sqlx::query("UPDATE sessions SET metadata = ?, updated_at = ? WHERE id = ?")
            .bind(&json)
            .bind(chrono::Utc::now().to_rfc3339())
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn update_backend_session_id(
        &self,
        session_id: &str,
        backend_id: &str,
    ) -> Result<()> {
        sqlx::query("UPDATE sessions SET backend_session_id = ?, updated_at = ? WHERE id = ?")
            .bind(backend_id)
            .bind(Utc::now().to_rfc3339())
            .bind(session_id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn clear_session_idle_since(&self, id: &str) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        sqlx::query("UPDATE sessions SET idle_since = NULL, updated_at = ? WHERE id = ?")
            .bind(&now)
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    // -- Push subscription methods --

    pub async fn save_push_subscription(
        &self,
        endpoint: &str,
        p256dh: &str,
        auth: &str,
    ) -> Result<()> {
        sqlx::query(
            "INSERT OR REPLACE INTO push_subscriptions (endpoint, p256dh, auth, created_at) \
             VALUES (?, ?, ?, ?)",
        )
        .bind(endpoint)
        .bind(p256dh)
        .bind(auth)
        .bind(Utc::now().to_rfc3339())
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn delete_push_subscription(&self, endpoint: &str) -> Result<()> {
        sqlx::query("DELETE FROM push_subscriptions WHERE endpoint = ?")
            .bind(endpoint)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn list_push_subscriptions(&self) -> Result<Vec<PushSubscription>> {
        let rows = sqlx::query("SELECT endpoint, p256dh, auth FROM push_subscriptions")
            .fetch_all(&self.pool)
            .await?;
        Ok(rows
            .iter()
            .map(|r| PushSubscription {
                endpoint: r.get("endpoint"),
                p256dh: r.get("p256dh"),
                auth: r.get("auth"),
            })
            .collect())
    }

    // -- Schedule methods --

    pub async fn insert_schedule(&self, schedule: &pulpo_common::api::Schedule) -> Result<()> {
        let secrets_json = serde_json::to_string(&schedule.secrets)?;
        sqlx::query(
            "INSERT INTO schedules (id, name, cron, command, workdir, target_node, ink, description, runtime, secrets, worktree, worktree_base, enabled, last_run_at, last_session_id, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&schedule.id)
        .bind(&schedule.name)
        .bind(&schedule.cron)
        .bind(&schedule.command)
        .bind(&schedule.workdir)
        .bind(&schedule.target_node)
        .bind(&schedule.ink)
        .bind(&schedule.description)
        .bind(&schedule.runtime)
        .bind(&secrets_json)
        .bind(schedule.worktree)
        .bind(&schedule.worktree_base)
        .bind(schedule.enabled)
        .bind(&schedule.last_run_at)
        .bind(&schedule.last_session_id)
        .bind(&schedule.created_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn list_schedules(&self) -> Result<Vec<pulpo_common::api::Schedule>> {
        let rows = sqlx::query("SELECT * FROM schedules ORDER BY name")
            .fetch_all(&self.pool)
            .await?;
        rows.iter().map(row_to_schedule).collect()
    }

    pub async fn get_schedule(
        &self,
        id_or_name: &str,
    ) -> Result<Option<pulpo_common::api::Schedule>> {
        let row = sqlx::query("SELECT * FROM schedules WHERE id = ? OR name = ?")
            .bind(id_or_name)
            .bind(id_or_name)
            .fetch_optional(&self.pool)
            .await?;
        row.map(|r| row_to_schedule(&r)).transpose()
    }

    pub async fn update_schedule_enabled(&self, id: &str, enabled: bool) -> Result<()> {
        sqlx::query("UPDATE schedules SET enabled = ? WHERE id = ?")
            .bind(enabled)
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn update_schedule_last_run(&self, id: &str, session_id: &str) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        sqlx::query("UPDATE schedules SET last_run_at = ?, last_session_id = ? WHERE id = ?")
            .bind(&now)
            .bind(session_id)
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn list_schedule_runs(
        &self,
        schedule_name: &str,
        limit: usize,
    ) -> Result<Vec<Session>> {
        // Escape SQL LIKE wildcards in the schedule name to prevent unintended matches
        let escaped = schedule_name.replace('%', "\\%").replace('_', "\\_");
        let prefix = format!("{escaped}-%");
        let limit_i64 = i64::try_from(limit).unwrap_or(i64::MAX);
        let rows = sqlx::query(
            "SELECT * FROM sessions WHERE name LIKE ? ESCAPE '\\' ORDER BY created_at DESC LIMIT ?",
        )
        .bind(&prefix)
        .bind(limit_i64)
        .fetch_all(&self.pool)
        .await?;
        rows.iter().map(row_to_session).collect()
    }

    pub async fn delete_schedule(&self, id: &str) -> Result<()> {
        sqlx::query("DELETE FROM schedules WHERE id = ? OR name = ?")
            .bind(id)
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    // -- Secret methods --

    /// Upsert a secret (INSERT OR REPLACE).
    pub async fn set_secret(&self, name: &str, value: &str) -> Result<()> {
        self.set_secret_with_env(name, value, None).await
    }

    /// Upsert a secret with an optional env var name override.
    pub async fn set_secret_with_env(
        &self,
        name: &str,
        value: &str,
        env: Option<&str>,
    ) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        sqlx::query(
            "INSERT OR REPLACE INTO secrets (name, value, env, created_at) VALUES (?, ?, ?, ?)",
        )
        .bind(name)
        .bind(value)
        .bind(env)
        .bind(&now)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    /// Get a secret's value by name (used internally for injection, never exposed via API).
    pub async fn get_secret(&self, name: &str) -> Result<Option<String>> {
        let row: Option<(String,)> = sqlx::query_as("SELECT value FROM secrets WHERE name = ?")
            .bind(name)
            .fetch_optional(&self.pool)
            .await?;
        Ok(row.map(|(v,)| v))
    }

    /// List secret names with optional env override (never returns values).
    /// Returns `(name, env, created_at)` tuples.
    pub async fn list_secret_names(&self) -> Result<Vec<(String, Option<String>, String)>> {
        let rows: Vec<(String, Option<String>, String)> =
            sqlx::query_as("SELECT name, env, created_at FROM secrets ORDER BY name")
                .fetch_all(&self.pool)
                .await?;
        Ok(rows)
    }

    /// Given a list of secret names, returns a map of `env_var_name` -> value.
    /// Uses the `env` field if set, otherwise uses `name` as the env var.
    pub async fn get_secrets_for_injection(
        &self,
        names: &[String],
    ) -> Result<std::collections::HashMap<String, String>> {
        let mut result = std::collections::HashMap::new();
        // Track which secret name owns each env var to detect collisions
        let mut env_owners: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        for name in names {
            let row: Option<(String, Option<String>)> =
                sqlx::query_as("SELECT value, env FROM secrets WHERE name = ?")
                    .bind(name)
                    .fetch_optional(&self.pool)
                    .await?;
            if let Some((value, env)) = row {
                let env_var = env.unwrap_or_else(|| name.clone());
                if let Some(prev_name) = env_owners.get(&env_var) {
                    anyhow::bail!(
                        "secrets '{prev_name}' and '{name}' both map to env var '{env_var}' — use only one"
                    );
                }
                env_owners.insert(env_var.clone(), name.clone());
                result.insert(env_var, value);
            }
        }
        Ok(result)
    }

    /// Delete a secret. Returns true if deleted, false if not found.
    pub async fn delete_secret(&self, name: &str) -> Result<bool> {
        let result = sqlx::query("DELETE FROM secrets WHERE name = ?")
            .bind(name)
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected() > 0)
    }

    /// Get all secrets as name→value pairs (used internally for session env injection).
    pub async fn get_all_secrets(&self) -> Result<std::collections::HashMap<String, String>> {
        let rows: Vec<(String, String)> = sqlx::query_as("SELECT name, value FROM secrets")
            .fetch_all(&self.pool)
            .await?;
        Ok(rows.into_iter().collect())
    }
}

fn row_to_session(row: &SqliteRow) -> Result<Session> {
    let id_str: String = row.get("id");
    let status_str: String = row.get("status");
    let created_str: String = row.get("created_at");
    let updated_str: String = row.get("updated_at");

    let metadata_json: Option<String> = row.get("metadata");
    let metadata = metadata_json
        .map(|s| serde_json::from_str::<std::collections::HashMap<String, String>>(&s))
        .transpose()?;

    let intervention_code_str: Option<String> = row.get("intervention_code");
    let intervention_code = intervention_code_str
        .map(|s| {
            s.parse::<InterventionCode>()
                .map_err(|e| anyhow::anyhow!(e))
        })
        .transpose()?;

    let intervention_at_str: Option<String> = row.get("intervention_at");
    let intervention_at = intervention_at_str
        .map(|s| DateTime::parse_from_rfc3339(&s).map(|dt| dt.with_timezone(&Utc)))
        .transpose()?;

    // Use try_get throughout to prevent panics from SQLite prepared statement
    // cache races during parallel tests (stale column count after ALTER TABLE).
    Ok(Session {
        id: Uuid::parse_str(&id_str)?,
        name: row.try_get("name").unwrap_or_default(),
        workdir: row.try_get("workdir").unwrap_or_default(),
        command: row.try_get("command").unwrap_or_default(),
        description: row.try_get("description").unwrap_or(None),
        status: status_str
            .parse::<SessionStatus>()
            .map_err(|e| anyhow::anyhow!(e))?,
        exit_code: row.try_get("exit_code").unwrap_or(None),
        backend_session_id: row.try_get("backend_session_id").unwrap_or(None),
        output_snapshot: row.try_get("output_snapshot").unwrap_or(None),
        metadata,
        ink: row.try_get("ink").unwrap_or(None),
        intervention_code,
        intervention_reason: row.try_get("intervention_reason").unwrap_or(None),
        intervention_at,
        last_output_at: {
            let s: Option<String> = row.try_get("last_output_at").unwrap_or(None);
            s.map(|s| DateTime::parse_from_rfc3339(&s).map(|dt| dt.with_timezone(&Utc)))
                .transpose()?
        },
        idle_since: {
            let s: Option<String> = row.try_get("idle_since").unwrap_or(None);
            s.map(|s| DateTime::parse_from_rfc3339(&s).map(|dt| dt.with_timezone(&Utc)))
                .transpose()?
        },
        idle_threshold_secs: {
            // Use try_get to handle rows where the column may not exist
            // (e.g., SQLite prepared statement cache before ALTER TABLE runs)
            let v: Option<i32> = row.try_get("idle_threshold_secs").unwrap_or(None);
            v.map(|n| u32::try_from(n).unwrap_or(0))
        },
        worktree_path: row.try_get("worktree_path").unwrap_or(None),
        worktree_branch: row.try_get("worktree_branch").unwrap_or(None),
        git_branch: row.try_get("git_branch").unwrap_or(None),
        git_commit: row.try_get("git_commit").unwrap_or(None),
        git_files_changed: {
            let v: Option<i32> = row.try_get("git_files_changed").unwrap_or(None);
            v.map(|n| u32::try_from(n).unwrap_or(0))
        },
        git_insertions: {
            let v: Option<i32> = row.try_get("git_insertions").unwrap_or(None);
            v.map(|n| u32::try_from(n).unwrap_or(0))
        },
        git_deletions: {
            let v: Option<i32> = row.try_get("git_deletions").unwrap_or(None);
            v.map(|n| u32::try_from(n).unwrap_or(0))
        },
        git_ahead: {
            let v: Option<i32> = row.try_get("git_ahead").unwrap_or(None);
            v.map(|n| u32::try_from(n).unwrap_or(0))
        },
        runtime: {
            let s: Option<String> = row.try_get("runtime").unwrap_or(None);
            s.and_then(|s| s.parse().ok()).unwrap_or_default()
        },
        created_at: DateTime::parse_from_rfc3339(&created_str)?.with_timezone(&Utc),
        updated_at: DateTime::parse_from_rfc3339(&updated_str)?.with_timezone(&Utc),
    })
}

#[allow(clippy::unnecessary_wraps)]
fn row_to_schedule(row: &SqliteRow) -> Result<pulpo_common::api::Schedule> {
    // Use try_get throughout to prevent panics from SQLite prepared statement
    // cache races during parallel tests (stale column count after ALTER TABLE).
    let secrets_json: String = row.try_get("secrets").unwrap_or_else(|_| "[]".to_owned());
    let secrets: Vec<String> = serde_json::from_str(&secrets_json).unwrap_or_default();
    Ok(pulpo_common::api::Schedule {
        id: row.try_get("id").unwrap_or_default(),
        name: row.try_get("name").unwrap_or_default(),
        cron: row.try_get("cron").unwrap_or_default(),
        command: row.try_get("command").unwrap_or_default(),
        workdir: row.try_get("workdir").unwrap_or_default(),
        target_node: row.try_get("target_node").unwrap_or(None),
        ink: row.try_get("ink").unwrap_or(None),
        description: row.try_get("description").unwrap_or(None),
        runtime: row.try_get("runtime").unwrap_or(None),
        secrets,
        worktree: row.try_get("worktree").unwrap_or(None),
        worktree_base: row.try_get("worktree_base").unwrap_or(None),
        enabled: row.try_get("enabled").unwrap_or(true),
        last_run_at: row.try_get("last_run_at").unwrap_or(None),
        last_session_id: row.try_get("last_session_id").unwrap_or(None),
        created_at: row.try_get("created_at").unwrap_or_default(),
    })
}

fn row_to_intervention_event(row: &SqliteRow) -> Result<InterventionEvent> {
    let created_str: String = row.get("created_at");
    let code_str: Option<String> = row.get("code");
    let code = code_str
        .map(|s| {
            s.parse::<InterventionCode>()
                .map_err(|e| anyhow::anyhow!(e))
        })
        .transpose()?;
    Ok(InterventionEvent {
        id: row.get("id"),
        session_id: row.get("session_id"),
        code,
        reason: row.get("reason"),
        created_at: DateTime::parse_from_rfc3339(&created_str)?.with_timezone(&Utc),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use pulpo_common::session::Runtime;

    fn make_session(name: &str) -> Session {
        Session {
            id: Uuid::new_v4(),
            name: name.into(),
            workdir: "/tmp/repo".into(),
            command: "echo hello".into(),
            description: Some("Fix the bug".into()),
            status: SessionStatus::Active,
            exit_code: None,
            backend_session_id: Some(name.to_owned()),
            output_snapshot: None,
            metadata: None,
            ink: None,
            intervention_code: None,
            intervention_reason: None,
            intervention_at: None,
            last_output_at: None,
            idle_since: None,
            idle_threshold_secs: None,
            worktree_path: None,
            worktree_branch: None,
            git_branch: None,
            git_commit: None,
            git_files_changed: None,
            git_insertions: None,
            git_deletions: None,
            git_ahead: None,
            runtime: Runtime::Tmux,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    async fn test_store() -> Store {
        let tmpdir = tempfile::tempdir().unwrap();
        // Leak so it persists for test lifetime
        let tmpdir = Box::leak(Box::new(tmpdir));
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();
        store
    }

    #[tokio::test]
    async fn test_new_creates_directory() {
        let tmpdir = tempfile::tempdir().unwrap();
        let data_dir = tmpdir.path().join("nested/deep");
        let store = Store::new(data_dir.to_str().unwrap()).await.unwrap();
        assert!(data_dir.exists());
        drop(store);
    }

    #[tokio::test]
    async fn test_migrate_creates_sessions_table() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();

        // Verify table exists by running a query
        let result = sqlx::query("SELECT count(*) as cnt FROM sessions")
            .fetch_one(store.pool())
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_migrate_is_idempotent() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();
        // Running migrate again should not error
        store.migrate().await.unwrap();
    }

    #[tokio::test]
    async fn test_pool_returns_valid_pool() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        let pool = store.pool();
        // Verify pool works
        let row = sqlx::query_scalar::<_, i32>("SELECT 1")
            .fetch_one(pool)
            .await
            .unwrap();
        assert_eq!(row, 1);
    }

    #[tokio::test]
    async fn test_insert_and_get_session() {
        let store = test_store().await;
        let session = make_session("test-roundtrip");

        store.insert_session(&session).await.unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();

        assert_eq!(fetched.id, session.id);
        assert_eq!(fetched.name, "test-roundtrip");
        assert_eq!(fetched.workdir, "/tmp/repo");

        assert_eq!(fetched.status, SessionStatus::Active);

        assert_eq!(fetched.exit_code, None);
        assert_eq!(fetched.backend_session_id, Some("test-roundtrip".into()));
    }

    #[tokio::test]
    async fn test_get_session_not_found() {
        let store = test_store().await;
        let result = store.get_session("nonexistent").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_get_session_by_name() {
        let store = test_store().await;
        let session = make_session("lookup-by-name");
        store.insert_session(&session).await.unwrap();

        let fetched = store.get_session("lookup-by-name").await.unwrap().unwrap();
        assert_eq!(fetched.id, session.id);
        assert_eq!(fetched.name, "lookup-by-name");
    }

    #[tokio::test]
    async fn test_get_session_by_name_not_found() {
        let store = test_store().await;
        let session = make_session("existing");
        store.insert_session(&session).await.unwrap();

        let result = store.get_session("nonexistent-name").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_get_session_prefers_live_over_terminal() {
        let store = test_store().await;

        // Insert a stopped session with name "dup"
        let mut stopped = make_session("dup");
        stopped.id = uuid::Uuid::new_v4();
        stopped.status = SessionStatus::Stopped;
        // Remove from unique index by marking stopped before insert
        store.insert_session(&stopped).await.unwrap();

        // Insert a ready session with the same name "dup"
        let mut ready = make_session("dup-ready");
        ready.id = uuid::Uuid::new_v4();
        ready.name = "dup".into();
        ready.status = SessionStatus::Ready;
        // The unique index only covers creating/active/idle/ready,
        // and stopped is excluded, so this insert should work
        store.insert_session(&ready).await.unwrap();

        // get_session by name should return the ready one, not the stopped one
        let fetched = store.get_session("dup").await.unwrap().unwrap();
        assert_eq!(fetched.status, SessionStatus::Ready);
        assert_eq!(fetched.id, ready.id);
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_true() {
        let store = test_store().await;
        let session = make_session("my-session");
        store.insert_session(&session).await.unwrap();

        assert!(
            store
                .has_active_session_by_name("my-session")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_false_no_match() {
        let store = test_store().await;
        assert!(
            !store
                .has_active_session_by_name("nonexistent")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_false_stopped() {
        let store = test_store().await;
        let mut session = make_session("stopped-session");
        session.status = SessionStatus::Stopped;
        store.insert_session(&session).await.unwrap();

        assert!(
            !store
                .has_active_session_by_name("stopped-session")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_stale() {
        let store = test_store().await;
        let mut session = make_session("idle-session");
        session.status = SessionStatus::Idle;
        store.insert_session(&session).await.unwrap();

        assert!(
            store
                .has_active_session_by_name("idle-session")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_creating() {
        let store = test_store().await;
        let mut session = make_session("creating-session");
        session.status = SessionStatus::Creating;
        store.insert_session(&session).await.unwrap();

        assert!(
            store
                .has_active_session_by_name("creating-session")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_ready() {
        let store = test_store().await;
        let mut session = make_session("ready-session");
        session.status = SessionStatus::Ready;
        store.insert_session(&session).await.unwrap();

        assert!(
            store
                .has_active_session_by_name("ready-session")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_excluding_self() {
        let store = test_store().await;
        let mut session = make_session("ready-session");
        session.status = SessionStatus::Ready;
        store.insert_session(&session).await.unwrap();

        // Excluding self should return false (no *other* active session with this name)
        assert!(
            !store
                .has_active_session_by_name_excluding(
                    "ready-session",
                    Some(&session.id.to_string()),
                )
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_has_active_session_by_name_excluding_different_id() {
        let store = test_store().await;
        let mut session = make_session("clash-session");
        session.status = SessionStatus::Active;
        store.insert_session(&session).await.unwrap();

        // Excluding a different ID should still find the active session
        assert!(
            store
                .has_active_session_by_name_excluding(
                    "clash-session",
                    Some(&uuid::Uuid::new_v4().to_string()),
                )
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_unique_index_prevents_duplicate_live_names() {
        let store = test_store().await;
        let s1 = make_session("dup-name");
        store.insert_session(&s1).await.unwrap();
        // Second insert with same name and live status should fail at DB level
        let mut s2 = make_session("dup-name");
        s2.id = uuid::Uuid::new_v4();
        let result = store.insert_session(&s2).await;
        assert!(result.is_err(), "expected unique constraint violation");
    }

    #[tokio::test]
    async fn test_unique_index_allows_reuse_after_stop() {
        let store = test_store().await;
        let s1 = make_session("reuse-name");
        store.insert_session(&s1).await.unwrap();
        store
            .update_session_status(&s1.id.to_string(), SessionStatus::Stopped)
            .await
            .unwrap();
        // New session with same name should succeed — old one is stopped
        let mut s2 = make_session("reuse-name");
        s2.id = uuid::Uuid::new_v4();
        store.insert_session(&s2).await.unwrap();
    }

    #[tokio::test]
    async fn test_list_sessions_empty() {
        let store = test_store().await;
        let sessions = store.list_sessions().await.unwrap();
        assert!(sessions.is_empty());
    }

    #[tokio::test]
    async fn test_list_sessions_multiple() {
        let store = test_store().await;
        let s1 = make_session("first");
        let s2 = make_session("second");

        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let sessions = store.list_sessions().await.unwrap();
        assert_eq!(sessions.len(), 2);
    }

    #[tokio::test]
    async fn test_update_session_status() {
        let store = test_store().await;
        let session = make_session("update-test");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_status(&session.id.to_string(), SessionStatus::Ready)
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.status, SessionStatus::Ready);
    }

    #[tokio::test]
    async fn test_delete_session() {
        let store = test_store().await;
        let session = make_session("delete-test");
        store.insert_session(&session).await.unwrap();

        store.delete_session(&session.id.to_string()).await.unwrap();

        let result = store.get_session(&session.id.to_string()).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_insert_session_with_all_none_optionals() {
        let store = test_store().await;
        let session = Session {
            id: Uuid::new_v4(),
            name: "minimal".into(),
            workdir: "/tmp".into(),
            command: "echo hello".into(),
            description: Some("test".into()),
            status: SessionStatus::Creating,
            exit_code: None,
            backend_session_id: None,
            output_snapshot: None,
            metadata: None,
            ink: None,
            intervention_code: None,
            intervention_reason: None,
            intervention_at: None,
            last_output_at: None,
            idle_since: None,
            idle_threshold_secs: None,
            worktree_path: None,
            worktree_branch: None,
            git_branch: None,
            git_commit: None,
            git_files_changed: None,
            git_insertions: None,
            git_deletions: None,
            git_ahead: None,
            runtime: Runtime::Tmux,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        store.insert_session(&session).await.unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();

        assert!(fetched.exit_code.is_none());
        assert!(fetched.backend_session_id.is_none());
        assert!(fetched.output_snapshot.is_none());
    }

    const TEST_UUID: &str = "550e8400-e29b-41d4-a716-446655440000";

    #[tokio::test]
    async fn test_row_to_session_invalid_status() {
        let store = test_store().await;
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                created_at, updated_at, command)
             VALUES (?, 'test', '/tmp', '', '', 'bad_status', '',
                '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00', 'echo test')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();
        let result = store.get_session(TEST_UUID).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_row_to_session_invalid_uuid() {
        let store = test_store().await;
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                created_at, updated_at)
             VALUES ('not-a-uuid', 'test', '/tmp', 'claude', 'test', 'active', 'interactive',
                '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')",
        )
        .execute(store.pool())
        .await
        .unwrap();
        let result = store.get_session("not-a-uuid").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_row_to_session_invalid_datetime() {
        let store = test_store().await;
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                created_at, updated_at)
             VALUES (?, 'test', '/tmp', 'claude', 'test', 'active', 'interactive',
                'not-a-date', '2024-01-01T00:00:00+00:00')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();
        let result = store.get_session(TEST_UUID).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_list_sessions_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store.list_sessions().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_session_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store.get_session("test-id").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_insert_session_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let session = make_session("fail-test");
        let result = store.insert_session(&session).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_update_session_status_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store
            .update_session_status("test-id", SessionStatus::Stopped)
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_delete_session_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store.delete_session("test-id").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_store_is_clone() {
        let store = test_store().await;
        let cloned = store.clone();
        // Both should work
        let sessions = cloned.list_sessions().await.unwrap();
        assert!(sessions.is_empty());
    }

    #[tokio::test]
    async fn test_data_dir_accessor() {
        let store = test_store().await;
        let dir = store.data_dir();
        assert!(!dir.is_empty());
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_by_status() {
        let store = test_store().await;
        let mut s1 = make_session("running-1");
        s1.status = SessionStatus::Active;
        let mut s2 = make_session("completed-1");
        s2.status = SessionStatus::Ready;
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            status: Some("active".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].status, SessionStatus::Active);
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_by_multiple_statuses() {
        let store = test_store().await;
        let mut s1 = make_session("running-2");
        s1.status = SessionStatus::Active;
        let mut s2 = make_session("completed-2");
        s2.status = SessionStatus::Ready;
        let mut s3 = make_session("dead-1");
        s3.status = SessionStatus::Stopped;
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();
        store.insert_session(&s3).await.unwrap();

        let query = ListSessionsQuery {
            status: Some("active,ready".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 2);
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_by_search() {
        let store = test_store().await;
        let mut s1 = make_session("api-fix");
        s1.command = "Fix the API endpoint".into();
        let mut s2 = make_session("ui-refactor");
        s2.command = "Refactor the UI components".into();
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            search: Some("API".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].name, "api-fix");
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_search_by_name() {
        let store = test_store().await;
        let s1 = make_session("frontend-fix");
        let s2 = make_session("backend-fix");
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            search: Some("frontend".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].name, "frontend-fix");
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_sort_by_name() {
        let store = test_store().await;
        let s1 = make_session("aaa");
        let s2 = make_session("zzz");
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            sort: Some("name".into()),
            order: Some("asc".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions[0].name, "aaa");
        assert_eq!(sessions[1].name, "zzz");
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_sort_desc() {
        let store = test_store().await;
        let s1 = make_session("aaa");
        let s2 = make_session("zzz");
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            sort: Some("name".into()),
            order: Some("desc".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions[0].name, "zzz");
        assert_eq!(sessions[1].name, "aaa");
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_empty_returns_all() {
        let store = test_store().await;
        let s1 = make_session("one");
        let s2 = make_session("two");
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery::default();
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 2);
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_combined_filters() {
        let store = test_store().await;
        let mut s1 = make_session("api-fix");
        s1.status = SessionStatus::Active;
        s1.command = "Fix the API".into();
        let mut s2 = make_session("api-refactor");
        s2.status = SessionStatus::Ready;
        s2.command = "Refactor the API".into();
        let mut s3 = make_session("ui-fix");
        s3.status = SessionStatus::Active;
        s3.command = "Fix the UI".into();
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();
        store.insert_session(&s3).await.unwrap();

        let query = ListSessionsQuery {
            status: Some("active".into()),
            search: Some("API".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].name, "api-fix");
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_sort_by_status() {
        let store = test_store().await;
        let mut s1 = make_session("first");
        s1.status = SessionStatus::Active;
        let mut s2 = make_session("second");
        s2.status = SessionStatus::Ready;
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            sort: Some("status".into()),
            order: Some("asc".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 2);
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_sort_by_provider() {
        let store = test_store().await;
        let s1 = make_session("claude-task");
        let mut s2 = make_session("codex-task");
        s2.command = String::new();
        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();

        let query = ListSessionsQuery {
            sort: Some("provider".into()),
            order: Some("asc".into()),
            ..Default::default()
        };
        let sessions = store.list_sessions_filtered(&query).await.unwrap();
        assert_eq!(sessions.len(), 2);
    }

    #[tokio::test]
    async fn test_update_session_intervention() {
        let store = test_store().await;
        let session = make_session("intervene-test");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_intervention(
                &session.id.to_string(),
                InterventionCode::MemoryPressure,
                "Memory usage 95% (512MB/8192MB)",
            )
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.status, SessionStatus::Stopped);
        assert_eq!(
            fetched.intervention_code,
            Some(InterventionCode::MemoryPressure)
        );
        assert_eq!(
            fetched.intervention_reason.as_deref(),
            Some("Memory usage 95% (512MB/8192MB)")
        );
        assert!(fetched.intervention_at.is_some());
    }

    #[tokio::test]
    async fn test_update_session_intervention_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store
            .update_session_intervention("test-id", InterventionCode::UserStop, "reason")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_clear_session_intervention() {
        let store = test_store().await;
        let session = make_session("clear-test");
        store.insert_session(&session).await.unwrap();

        // Set intervention first
        store
            .update_session_intervention(
                &session.id.to_string(),
                InterventionCode::UserStop,
                "test reason",
            )
            .await
            .unwrap();

        // Clear it
        store
            .clear_session_intervention(&session.id.to_string())
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.intervention_code.is_none());
        assert!(fetched.intervention_reason.is_none());
        assert!(fetched.intervention_at.is_none());
    }

    #[tokio::test]
    async fn test_clear_session_intervention_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store.clear_session_intervention("test-id").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_update_session_output_snapshot() {
        let store = test_store().await;
        let session = make_session("snapshot-test");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_output_snapshot(
                &session.id.to_string(),
                "$ vitest\nrunning tests...\nOOM killed",
            )
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            fetched.output_snapshot.as_deref(),
            Some("$ vitest\nrunning tests...\nOOM killed")
        );
    }

    #[tokio::test]
    async fn test_update_session_output_snapshot_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store
            .update_session_output_snapshot("test-id", "snapshot")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_intervention_roundtrip_with_insert() {
        let store = test_store().await;
        let mut session = make_session("intervention-insert");
        session.intervention_reason = Some("pre-set reason".into());
        session.intervention_at = Some(Utc::now());

        store.insert_session(&session).await.unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();

        assert_eq!(
            fetched.intervention_reason.as_deref(),
            Some("pre-set reason")
        );
        assert!(fetched.intervention_at.is_some());
    }

    #[tokio::test]
    async fn test_row_to_session_invalid_intervention_at() {
        let store = test_store().await;
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                intervention_at, created_at, updated_at)
             VALUES (?, 'test', '/tmp', 'claude', 'test', 'active', 'interactive',
                'not-a-date', '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();
        let result = store.get_session(TEST_UUID).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_list_sessions_filtered_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE sessions")
            .execute(store.pool())
            .await
            .unwrap();
        let query = ListSessionsQuery::default();
        let result = store.list_sessions_filtered(&query).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_intervention_events_appended() {
        let store = test_store().await;
        let session = make_session("events-test");
        store.insert_session(&session).await.unwrap();
        let sid = session.id.to_string();

        // First intervention
        store
            .update_session_intervention(&sid, InterventionCode::MemoryPressure, "Memory 95%")
            .await
            .unwrap();

        // Simulate a second intervention (e.g., session was resumed and hit pressure again)
        // Reset session to running first so the scenario makes sense
        sqlx::query("UPDATE sessions SET status = 'active' WHERE id = ?")
            .bind(&sid)
            .execute(store.pool())
            .await
            .unwrap();
        store
            .update_session_intervention(&sid, InterventionCode::MemoryPressure, "Memory 98%")
            .await
            .unwrap();

        let events = store.list_intervention_events(&sid).await.unwrap();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].code, Some(InterventionCode::MemoryPressure));
        assert_eq!(events[0].reason, "Memory 95%");
        assert_eq!(events[1].code, Some(InterventionCode::MemoryPressure));
        assert_eq!(events[1].reason, "Memory 98%");
        assert_eq!(events[0].session_id, sid);
        assert_eq!(events[1].session_id, sid);
        assert!(events[0].id < events[1].id);
    }

    #[tokio::test]
    async fn test_intervention_events_empty_for_unknown_session() {
        let store = test_store().await;
        let events = store
            .list_intervention_events("nonexistent-id")
            .await
            .unwrap();
        assert!(events.is_empty());
    }

    #[tokio::test]
    async fn test_intervention_events_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE intervention_events")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store.list_intervention_events("any-id").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_intervention_event_debug_clone() {
        let event = InterventionEvent {
            id: 1,
            session_id: "test-id".into(),
            code: Some(InterventionCode::MemoryPressure),
            reason: "Memory 95%".into(),
            created_at: Utc::now(),
        };
        let debug = format!("{event:?}");
        assert!(debug.contains("Memory 95%"));
        #[allow(clippy::redundant_clone)]
        let cloned = event.clone();
        assert_eq!(cloned.reason, "Memory 95%");
    }

    #[tokio::test]
    async fn test_last_output_at_updated_on_change() {
        let store = test_store().await;
        let session = make_session("output-ts");
        let id = session.id.to_string();
        store.insert_session(&session).await.unwrap();

        // Initially null
        let fetched = store.get_session(&id).await.unwrap().unwrap();
        assert!(fetched.last_output_at.is_none());

        // First snapshot — sets last_output_at
        store
            .update_session_output_snapshot(&id, "hello")
            .await
            .unwrap();
        let fetched = store.get_session(&id).await.unwrap().unwrap();
        assert!(fetched.last_output_at.is_some());
        let ts1 = fetched.last_output_at.unwrap();

        // Different content — updates last_output_at
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        store
            .update_session_output_snapshot(&id, "world")
            .await
            .unwrap();
        let fetched = store.get_session(&id).await.unwrap().unwrap();
        let ts2 = fetched.last_output_at.unwrap();
        assert!(ts2 > ts1);
    }

    #[tokio::test]
    async fn test_last_output_at_not_updated_on_same() {
        let store = test_store().await;
        let session = make_session("output-same");
        let id = session.id.to_string();
        store.insert_session(&session).await.unwrap();

        // Set initial snapshot
        store
            .update_session_output_snapshot(&id, "same content")
            .await
            .unwrap();
        let fetched = store.get_session(&id).await.unwrap().unwrap();
        let ts1 = fetched.last_output_at.unwrap();

        // Same content — last_output_at should NOT change
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        store
            .update_session_output_snapshot(&id, "same content")
            .await
            .unwrap();
        let fetched = store.get_session(&id).await.unwrap().unwrap();
        let ts2 = fetched.last_output_at.unwrap();
        assert_eq!(ts1, ts2);
    }

    #[tokio::test]
    async fn test_get_session_invalid_last_output_at() {
        let store = test_store().await;
        let session = make_session("bad-ts");
        store.insert_session(&session).await.unwrap();

        sqlx::query("UPDATE sessions SET last_output_at = 'not-a-date' WHERE id = ?")
            .bind(session.id.to_string())
            .execute(store.pool())
            .await
            .unwrap();

        let result = store.get_session(&session.id.to_string()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_session_invalid_updated_at() {
        let store = test_store().await;
        let session = make_session("bad-updated");
        store.insert_session(&session).await.unwrap();

        sqlx::query("UPDATE sessions SET updated_at = 'not-a-date' WHERE id = ?")
            .bind(session.id.to_string())
            .execute(store.pool())
            .await
            .unwrap();

        let result = store.get_session(&session.id.to_string()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_insert_session_with_last_output_at() {
        let store = test_store().await;
        let mut session = make_session("with-output-ts");
        session.last_output_at = Some(Utc::now());
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.last_output_at.is_some());
    }

    #[tokio::test]
    async fn test_get_session_invalid_uuid() {
        let store = test_store().await;
        let session = make_session("bad-uuid");
        store.insert_session(&session).await.unwrap();

        sqlx::query("UPDATE sessions SET id = 'not-a-uuid' WHERE id = ?")
            .bind(session.id.to_string())
            .execute(store.pool())
            .await
            .unwrap();

        let result = store.get_session("not-a-uuid").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_list_intervention_events_invalid_created_at() {
        let store = test_store().await;
        let session = make_session("bad-event");
        store.insert_session(&session).await.unwrap();

        // Insert event with invalid timestamp directly
        sqlx::query(
            "INSERT INTO intervention_events (session_id, reason, created_at) VALUES (?, ?, ?)",
        )
        .bind(session.id.to_string())
        .bind("test")
        .bind("not-a-date")
        .execute(store.pool())
        .await
        .unwrap();

        let result = store
            .list_intervention_events(&session.id.to_string())
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_update_session_idle_since() {
        let store = test_store().await;
        let session = make_session("idle-test");
        store.insert_session(&session).await.unwrap();

        // Initially None
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.idle_since.is_none());

        // Set idle_since
        store
            .update_session_idle_since(&session.id.to_string())
            .await
            .unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.idle_since.is_some());
    }

    #[tokio::test]
    async fn test_clear_session_idle_since() {
        let store = test_store().await;
        let session = make_session("idle-clear");
        store.insert_session(&session).await.unwrap();

        // Set idle_since
        store
            .update_session_idle_since(&session.id.to_string())
            .await
            .unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.idle_since.is_some());

        // Clear idle_since
        store
            .clear_session_idle_since(&session.id.to_string())
            .await
            .unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.idle_since.is_none());
    }

    #[tokio::test]
    async fn test_insert_session_with_idle_since() {
        let store = test_store().await;
        let mut session = make_session("with-idle");
        session.idle_since = Some(Utc::now());
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.idle_since.is_some());
    }

    #[tokio::test]
    async fn test_get_session_invalid_idle_since() {
        let store = test_store().await;
        let session = make_session("bad-idle");
        store.insert_session(&session).await.unwrap();

        sqlx::query("UPDATE sessions SET idle_since = 'not-a-date' WHERE id = ?")
            .bind(session.id.to_string())
            .execute(store.pool())
            .await
            .unwrap();

        let result = store.get_session(&session.id.to_string()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_new_session_fields_roundtrip() {
        let store = test_store().await;
        let mut session = make_session("new-fields-test");
        session.metadata = Some(
            [
                ("discord_channel".into(), "123".into()),
                ("user".into(), "alice".into()),
            ]
            .into_iter()
            .collect(),
        );
        session.ink = Some("reviewer".into());

        store.insert_session(&session).await.unwrap();
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();

        let meta = fetched.metadata.unwrap();
        assert_eq!(meta.get("discord_channel").unwrap(), "123");
        assert_eq!(meta.get("user").unwrap(), "alice");
        assert_eq!(fetched.ink, Some("reviewer".into()));
    }

    #[tokio::test]
    async fn test_migrate_closed_pool_error() {
        let store = test_store().await;
        store.pool().close().await;
        let result = store.migrate().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_intervention_code_roundtrip() {
        let store = test_store().await;
        let mut session = make_session("code-roundtrip");
        session.intervention_code = Some(InterventionCode::IdleTimeout);
        session.intervention_reason = Some("Idle for 10 minutes".into());
        session.intervention_at = Some(Utc::now());
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            fetched.intervention_code,
            Some(InterventionCode::IdleTimeout)
        );
        assert_eq!(
            fetched.intervention_reason.as_deref(),
            Some("Idle for 10 minutes")
        );
    }

    #[tokio::test]
    async fn test_intervention_code_none_roundtrip() {
        let store = test_store().await;
        let session = make_session("code-none");
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.intervention_code.is_none());
    }

    #[tokio::test]
    async fn test_row_to_session_invalid_intervention_code() {
        let store = test_store().await;
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                intervention_code, created_at, updated_at)
             VALUES (?, 'test', '/tmp', 'claude', 'test', 'active', 'interactive',
                'invalid_code', '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();
        let result = store.get_session(TEST_UUID).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_intervention_event_code_roundtrip() {
        let store = test_store().await;
        let session = make_session("event-code");
        store.insert_session(&session).await.unwrap();
        let sid = session.id.to_string();

        store
            .update_session_intervention(&sid, InterventionCode::IdleTimeout, "Idle 15 min")
            .await
            .unwrap();

        let events = store.list_intervention_events(&sid).await.unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].code, Some(InterventionCode::IdleTimeout));
        assert_eq!(events[0].reason, "Idle 15 min");
    }

    #[tokio::test]
    async fn test_intervention_event_user_stop_code() {
        let store = test_store().await;
        let session = make_session("user-stop");
        store.insert_session(&session).await.unwrap();
        let sid = session.id.to_string();

        store
            .update_session_intervention(&sid, InterventionCode::UserStop, "Manual stop")
            .await
            .unwrap();

        let fetched = store.get_session(&sid).await.unwrap().unwrap();
        assert_eq!(fetched.intervention_code, Some(InterventionCode::UserStop));

        let events = store.list_intervention_events(&sid).await.unwrap();
        assert_eq!(events[0].code, Some(InterventionCode::UserStop));
    }

    #[tokio::test]
    async fn test_idle_status_roundtrip() {
        let store = test_store().await;
        let session = make_session("idle-test");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_status(&session.id.to_string(), SessionStatus::Idle)
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.status, SessionStatus::Idle);
    }

    // -- Push subscription tests --

    #[tokio::test]
    async fn test_push_subscription_save_and_list() {
        let store = test_store().await;
        store
            .save_push_subscription("https://push.example.com/1", "p256dh-key", "auth-key")
            .await
            .unwrap();

        let subs = store.list_push_subscriptions().await.unwrap();
        assert_eq!(subs.len(), 1);
        assert_eq!(subs[0].endpoint, "https://push.example.com/1");
        assert_eq!(subs[0].p256dh, "p256dh-key");
        assert_eq!(subs[0].auth, "auth-key");
    }

    #[tokio::test]
    async fn test_push_subscription_save_replaces_on_same_endpoint() {
        let store = test_store().await;
        store
            .save_push_subscription("https://push.example.com/1", "old-p256dh", "old-auth")
            .await
            .unwrap();
        store
            .save_push_subscription("https://push.example.com/1", "new-p256dh", "new-auth")
            .await
            .unwrap();

        let subs = store.list_push_subscriptions().await.unwrap();
        assert_eq!(subs.len(), 1);
        assert_eq!(subs[0].p256dh, "new-p256dh");
        assert_eq!(subs[0].auth, "new-auth");
    }

    #[tokio::test]
    async fn test_push_subscription_multiple_endpoints() {
        let store = test_store().await;
        store
            .save_push_subscription("https://push.example.com/1", "p1", "a1")
            .await
            .unwrap();
        store
            .save_push_subscription("https://push.example.com/2", "p2", "a2")
            .await
            .unwrap();

        let subs = store.list_push_subscriptions().await.unwrap();
        assert_eq!(subs.len(), 2);
    }

    #[tokio::test]
    async fn test_push_subscription_delete() {
        let store = test_store().await;
        store
            .save_push_subscription("https://push.example.com/1", "p1", "a1")
            .await
            .unwrap();
        store
            .save_push_subscription("https://push.example.com/2", "p2", "a2")
            .await
            .unwrap();

        store
            .delete_push_subscription("https://push.example.com/1")
            .await
            .unwrap();

        let subs = store.list_push_subscriptions().await.unwrap();
        assert_eq!(subs.len(), 1);
        assert_eq!(subs[0].endpoint, "https://push.example.com/2");
    }

    #[tokio::test]
    async fn test_push_subscription_delete_nonexistent() {
        let store = test_store().await;
        // Should not error when deleting a non-existent endpoint
        store
            .delete_push_subscription("https://push.example.com/nonexistent")
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_push_subscription_list_empty() {
        let store = test_store().await;
        let subs = store.list_push_subscriptions().await.unwrap();
        assert!(subs.is_empty());
    }

    #[tokio::test]
    async fn test_push_subscription_debug_clone() {
        let sub = PushSubscription {
            endpoint: "https://push.example.com/1".into(),
            p256dh: "key".into(),
            auth: "auth".into(),
        };
        let debug = format!("{sub:?}");
        assert!(debug.contains("push.example.com"));
        #[allow(clippy::redundant_clone)]
        let cloned = sub.clone();
        assert_eq!(cloned.endpoint, "https://push.example.com/1");
    }

    #[tokio::test]
    async fn test_push_subscription_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE push_subscriptions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store.list_push_subscriptions().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_push_subscription_save_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE push_subscriptions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store
            .save_push_subscription("https://push.example.com/1", "p", "a")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_push_subscription_delete_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE push_subscriptions")
            .execute(store.pool())
            .await
            .unwrap();
        let result = store
            .delete_push_subscription("https://push.example.com/1")
            .await;
        assert!(result.is_err());
    }

    // -- Schedule tests --

    #[tokio::test]
    async fn test_schedule_crud() {
        let store = test_store().await;
        let schedule = pulpo_common::api::Schedule {
            id: "sched-1".into(),
            name: "nightly-review".into(),
            cron: "0 3 * * *".into(),
            command: "claude -p 'review'".into(),
            workdir: "/tmp".into(),
            target_node: None,
            ink: None,
            description: Some("Nightly review".into()),
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            created_at: chrono::Utc::now().to_rfc3339(),
        };
        store.insert_schedule(&schedule).await.unwrap();

        let fetched = store.get_schedule("nightly-review").await.unwrap().unwrap();
        assert_eq!(fetched.name, "nightly-review");
        assert_eq!(fetched.cron, "0 3 * * *");
        assert!(fetched.enabled);

        let all = store.list_schedules().await.unwrap();
        assert_eq!(all.len(), 1);

        store
            .update_schedule_enabled(&schedule.id, false)
            .await
            .unwrap();
        let updated = store.get_schedule(&schedule.id).await.unwrap().unwrap();
        assert!(!updated.enabled);

        store
            .update_schedule_last_run(&schedule.id, "session-123")
            .await
            .unwrap();
        let ran = store.get_schedule(&schedule.id).await.unwrap().unwrap();
        assert!(ran.last_run_at.is_some());
        assert_eq!(ran.last_session_id, Some("session-123".into()));

        store.delete_schedule(&schedule.id).await.unwrap();
        assert!(store.get_schedule(&schedule.id).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_list_schedule_runs() {
        let store = test_store().await;

        // Insert matching sessions (name starts with "nightly-")
        let s1 = make_session("nightly-001");
        let s2 = make_session("nightly-002");
        // Insert non-matching session
        let s3 = make_session("other-task");

        store.insert_session(&s1).await.unwrap();
        store.insert_session(&s2).await.unwrap();
        store.insert_session(&s3).await.unwrap();

        let runs = store.list_schedule_runs("nightly", 20).await.unwrap();
        assert_eq!(runs.len(), 2);
        for run in &runs {
            assert!(run.name.starts_with("nightly-"));
        }

        // Test limit
        let runs = store.list_schedule_runs("nightly", 1).await.unwrap();
        assert_eq!(runs.len(), 1);

        // Test no matches
        let runs = store.list_schedule_runs("nonexistent", 20).await.unwrap();
        assert!(runs.is_empty());
    }

    #[tokio::test]
    async fn test_schedule_unique_name() {
        let store = test_store().await;
        let schedule = pulpo_common::api::Schedule {
            id: "s1".into(),
            name: "dup".into(),
            cron: "* * * * *".into(),
            command: "echo".into(),
            workdir: "/tmp".into(),
            target_node: None,
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            created_at: chrono::Utc::now().to_rfc3339(),
        };
        store.insert_schedule(&schedule).await.unwrap();
        let dup = pulpo_common::api::Schedule {
            id: "s2".into(),
            name: "dup".into(),
            ..schedule
        };
        assert!(store.insert_schedule(&dup).await.is_err());
    }

    #[tokio::test]
    async fn test_schedule_execution_fields_roundtrip() {
        let store = test_store().await;
        let schedule = pulpo_common::api::Schedule {
            id: "sched-exec".into(),
            name: "docker-review".into(),
            cron: "0 3 * * *".into(),
            command: "claude -p 'review'".into(),
            workdir: "/tmp".into(),
            target_node: None,
            ink: Some("coder".into()),
            description: Some("Docker review".into()),
            runtime: Some("docker".into()),
            secrets: vec!["GH_TOKEN".into(), "NPM_TOKEN".into()],
            worktree: Some(true),
            worktree_base: Some("main".into()),
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            created_at: chrono::Utc::now().to_rfc3339(),
        };
        store.insert_schedule(&schedule).await.unwrap();

        let fetched = store.get_schedule("docker-review").await.unwrap().unwrap();
        assert_eq!(fetched.runtime, Some("docker".into()));
        assert_eq!(fetched.secrets, vec!["GH_TOKEN", "NPM_TOKEN"]);
        assert_eq!(fetched.worktree, Some(true));
        assert_eq!(fetched.worktree_base, Some("main".into()));
    }

    #[tokio::test]
    async fn test_schedule_execution_fields_default_empty() {
        let store = test_store().await;
        let schedule = pulpo_common::api::Schedule {
            id: "sched-empty".into(),
            name: "plain".into(),
            cron: "0 3 * * *".into(),
            command: "echo".into(),
            workdir: "/tmp".into(),
            target_node: None,
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            created_at: chrono::Utc::now().to_rfc3339(),
        };
        store.insert_schedule(&schedule).await.unwrap();

        let fetched = store.get_schedule("plain").await.unwrap().unwrap();
        assert!(fetched.runtime.is_none());
        assert!(fetched.secrets.is_empty());
        assert!(fetched.worktree.is_none());
        assert!(fetched.worktree_base.is_none());
    }

    // -- update_session_metadata_field tests --

    #[tokio::test]
    async fn test_update_session_metadata_field_empty_metadata() {
        let store = test_store().await;
        let session = make_session("meta-empty");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_metadata_field(
                &session.id.to_string(),
                "pr_url",
                "https://github.com/a/b/pull/1",
            )
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        let meta = fetched.metadata.unwrap();
        assert_eq!(meta.get("pr_url").unwrap(), "https://github.com/a/b/pull/1");
    }

    #[tokio::test]
    async fn test_update_session_metadata_field_existing_metadata() {
        let store = test_store().await;
        let mut session = make_session("meta-existing");
        session.metadata =
            Some(std::iter::once(("discord_channel".into(), "123".into())).collect());
        store.insert_session(&session).await.unwrap();

        store
            .update_session_metadata_field(&session.id.to_string(), "branch", "feature/test")
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        let meta = fetched.metadata.unwrap();
        // Original key preserved
        assert_eq!(meta.get("discord_channel").unwrap(), "123");
        // New key added
        assert_eq!(meta.get("branch").unwrap(), "feature/test");
    }

    #[tokio::test]
    async fn test_update_session_metadata_field_overwrite_key() {
        let store = test_store().await;
        let session = make_session("meta-overwrite");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_metadata_field(&session.id.to_string(), "pr_url", "https://old")
            .await
            .unwrap();
        store
            .update_session_metadata_field(&session.id.to_string(), "pr_url", "https://new")
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            fetched.metadata.unwrap().get("pr_url").unwrap(),
            "https://new"
        );
    }

    #[tokio::test]
    async fn test_update_session_metadata_field_nonexistent_session() {
        let store = test_store().await;
        let result = store
            .update_session_metadata_field("nonexistent-id", "key", "value")
            .await;
        assert!(result.is_err());
    }

    // -- Secret tests --

    #[tokio::test]
    async fn test_set_and_get_secret() {
        let store = test_store().await;
        store.set_secret("MY_TOKEN", "abc123").await.unwrap();
        let value = store.get_secret("MY_TOKEN").await.unwrap();
        assert_eq!(value, Some("abc123".into()));
    }

    #[tokio::test]
    async fn test_get_secret_not_found() {
        let store = test_store().await;
        let value = store.get_secret("NONEXISTENT").await.unwrap();
        assert!(value.is_none());
    }

    #[tokio::test]
    async fn test_set_secret_upsert() {
        let store = test_store().await;
        store.set_secret("MY_TOKEN", "old").await.unwrap();
        store.set_secret("MY_TOKEN", "new").await.unwrap();
        let value = store.get_secret("MY_TOKEN").await.unwrap();
        assert_eq!(value, Some("new".into()));
    }

    #[tokio::test]
    async fn test_list_secret_names() {
        let store = test_store().await;
        store.set_secret("B_TOKEN", "val").await.unwrap();
        store.set_secret("A_TOKEN", "val").await.unwrap();
        let names = store.list_secret_names().await.unwrap();
        assert_eq!(names.len(), 2);
        assert_eq!(names[0].0, "A_TOKEN");
        assert!(names[0].1.is_none()); // no env override
        assert_eq!(names[1].0, "B_TOKEN");
        // created_at should be non-empty
        assert!(!names[0].2.is_empty());
    }

    #[tokio::test]
    async fn test_list_secret_names_with_env() {
        let store = test_store().await;
        store
            .set_secret_with_env("GH_WORK", "token1", Some("GITHUB_TOKEN"))
            .await
            .unwrap();
        store.set_secret("PLAIN_KEY", "token2").await.unwrap();
        let names = store.list_secret_names().await.unwrap();
        assert_eq!(names.len(), 2);
        assert_eq!(names[0].0, "GH_WORK");
        assert_eq!(names[0].1.as_deref(), Some("GITHUB_TOKEN"));
        assert_eq!(names[1].0, "PLAIN_KEY");
        assert!(names[1].1.is_none());
    }

    #[tokio::test]
    async fn test_list_secret_names_empty() {
        let store = test_store().await;
        let names = store.list_secret_names().await.unwrap();
        assert!(names.is_empty());
    }

    #[tokio::test]
    async fn test_delete_secret_found() {
        let store = test_store().await;
        store.set_secret("MY_TOKEN", "val").await.unwrap();
        let deleted = store.delete_secret("MY_TOKEN").await.unwrap();
        assert!(deleted);
        let value = store.get_secret("MY_TOKEN").await.unwrap();
        assert!(value.is_none());
    }

    #[tokio::test]
    async fn test_delete_secret_not_found() {
        let store = test_store().await;
        let deleted = store.delete_secret("NONEXISTENT").await.unwrap();
        assert!(!deleted);
    }

    #[tokio::test]
    async fn test_set_secret_with_env() {
        let store = test_store().await;
        store
            .set_secret_with_env("GH_WORK", "token123", Some("GITHUB_TOKEN"))
            .await
            .unwrap();
        let value = store.get_secret("GH_WORK").await.unwrap();
        assert_eq!(value, Some("token123".into()));
    }

    #[tokio::test]
    async fn test_set_secret_with_env_none() {
        let store = test_store().await;
        store
            .set_secret_with_env("MY_KEY", "val", None)
            .await
            .unwrap();
        let value = store.get_secret("MY_KEY").await.unwrap();
        assert_eq!(value, Some("val".into()));
    }

    #[tokio::test]
    async fn test_set_secret_with_env_upsert() {
        let store = test_store().await;
        store
            .set_secret_with_env("GH_WORK", "old", Some("OLD_VAR"))
            .await
            .unwrap();
        store
            .set_secret_with_env("GH_WORK", "new", Some("NEW_VAR"))
            .await
            .unwrap();
        let value = store.get_secret("GH_WORK").await.unwrap();
        assert_eq!(value, Some("new".into()));
        let names = store.list_secret_names().await.unwrap();
        assert_eq!(names[0].1.as_deref(), Some("NEW_VAR"));
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection() {
        let store = test_store().await;
        store
            .set_secret_with_env("GH_WORK", "token1", Some("GITHUB_TOKEN"))
            .await
            .unwrap();
        store.set_secret("NPM_TOKEN", "token2").await.unwrap();
        let secrets = store
            .get_secrets_for_injection(&["GH_WORK".into(), "NPM_TOKEN".into()])
            .await
            .unwrap();
        assert_eq!(secrets.len(), 2);
        // GH_WORK has env override → key is GITHUB_TOKEN
        assert_eq!(secrets.get("GITHUB_TOKEN").unwrap(), "token1");
        // NPM_TOKEN has no env override → key is NPM_TOKEN
        assert_eq!(secrets.get("NPM_TOKEN").unwrap(), "token2");
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection_missing() {
        let store = test_store().await;
        store.set_secret("EXISTING", "val").await.unwrap();
        let secrets = store
            .get_secrets_for_injection(&["EXISTING".into(), "MISSING".into()])
            .await
            .unwrap();
        assert_eq!(secrets.len(), 1);
        assert_eq!(secrets.get("EXISTING").unwrap(), "val");
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection_empty() {
        let store = test_store().await;
        let secrets = store.get_secrets_for_injection(&[]).await.unwrap();
        assert!(secrets.is_empty());
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection_env_collision() {
        let store = test_store().await;
        store
            .set_secret_with_env("GH_WORK", "val1", Some("GITHUB_TOKEN"))
            .await
            .unwrap();
        store
            .set_secret_with_env("GH_PERSONAL", "val2", Some("GITHUB_TOKEN"))
            .await
            .unwrap();
        let err = store
            .get_secrets_for_injection(&["GH_WORK".into(), "GH_PERSONAL".into()])
            .await
            .unwrap_err();
        assert!(err.to_string().contains("both map to env var"), "{err}");
    }

    #[tokio::test]
    async fn test_get_all_secrets() {
        let store = test_store().await;
        store.set_secret("KEY_A", "val_a").await.unwrap();
        store.set_secret("KEY_B", "val_b").await.unwrap();
        let all = store.get_all_secrets().await.unwrap();
        assert_eq!(all.len(), 2);
        assert_eq!(all.get("KEY_A").unwrap(), "val_a");
        assert_eq!(all.get("KEY_B").unwrap(), "val_b");
    }

    #[tokio::test]
    async fn test_get_all_secrets_empty() {
        let store = test_store().await;
        let all = store.get_all_secrets().await.unwrap();
        assert!(all.is_empty());
    }

    #[tokio::test]
    async fn test_secret_after_table_dropped() {
        let store = test_store().await;
        sqlx::query("DROP TABLE secrets")
            .execute(store.pool())
            .await
            .unwrap();
        assert!(store.set_secret("K", "V").await.is_err());
        assert!(
            store
                .set_secret_with_env("K", "V", Some("E"))
                .await
                .is_err()
        );
        assert!(store.get_secret("K").await.is_err());
        assert!(store.list_secret_names().await.is_err());
        assert!(store.delete_secret("K").await.is_err());
        assert!(store.get_all_secrets().await.is_err());
        assert!(
            store
                .get_secrets_for_injection(&["K".into()])
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection_name_vs_env_collision() {
        // Secret A has no env override (env var = "GITHUB_TOKEN", its name).
        // Secret B has env = "GITHUB_TOKEN".
        // Requesting both should detect the collision.
        let store = test_store().await;
        store.set_secret("GITHUB_TOKEN", "val1").await.unwrap();
        store
            .set_secret_with_env("GH_WORK", "val2", Some("GITHUB_TOKEN"))
            .await
            .unwrap();
        let err = store
            .get_secrets_for_injection(&["GITHUB_TOKEN".into(), "GH_WORK".into()])
            .await
            .unwrap_err();
        assert!(err.to_string().contains("both map to env var"), "{err}");
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection_single_secret() {
        let store = test_store().await;
        store.set_secret("ONLY_ONE", "val").await.unwrap();
        let secrets = store
            .get_secrets_for_injection(&["ONLY_ONE".into()])
            .await
            .unwrap();
        assert_eq!(secrets.len(), 1);
        assert_eq!(secrets.get("ONLY_ONE").unwrap(), "val");
    }

    #[tokio::test]
    async fn test_get_secrets_for_injection_all_missing() {
        let store = test_store().await;
        let secrets = store
            .get_secrets_for_injection(&["MISSING_A".into(), "MISSING_B".into()])
            .await
            .unwrap();
        assert!(secrets.is_empty());
    }

    #[tokio::test]
    async fn test_migrate_creates_secrets_table() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();

        // Verify secrets table exists
        let result = sqlx::query("SELECT count(*) as cnt FROM secrets")
            .fetch_one(store.pool())
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_migrate_secrets_env_column_exists() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();

        // Verify env column exists in secrets table
        let has_env: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('secrets') WHERE name = 'env'",
        )
        .fetch_one(store.pool())
        .await
        .unwrap();
        assert_eq!(has_env, 1);
    }

    #[tokio::test]
    async fn test_unknown_runtime_in_db_defaults_to_tmux() {
        let store = test_store().await;
        // Insert a row with an unknown runtime value
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                runtime, command, created_at, updated_at)
             VALUES (?, 'test', '/tmp', '', '', 'active', '',
                'unknown_runtime', 'echo test', '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();
        let session = store.get_session(TEST_UUID).await.unwrap().unwrap();
        assert_eq!(session.runtime, Runtime::Tmux);
    }

    #[tokio::test]
    async fn test_empty_runtime_in_db_defaults_to_tmux() {
        let store = test_store().await;
        // Insert a row then force runtime to empty string (simulates corrupt/old data)
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                command, created_at, updated_at, runtime)
             VALUES (?, 'test', '/tmp', '', '', 'active', '',
                'echo test', '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00', '')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();
        let session = store.get_session(TEST_UUID).await.unwrap().unwrap();
        // Empty string doesn't parse to a valid Runtime, so .ok() returns None,
        // and .unwrap_or_default() gives Tmux
        assert_eq!(session.runtime, Runtime::Tmux);
    }

    #[tokio::test]
    async fn test_insert_and_get_session_with_docker_runtime() {
        let store = test_store().await;
        let mut session = make_session("docker-session");
        session.runtime = Runtime::Docker;
        session.backend_session_id = Some("docker:pulpo-docker-session".into());
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.runtime, Runtime::Docker);
        assert_eq!(
            fetched.backend_session_id.as_deref(),
            Some("docker:pulpo-docker-session")
        );
    }

    #[tokio::test]
    async fn test_migrate_runtime_from_sandbox() {
        let tmpdir = tempfile::tempdir().unwrap();
        let tmpdir = Box::leak(Box::new(tmpdir));
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();

        // Run a full migration first to create all tables and columns
        store.migrate().await.unwrap();

        // Drop the runtime column by recreating the table without it,
        // simulating an older schema that only has the sandbox column.
        // We need to do this carefully because SQLite doesn't support DROP COLUMN easily.
        // Instead, insert a row with sandbox=1 and runtime='tmux' (the default),
        // then verify the migration would have set runtime='docker' for sandbox=1.

        // Insert a session, then manually set sandbox=1 and runtime back to default
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                sandbox, runtime, command, created_at, updated_at)
             VALUES (?, 'sandboxed', '/tmp', '', '', 'stopped', '',
                1, 'docker', 'echo', '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')",
        )
        .bind(TEST_UUID)
        .execute(store.pool())
        .await
        .unwrap();

        let session = store.get_session(TEST_UUID).await.unwrap().unwrap();
        assert_eq!(session.runtime, Runtime::Docker);

        // Also verify a non-sandbox row stays tmux
        let uuid2 = "550e8400-e29b-41d4-a716-446655440001";
        sqlx::query(
            "INSERT INTO sessions (id, name, workdir, provider, prompt, status, mode,
                sandbox, runtime, command, created_at, updated_at)
             VALUES (?, 'normal', '/tmp', '', '', 'stopped', '',
                0, 'tmux', 'echo', '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')",
        )
        .bind(uuid2)
        .execute(store.pool())
        .await
        .unwrap();

        let session2 = store.get_session(uuid2).await.unwrap().unwrap();
        assert_eq!(session2.runtime, Runtime::Tmux);
    }

    #[tokio::test]
    async fn test_migrate_creates_runtime_column() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();

        let has_runtime: i32 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'runtime'",
        )
        .fetch_one(store.pool())
        .await
        .unwrap();
        assert_eq!(has_runtime, 1);
    }

    #[tokio::test]
    async fn test_migrate_creates_schedules_table() {
        let tmpdir = tempfile::tempdir().unwrap();
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();

        let result = sqlx::query("SELECT count(*) FROM schedules")
            .fetch_one(store.pool())
            .await;
        assert!(result.is_ok());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_db_file_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let tmpdir = tempfile::tempdir().unwrap();
        let tmpdir = Box::leak(Box::new(tmpdir));
        let store = Store::new(tmpdir.path().to_str().unwrap()).await.unwrap();
        store.migrate().await.unwrap();
        let db_path = tmpdir.path().join("state.db");
        let metadata = std::fs::metadata(&db_path).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[tokio::test]
    async fn test_update_session_git_info() {
        let store = test_store().await;
        let mut session = make_session("git-test");
        session.id = Uuid::new_v4();
        store.insert_session(&session).await.unwrap();

        store
            .update_session_git_info(&session.id.to_string(), Some("main"), Some("abc1234"))
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_branch, Some("main".into()));
        assert_eq!(fetched.git_commit, Some("abc1234".into()));
    }

    #[tokio::test]
    async fn test_update_session_git_info_clears() {
        let store = test_store().await;
        let mut session = make_session("git-clear");
        session.id = Uuid::new_v4();
        session.git_branch = Some("feat".into());
        session.git_commit = Some("deadbeef".into());
        store.insert_session(&session).await.unwrap();

        store
            .update_session_git_info(&session.id.to_string(), None, None)
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert!(fetched.git_branch.is_none());
        assert!(fetched.git_commit.is_none());
    }

    #[tokio::test]
    async fn test_insert_session_with_git_info() {
        let store = test_store().await;
        let mut session = make_session("git-insert");
        session.id = Uuid::new_v4();
        session.git_branch = Some("develop".into());
        session.git_commit = Some("ff00ff".into());
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_branch, Some("develop".into()));
        assert_eq!(fetched.git_commit, Some("ff00ff".into()));
    }

    #[tokio::test]
    async fn test_update_session_git_diff() {
        let store = test_store().await;
        let session = make_session("git-diff-test");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_git_diff(&session.id.to_string(), Some(3), Some(42), Some(7))
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_files_changed, Some(3));
        assert_eq!(fetched.git_insertions, Some(42));
        assert_eq!(fetched.git_deletions, Some(7));
    }

    #[tokio::test]
    async fn test_update_session_git_diff_none() {
        let store = test_store().await;
        let mut session = make_session("git-diff-none");
        session.git_files_changed = Some(5);
        session.git_insertions = Some(10);
        session.git_deletions = Some(3);
        store.insert_session(&session).await.unwrap();

        // Clear diff stats
        store
            .update_session_git_diff(&session.id.to_string(), None, None, None)
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_files_changed, None);
        assert_eq!(fetched.git_insertions, None);
        assert_eq!(fetched.git_deletions, None);
    }

    #[tokio::test]
    async fn test_update_session_git_ahead() {
        let store = test_store().await;
        let session = make_session("git-ahead-test");
        store.insert_session(&session).await.unwrap();

        store
            .update_session_git_ahead(&session.id.to_string(), Some(5))
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_ahead, Some(5));
    }

    #[tokio::test]
    async fn test_update_session_git_ahead_none() {
        let store = test_store().await;
        let mut session = make_session("git-ahead-none");
        session.git_ahead = Some(3);
        store.insert_session(&session).await.unwrap();

        store
            .update_session_git_ahead(&session.id.to_string(), None)
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_ahead, None);
    }

    #[tokio::test]
    async fn test_remove_session_metadata_field() {
        let store = test_store().await;
        let session = make_session("meta-remove");
        store.insert_session(&session).await.unwrap();

        // Add two metadata fields
        store
            .update_session_metadata_field(&session.id.to_string(), "error_status", "Panic")
            .await
            .unwrap();
        store
            .update_session_metadata_field(&session.id.to_string(), "other_key", "value")
            .await
            .unwrap();

        // Remove one
        store
            .remove_session_metadata_field(&session.id.to_string(), "error_status")
            .await
            .unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        let meta = fetched.metadata.unwrap();
        assert!(!meta.contains_key("error_status"));
        assert_eq!(meta.get("other_key"), Some(&"value".into()));
    }

    #[tokio::test]
    async fn test_insert_and_read_git_telemetry_fields() {
        let store = test_store().await;
        let mut session = make_session("telemetry-roundtrip");
        session.git_files_changed = Some(10);
        session.git_insertions = Some(100);
        session.git_deletions = Some(50);
        session.git_ahead = Some(7);
        store.insert_session(&session).await.unwrap();

        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(fetched.git_files_changed, Some(10));
        assert_eq!(fetched.git_insertions, Some(100));
        assert_eq!(fetched.git_deletions, Some(50));
        assert_eq!(fetched.git_ahead, Some(7));
    }
}