voro-core 0.2.0

Core logic for Voro: the SQLite store, task state machine, scheduler, and scoring.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use rusqlite::{Connection, OptionalExtension, params};

use crate::error::{Error, Result};
use crate::model::{
    Dep, DepKind, DepRef, Doc, Event, LivenessSource, Priority, Project, RefineOutcome, Repo,
    RunningRow, Session, SessionOutcome, Task, TaskState, location_is_url,
};

const MIGRATIONS: &[&str] = &[
    include_str!("../migrations/0001_init.sql"),
    include_str!("../migrations/0002_rename_backlog_to_parked.sql"),
    include_str!("../migrations/0003_track_pr.sql"),
    include_str!("../migrations/0004_add_session_ref.sql"),
    include_str!("../migrations/0005_add_branch.sql"),
    include_str!("../migrations/0006_one_open_session_per_task.sql"),
    include_str!("../migrations/0007_add_human.sql"),
    include_str!("../migrations/0008_add_stalled_state.sql"),
    include_str!("../migrations/0009_add_review_action.sql"),
    include_str!("../migrations/0010_add_waiting_state.sql"),
    include_str!("../migrations/0011_add_archived.sql"),
    include_str!("../migrations/0012_repos.sql"),
    include_str!("../migrations/0013_add_deep.sql"),
    include_str!("../migrations/0014_docs.sql"),
    include_str!("../migrations/0015_dep_kind_in_key.sql"),
    include_str!("../migrations/0016_add_refining_state.sql"),
    include_str!("../migrations/0017_schema_migrations.sql"),
    include_str!("../migrations/0018_project_viewer.sql"),
    include_str!("../migrations/0019_session_liveness_source.sql"),
    include_str!("../migrations/0020_store_meta.sql"),
];

/// Whether a path lies inside a Cargo build directory — a `target` component
/// followed immediately by a profile. Covers `target/debug/voro`,
/// `target/release/voro`, and the `target/debug/deps/` binaries the test
/// harness runs, in a worktree or the primary checkout alike.
fn path_is_cargo_target(path: &Path) -> bool {
    let parts: Vec<_> = path
        .components()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .collect();
    parts
        .windows(2)
        .any(|pair| pair[0] == "target" && (pair[1] == "debug" || pair[1] == "release"))
}

/// Write the journal rows for a migration pass (§5). Migrations applied before
/// the journal existed are backfilled with a NULL `sql`; what this pass applies
/// is recorded verbatim, signed with the build that applied it and, on a
/// protected store, with the consent that let it (§5).
fn record_in_journal(tx: &Connection, from_version: usize, consent: Option<&str>) -> Result<()> {
    let found: i64 = tx.query_row(
        "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
        [],
        |row| row.get(0),
    )?;
    if found == 0 {
        return Ok(());
    }
    for idx in 1..=from_version {
        tx.execute(
            "INSERT OR IGNORE INTO schema_migrations (idx, sql, applied_at, applied_by)
             VALUES (?1, NULL, datetime('now'), NULL)",
            params![idx as i64],
        )?;
    }
    let by = applied_by(consent);
    for idx in (from_version + 1)..=MIGRATIONS.len() {
        tx.execute(
            "INSERT OR REPLACE INTO schema_migrations (idx, sql, applied_at, applied_by)
             VALUES (?1, ?2, datetime('now'), ?3)",
            params![idx as i64, MIGRATIONS[idx - 1], by],
        )?;
    }
    Ok(())
}

/// How a build signs the journal: crate version and the running executable's
/// path, which is what identifies the build behind a divergence. A consented
/// migration of a protected store appends how the consent was given, so even
/// a `--yes` override leaves a trace.
fn applied_by(consent: Option<&str>) -> String {
    let exe = std::env::current_exe()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| "an unknown executable".to_string());
    let via = consent.map(|c| format!(", {c}")).unwrap_or_default();
    format!("voro {} at {exe}{via}", env!("CARGO_PKG_VERSION"))
}

/// The way out of a database carrying a migration this build does not have:
/// the dev store is rebuilt, the operator's is restored from a snapshot.
fn remedy_for_divergence(path: Option<&Path>) -> String {
    if path.is_some_and(|p| p == Store::dev_db_path()) {
        format!(
            "It is the dev store, which is disposable — rebuild it at this build's schema with \
             `voro seed --force`, or delete {} and it will be reseeded on the next run.",
            Store::dev_db_path().display()
        )
    } else {
        format!(
            "Restore the snapshot taken before that migration from {}; failing that, run the \
             build named above, which is the only one whose schema matches this database.",
            Store::backup_dir_for(path.unwrap_or(&Store::production_db_path())).display()
        )
    }
}

/// The way out of a database whose schema is ahead of this build: the dev
/// store is rebuilt, the operator's is restored from a snapshot.
fn remedy_for_schema_ahead(path: Option<&Path>) -> String {
    if path.is_some_and(|p| p == Store::dev_db_path()) {
        format!(
            "It is the dev store, which is disposable — rebuild it at this build's schema with \
             `voro seed --force`, or delete {} and it will be reseeded on the next run.",
            Store::dev_db_path().display()
        )
    } else {
        format!(
            "Restore a pre-migration snapshot from {}; failing that, run the build that migrated \
             it — though if that build was never released, doing so entrenches a schema no other \
             build can open.",
            Store::backup_dir_for(path.unwrap_or(&Store::production_db_path())).display()
        )
    }
}

/// Owns the SQLite database. All writes go through this type; task state in
/// particular is only ever changed by the transition API in `transition.rs`.
pub struct Store {
    pub(crate) conn: Connection,
}

/// Drop every row, leaving the schema in place — the reset behind
/// `voro seed --force`. The CLI is what confines this to the dev store.
impl Store {
    pub fn truncate_all(&mut self) -> Result<()> {
        let tx = self.conn.transaction()?;
        tx.pragma_update(None, "foreign_keys", false)?;
        for table in [
            "task_docs",
            "docs",
            "deps",
            "events",
            "sessions",
            "tasks",
            "repos",
            "projects",
        ] {
            tx.execute(&format!("DELETE FROM {table}"), [])?;
        }
        tx.execute("DELETE FROM sqlite_sequence", []).ok();
        tx.commit()?;
        self.conn.pragma_update(None, "foreign_keys", true)?;
        Ok(())
    }
}

/// Initial state for a task created by a human. `proposed` is quick capture;
/// `parked`/`ready` mean the creator has already triaged their own task.
#[derive(Debug, Clone)]
pub struct NewTask {
    pub project_id: i64,
    /// The repo the task runs in; `None` resolves to the project's default.
    pub repo_id: Option<i64>,
    pub title: String,
    pub body: String,
    pub priority: Priority,
    pub state: TaskState,
    pub agent: Option<String>,
    pub human: bool,
    pub deep: bool,
}

/// Content edits. State is deliberately absent — use `Store::apply`.
#[derive(Debug, Clone)]
pub struct TaskEdit {
    pub title: String,
    pub body: String,
    pub priority: Priority,
    pub agent: Option<String>,
    pub human: bool,
    pub deep: bool,
}

impl Store {
    pub fn open(path: &Path) -> Result<Store> {
        Store::open_with_consent(path, None)
    }

    /// Open with consent to migrate a protected store (§5): the TUI's launch
    /// prompt and `voro migrate` call this after a human has answered, or with
    /// `--yes` standing in for one. `consent` says how the consent was given
    /// and is recorded in the journal's `applied_by`. On an unprotected store
    /// it changes nothing — migration there never needed asking.
    pub fn open_migrate(path: &Path, consent: &str) -> Result<Store> {
        Store::open_with_consent(path, Some(consent))
    }

    fn open_with_consent(path: &Path, consent: Option<&str>) -> Result<Store> {
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)
                .map_err(|e| Error::Invalid(format!("cannot create {}: {e}", dir.display())))?;
        }
        Store::open_at(
            Connection::open(path)?,
            path,
            &Store::production_db_path(),
            consent,
        )
    }

    pub fn open_in_memory() -> Result<Store> {
        Store::from_connection_at(Connection::open_in_memory()?, None)
    }

    /// `$XDG_DATA_HOME/voro`, defaulting to `~/.local/share/voro`.
    pub fn data_dir() -> PathBuf {
        let data_home = std::env::var_os("XDG_DATA_HOME")
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            .unwrap_or_else(|| {
                let home = std::env::var_os("HOME")
                    .map(PathBuf::from)
                    .unwrap_or_default();
                home.join(".local/share")
            });
        data_home.join("voro")
    }

    /// The operator's store (DESIGN.md §5), at a path that does not vary with
    /// how the running binary was built. Dispatch renders `--db` against it,
    /// and `voro seed` refuses it.
    pub fn production_db_path() -> PathBuf {
        Store::data_dir().join("voro.db")
    }

    /// The store a build out of a `target/` directory opens instead (DESIGN.md
    /// §5). Seeded on first open and disposable: `voro seed --force` rebuilds
    /// it, and deleting it costs nothing.
    pub fn dev_db_path() -> PathBuf {
        Store::data_dir().join("dev.db")
    }

    /// Where snapshots taken before a migration land: beside the database they
    /// protect, so a store opened with `--db` keeps its own history.
    pub fn backup_dir_for(path: &Path) -> PathBuf {
        path.parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or(Path::new("."))
            .join("backups")
    }

    /// True when this binary was run out of a Cargo `target/` directory rather
    /// than installed. It picks the default store and bounds nothing:
    /// `cargo install --path` builds a working checkout, unreleased migrations
    /// and all, into an ordinary install location, where this reads as an
    /// install. The journal and the counter (§5) are what protect the schema.
    pub fn is_dev_build() -> bool {
        std::env::current_exe().is_ok_and(|exe| path_is_cargo_target(&exe))
    }

    /// The store a bare `voro` opens: the dev one for a dev build, the
    /// operator's otherwise.
    pub fn default_db_path() -> PathBuf {
        if Store::is_dev_build() {
            Store::dev_db_path()
        } else {
            Store::production_db_path()
        }
    }

    #[cfg(test)]
    fn from_connection(conn: Connection) -> Result<Store> {
        Store::from_connection_at(conn, None)
    }

    fn from_connection_at(conn: Connection, path: Option<&Path>) -> Result<Store> {
        Store::open_at_opt(conn, path, &Store::production_db_path(), None)
    }

    fn open_at(
        conn: Connection,
        path: &Path,
        production: &Path,
        consent: Option<&str>,
    ) -> Result<Store> {
        Store::open_at_opt(conn, Some(path), production, consent)
    }

    fn open_at_opt(
        conn: Connection,
        path: Option<&Path>,
        production: &Path,
        consent: Option<&str>,
    ) -> Result<Store> {
        conn.pragma_update(None, "foreign_keys", true)?;
        let mut store = Store { conn };
        let version = store.schema_version()?;
        // Ahead of the version check, which cannot see a divergence.
        store.verify_journal(path)?;
        if version > MIGRATIONS.len() {
            return Err(Error::SchemaAhead {
                version,
                known: MIGRATIONS.len(),
                remedy: remedy_for_schema_ahead(path),
            });
        }
        if version < MIGRATIONS.len()
            && let Some(path) = path
        {
            // The consent gate (§5). A store with no schema at all is exempt —
            // a fresh install creates its database silently, and there is
            // nothing yet to protect.
            if version > 0 && consent.is_none() && store.is_protected(path, production)? {
                return Err(Error::MigrationsPending {
                    path: path.to_path_buf(),
                    pending: MIGRATIONS.len() - version,
                    version,
                    known: MIGRATIONS.len(),
                });
            }
            store.snapshot(path, version)?;
        }
        store.migrate(consent)?;
        if path == Some(production) {
            store.mark_protected()?;
        }
        Ok(store)
    }

    /// Whether this store is the operator's (§5): opened at the production
    /// path, or carrying the `protected` marker a past open there wrote — how
    /// the property survives a symlink, a moved data directory, or a restored
    /// copy. Runs before any migration, so it must read a store from before
    /// `store_meta` existed, where only the path can answer.
    fn is_protected(&self, path: &Path, production: &Path) -> Result<bool> {
        if path == production {
            return Ok(true);
        }
        let has_meta: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'store_meta'",
            [],
            |row| row.get(0),
        )?;
        if has_meta == 0 {
            return Ok(false);
        }
        let marked: Option<String> = self
            .conn
            .query_row(
                "SELECT value FROM store_meta WHERE key = 'protected'",
                [],
                |row| row.get(0),
            )
            .optional()?;
        Ok(marked.as_deref() == Some("1"))
    }

    /// `INSERT OR IGNORE` so an already-marked store takes no write at all:
    /// opening must not bump `data_version` for connections polling it.
    fn mark_protected(&self) -> Result<()> {
        self.conn.execute(
            "INSERT OR IGNORE INTO store_meta (key, value) VALUES ('protected', '1')",
            [],
        )?;
        Ok(())
    }

    /// Check the journal (§5) against the migrations this build carries. The
    /// counter reports a database that is *ahead*; this reports one that is
    /// *different*, which two branches numbering a migration alike produce.
    /// History predating the journal has a NULL `sql` and is skipped as
    /// unverifiable.
    fn verify_journal(&self, path: Option<&Path>) -> Result<()> {
        if !self.has_journal()? {
            return Ok(());
        }
        let mut stmt = self.conn.prepare(
            "SELECT idx, sql, applied_at, applied_by FROM schema_migrations
             WHERE sql IS NOT NULL ORDER BY idx",
        )?;
        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, i64>(0)? as usize,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, Option<String>>(3)?,
            ))
        })?;
        for row in rows {
            let (idx, applied, applied_at, applied_by) = row?;
            // Indices beyond this build's list are the counter's to report.
            let Some(carried) = MIGRATIONS.get(idx - 1) else {
                continue;
            };
            if applied != *carried {
                return Err(Error::SchemaDiverged {
                    idx,
                    applied_at,
                    applied_by: applied_by.unwrap_or_else(|| "an unrecorded build".to_string()),
                    remedy: remedy_for_divergence(path),
                });
            }
        }
        Ok(())
    }

    fn has_journal(&self) -> Result<bool> {
        let found: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
            [],
            |row| row.get(0),
        )?;
        Ok(found > 0)
    }

    /// The store's `user_version`. An open store always reads as the count of
    /// migrations its build carries; `voro migrate` reports it when there was
    /// nothing to apply.
    pub fn schema_version(&self) -> Result<usize> {
        Ok(self
            .conn
            .query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0))? as usize)
    }

    /// Copy the database beside itself before a migration touches it, since a
    /// migration that renames or drops a column is not reversible from the
    /// migrated file alone. A database with no schema yet is skipped, and a
    /// failure to write the copy is reported rather than fatal.
    fn snapshot(&self, path: &Path, version: usize) -> Result<()> {
        if version == 0 || !path.exists() {
            return Ok(());
        }
        let stamp: String =
            self.conn
                .query_row("SELECT strftime('%Y%m%d-%H%M%S', 'now')", [], |row| {
                    row.get(0)
                })?;
        let stem = path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "voro".to_string());
        let dir = Store::backup_dir_for(path);
        let target = dir.join(format!("{stem}-v{version}-{stamp}.db"));
        let copied = std::fs::create_dir_all(&dir).and_then(|()| std::fs::copy(path, &target));
        if let Err(e) = copied {
            eprintln!(
                "voro: could not snapshot {} before migrating to schema {}: {e}",
                path.display(),
                MIGRATIONS.len()
            );
        }
        Ok(())
    }

    /// SQLite's `PRAGMA data_version`, which increments whenever another
    /// connection commits a change to the database. The value is stable across
    /// commits made on this connection, so a caller can poll it to detect
    /// external writes without reacting to its own mutations.
    pub fn data_version(&self) -> Result<i64> {
        Ok(self
            .conn
            .query_row("PRAGMA data_version", [], |r| r.get(0))?)
    }

    /// Migrations may rebuild tables (SQLite cannot alter CHECK constraints),
    /// so foreign-key enforcement is suspended for the duration and integrity
    /// verified afterwards — the procedure SQLite documents for schema changes.
    fn migrate(&mut self, consent: Option<&str>) -> Result<()> {
        self.conn.pragma_update(None, "foreign_keys", false)?;
        let applied = self.apply_migrations(consent);
        let restored = self.conn.pragma_update(None, "foreign_keys", true);
        applied?;
        restored?;
        let violations: i64 =
            self.conn
                .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |r| {
                    r.get(0)
                })?;
        if violations > 0 {
            return Err(Error::Invalid(format!(
                "{violations} foreign key violation(s) after migration"
            )));
        }
        Ok(())
    }

    fn apply_migrations(&mut self, consent: Option<&str>) -> Result<()> {
        let tx = self.conn.transaction()?;
        let version: usize =
            tx.query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0))? as usize;
        for (i, sql) in MIGRATIONS.iter().enumerate().skip(version) {
            tx.execute_batch(sql)?;
            tx.pragma_update(None, "user_version", (i + 1) as i64)?;
        }
        record_in_journal(&tx, version, consent)?;
        tx.commit()?;
        Ok(())
    }

    // --- projects ---

    /// Create a project and its default repo in one transaction, so a project
    /// with no checkout is never observable (DESIGN.md §5). The repo is named
    /// after the project; `voro repo` renames nothing, but `repo add` puts
    /// further checkouts beside it.
    pub fn create_project(&mut self, name: &str, path: &str) -> Result<Project> {
        let tx = self.conn.transaction()?;
        tx.execute("INSERT INTO projects (name) VALUES (?1)", params![name])?;
        let id = tx.last_insert_rowid();
        tx.execute(
            "INSERT INTO repos (project_id, name, path, is_default) VALUES (?1, ?2, ?3, 1)",
            params![id, name, path],
        )?;
        tx.commit()?;
        self.project(id)
    }

    pub fn project(&self, id: i64) -> Result<Project> {
        self.conn
            .query_row(
                &format!("SELECT {PROJECT_COLUMNS} FROM projects WHERE id = ?1"),
                [id],
                project_from_row,
            )
            .optional()?
            .ok_or(Error::ProjectNotFound(id))
    }

    pub fn projects(&self) -> Result<Vec<Project>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {PROJECT_COLUMNS} FROM projects ORDER BY name"
        ))?;
        let rows = stmt.query_map([], project_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    pub fn set_weight(&mut self, project_id: i64, weight: i64) -> Result<()> {
        if !(0..=5).contains(&weight) {
            return Err(Error::Invalid(format!("weight {weight} out of range 0-5")));
        }
        let changed = self.conn.execute(
            "UPDATE projects SET weight = ?1 WHERE id = ?2",
            params![weight, project_id],
        )?;
        if changed == 0 {
            return Err(Error::ProjectNotFound(project_id));
        }
        Ok(())
    }

    /// Name the `voro.toml` viewer this project's local diffs open in
    /// (DESIGN.md §8/§11a). `None` stores NULL — no viewer named, so `open`
    /// falls back to the config's default viewer.
    pub fn set_viewer(&mut self, project_id: i64, viewer: Option<&str>) -> Result<Project> {
        let viewer = match viewer.map(str::trim) {
            Some("") => {
                return Err(Error::Invalid(
                    "viewer name is required — name no viewer to use the default one".into(),
                ));
            }
            named => named,
        };
        let changed = self.conn.execute(
            "UPDATE projects SET viewer = ?1 WHERE id = ?2",
            params![viewer, project_id],
        )?;
        if changed == 0 {
            return Err(Error::ProjectNotFound(project_id));
        }
        self.project(project_id)
    }

    /// Archive or unarchive a project (DESIGN.md §5). Archiving hides the
    /// project and all of its tasks from the cockpit views; the tasks
    /// themselves are not touched — no state change, no event — so unarchiving
    /// restores the pre-archive view exactly. Refuses a no-op so a typo'd
    /// second archive is heard rather than silently absorbed.
    pub fn set_archived(&mut self, project_id: i64, archived: bool) -> Result<Project> {
        let project = self.project(project_id)?;
        if project.archived == archived {
            return Err(Error::Invalid(format!(
                "project '{}' is {} archived",
                project.name,
                if archived { "already" } else { "not" }
            )));
        }
        self.conn.execute(
            "UPDATE projects SET archived = ?1 WHERE id = ?2",
            params![archived, project_id],
        )?;
        self.project(project_id)
    }

    /// Tasks reference a project by id, not name, so renaming is a pure
    /// label change — no task or dependency is touched.
    pub fn rename_project(&mut self, project_id: i64, name: &str) -> Result<Project> {
        let changed = self.conn.execute(
            "UPDATE projects SET name = ?1 WHERE id = ?2",
            params![name, project_id],
        )?;
        if changed == 0 {
            return Err(Error::ProjectNotFound(project_id));
        }
        self.project(project_id)
    }

    /// Re-point a project's *default* repo. This is what `voro project path`
    /// and the projects screen's path field edit — the single-repo spelling of
    /// `repo path`, kept because a one-repo project is still the common case.
    pub fn set_default_repo_path(&mut self, project_id: i64, path: &str) -> Result<Repo> {
        let repo = self.default_repo(project_id)?;
        self.set_repo_path(repo.id, path)
    }

    /// Delete a project outright — only safe when it has no tasks, since tasks
    /// reference their project by id and deleting would orphan history. A project
    /// with tasks in any state refuses; weight 0 snoozes without losing history.
    /// Its repos go with it: no task references them, so nothing is orphaned.
    pub fn delete_project(&mut self, project_id: i64) -> Result<()> {
        self.project(project_id)?;
        let task_count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM tasks WHERE project_id = ?1",
            [project_id],
            |r| r.get(0),
        )?;
        if task_count > 0 {
            return Err(Error::ProjectHasTasks {
                id: project_id,
                count: task_count,
            });
        }
        let tx = self.conn.transaction()?;
        tx.execute("DELETE FROM repos WHERE project_id = ?1", [project_id])?;
        tx.execute("DELETE FROM projects WHERE id = ?1", [project_id])?;
        tx.commit()?;
        Ok(())
    }

    // --- repos ---
    //
    // A project owns at least one repo, exactly one of which is its default
    // (DESIGN.md §3/§5). The at-most-one-default half is schema-enforced by a
    // partial unique index; the rest — never zero repos, no deleting the
    // default or a referenced one — lives here, the same place the state
    // machine's invariants live, so no interface can bypass them.

    /// A project's repos, default first, then by name.
    pub fn repos(&self, project_id: i64) -> Result<Vec<Repo>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {REPO_COLUMNS} FROM repos WHERE project_id = ?1
             ORDER BY is_default DESC, name"
        ))?;
        let rows = stmt.query_map([project_id], repo_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    pub fn repo(&self, id: i64) -> Result<Repo> {
        self.conn
            .query_row(
                &format!("SELECT {REPO_COLUMNS} FROM repos WHERE id = ?1"),
                [id],
                repo_from_row,
            )
            .optional()?
            .ok_or(Error::RepoIdNotFound(id))
    }

    /// A project's repo by name. An unknown name errors listing the project's
    /// repos, so a filing agent gets a correction rather than a wrong checkout.
    pub fn repo_by_name(&self, project_id: i64, name: &str) -> Result<Repo> {
        let repos = self.repos(project_id)?;
        repos
            .into_iter()
            .find(|r| r.name == name)
            .ok_or_else(|| Error::RepoNotFound {
                project: self.project(project_id).map(|p| p.name).unwrap_or_default(),
                name: name.to_string(),
                known: self.repo_names(project_id),
            })
    }

    pub fn default_repo(&self, project_id: i64) -> Result<Repo> {
        self.conn
            .query_row(
                &format!(
                    "SELECT {REPO_COLUMNS} FROM repos WHERE project_id = ?1 AND is_default = 1"
                ),
                [project_id],
                repo_from_row,
            )
            .optional()?
            .ok_or_else(|| match self.project(project_id) {
                // A project always has a default repo — `create_project` makes
                // it in the same transaction — so the only way here is an id
                // that names no project at all.
                Err(e) => e,
                Ok(_) => Error::Invalid(format!("project {project_id} has no default repo")),
            })
    }

    /// The checkout a task's work runs in (DESIGN.md §8): its own repo when it
    /// names one, else its project's default. The single resolution point —
    /// dispatch, `pr`/`open`, worktree cleanup, and `import` all come here
    /// rather than reading `repo_id` themselves.
    pub fn repo_for_task(&self, task: &Task) -> Result<Repo> {
        match task.repo_id {
            Some(id) => self.repo(id),
            None => self.default_repo(task.project_id),
        }
    }

    /// Add a repo to a project. The first repo of a project is made by
    /// `create_project`, so one added here is never the default; `set_default`
    /// promotes it.
    pub fn add_repo(&mut self, project_id: i64, name: &str, path: &str) -> Result<Repo> {
        self.project(project_id)?;
        if name.trim().is_empty() {
            return Err(Error::Invalid("a repo name is required".into()));
        }
        if self.repos(project_id)?.iter().any(|r| r.name == name) {
            return Err(Error::Invalid(format!(
                "project already has a repo named '{name}'"
            )));
        }
        self.conn.execute(
            "INSERT INTO repos (project_id, name, path, is_default) VALUES (?1, ?2, ?3, 0)",
            params![project_id, name, path],
        )?;
        self.repo(self.conn.last_insert_rowid())
    }

    pub fn set_repo_path(&mut self, repo_id: i64, path: &str) -> Result<Repo> {
        let changed = self.conn.execute(
            "UPDATE repos SET path = ?1 WHERE id = ?2",
            params![path, repo_id],
        )?;
        if changed == 0 {
            return Err(Error::RepoIdNotFound(repo_id));
        }
        self.repo(repo_id)
    }

    /// Make a repo its project's default. Clearing the old default and setting
    /// the new one share a transaction, because the partial unique index would
    /// otherwise refuse the intermediate state.
    pub fn set_default_repo(&mut self, repo_id: i64) -> Result<Repo> {
        let repo = self.repo(repo_id)?;
        let tx = self.conn.transaction()?;
        tx.execute(
            "UPDATE repos SET is_default = 0 WHERE project_id = ?1",
            [repo.project_id],
        )?;
        tx.execute("UPDATE repos SET is_default = 1 WHERE id = ?1", [repo_id])?;
        tx.commit()?;
        self.repo(repo_id)
    }

    /// Remove a repo, refusing the three ways it would leave the store
    /// inconsistent: the project's last repo (a project always has a
    /// checkout), its default while others remain (set a new one first), and
    /// one any task still names (re-point those tasks first).
    pub fn delete_repo(&mut self, repo_id: i64) -> Result<()> {
        let repo = self.repo(repo_id)?;
        let project = self.project(repo.project_id)?;
        if self.repos(repo.project_id)?.len() == 1 {
            return Err(Error::LastRepo {
                project: project.name,
                name: repo.name,
            });
        }
        if repo.is_default {
            return Err(Error::DefaultRepo {
                project: project.name,
                name: repo.name,
            });
        }
        let used: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM tasks WHERE repo_id = ?1",
            [repo_id],
            |r| r.get(0),
        )?;
        if used > 0 {
            return Err(Error::RepoInUse {
                name: repo.name,
                count: used,
            });
        }
        self.conn
            .execute("DELETE FROM repos WHERE id = ?1", [repo_id])?;
        Ok(())
    }

    /// Re-point a task at a repo of its own project, or back at the default
    /// with `None`. A repo belonging to another project is refused — a task's
    /// checkout is chosen from its project's repos, not from every repo.
    pub fn set_task_repo(&mut self, task_id: i64, repo_id: Option<i64>) -> Result<Task> {
        let task = self.task(task_id)?;
        if let Some(id) = repo_id {
            let repo = self.repo(id)?;
            if repo.project_id != task.project_id {
                return Err(Error::Invalid(format!(
                    "repo '{}' belongs to another project",
                    repo.name
                )));
            }
        }
        self.conn.execute(
            "UPDATE tasks SET repo_id = ?1 WHERE id = ?2",
            params![repo_id, task_id],
        )?;
        self.task(task_id)
    }

    fn repo_names(&self, project_id: i64) -> String {
        self.repos(project_id)
            .map(|repos| {
                repos
                    .into_iter()
                    .map(|r| r.name)
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default()
    }

    // --- docs ---
    //
    // A document is a plan a project's work derives from (DESIGN.md §3/§5).
    // It is *owned* by one project, which is where a relative location resolves
    // and where `doc list` shows it, but the task edge is deliberately not
    // constrained to that project: one strategy doc routinely spawns work
    // across several, and refusing the cross-project link would defeat the
    // "which tasks came from this plan?" query the table exists for.

    /// Register a document against a project. `location` is a checkout-relative
    /// path, an absolute path, or a URL; an absolute path that lies inside one
    /// of the project's checkouts is stored relative to it (DESIGN.md §5), so
    /// the link survives the checkout moving. `repo` names which checkout a
    /// relative path resolves against, `None` meaning the project's default.
    pub fn create_doc(
        &mut self,
        project_id: i64,
        repo_id: Option<i64>,
        location: &str,
        title: Option<&str>,
    ) -> Result<Doc> {
        self.project(project_id)?;
        let (location, repo_id) = self.normalise_location(project_id, repo_id, location)?;
        if self
            .docs(project_id)?
            .iter()
            .any(|d| d.location == location)
        {
            return Err(Error::Invalid(format!(
                "this project already has a document at '{location}'"
            )));
        }
        self.conn.execute(
            "INSERT INTO docs (project_id, repo_id, title, location, created_at)
             VALUES (?1, ?2, ?3, ?4, datetime('now'))",
            params![project_id, repo_id, title, location],
        )?;
        let doc = self.doc(self.conn.last_insert_rowid())?;
        log_global_event(&self.conn, "doc-added", Some(&doc.location))?;
        Ok(doc)
    }

    /// Reduce an operator-supplied location to what is stored: a URL verbatim
    /// (and never against a repo, since it resolves unaided), an absolute path
    /// relativised against the checkout that contains it, and anything else
    /// left as given. An explicit `repo_id` pins which checkout is meant, and
    /// an absolute path outside it is refused rather than silently stored whole.
    fn normalise_location(
        &self,
        project_id: i64,
        repo_id: Option<i64>,
        location: &str,
    ) -> Result<(String, Option<i64>)> {
        let location = location.trim();
        if location.is_empty() {
            return Err(Error::Invalid("a document path or URL is required".into()));
        }
        if let Some(id) = repo_id {
            let repo = self.repo(id)?;
            if repo.project_id != project_id {
                return Err(Error::Invalid(format!(
                    "repo '{}' belongs to another project",
                    repo.name
                )));
            }
        }
        if location_is_url(location) {
            if repo_id.is_some() {
                return Err(Error::Invalid(
                    "a URL resolves on its own — drop --repo, which only picks the checkout a \
                     relative path is read from"
                        .into(),
                ));
            }
            return Ok((location.to_string(), None));
        }
        if !Path::new(location).is_absolute() {
            return Ok((location.to_string(), repo_id));
        }
        // An absolute path: prefer the checkout that contains it, so the stored
        // location survives that checkout moving. The longest matching path
        // wins, for the case of a repo nested inside another.
        let mut repos = match repo_id {
            Some(id) => vec![self.repo(id)?],
            None => self.repos(project_id)?,
        };
        repos.sort_by_key(|r| std::cmp::Reverse(r.path.len()));
        for repo in &repos {
            if let Ok(rel) = Path::new(location).strip_prefix(&repo.path) {
                return Ok((rel.to_string_lossy().into_owned(), Some(repo.id)));
            }
        }
        match repo_id {
            // An explicit --repo said which checkout to read this path from, so
            // a path outside it is a mistake worth hearing rather than storing.
            Some(id) => Err(Error::Invalid(format!(
                "'{location}' is not inside repo '{}' ({})",
                self.repo(id)?.name,
                self.repo(id)?.path
            ))),
            // Outside every checkout: a legitimate external document, kept
            // absolute and resolving against no repo.
            None => Ok((location.to_string(), None)),
        }
    }

    pub fn doc(&self, id: i64) -> Result<Doc> {
        self.conn
            .query_row(
                &format!("SELECT {DOC_COLUMNS} FROM docs WHERE id = ?1"),
                [id],
                doc_from_row,
            )
            .optional()?
            .ok_or(Error::DocNotFound(id))
    }

    /// A project's documents, oldest first — registration order is the closest
    /// thing a plan library has to a meaningful one.
    pub fn docs(&self, project_id: i64) -> Result<Vec<Doc>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {DOC_COLUMNS} FROM docs WHERE project_id = ?1 ORDER BY id"
        ))?;
        let rows = stmt.query_map([project_id], doc_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    pub fn all_docs(&self) -> Result<Vec<Doc>> {
        let mut stmt = self
            .conn
            .prepare(&format!("SELECT {DOC_COLUMNS} FROM docs ORDER BY id"))?;
        let rows = stmt.query_map([], doc_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    /// Every document with the given location, across projects — what a `--doc`
    /// flag naming a path rather than an id matches. More than one match is
    /// returned rather than resolved, so the caller can say which ids collided.
    pub fn docs_at(&self, location: &str) -> Result<Vec<Doc>> {
        let location = location.trim();
        Ok(self
            .all_docs()?
            .into_iter()
            .filter(|d| d.location == location)
            .collect())
    }

    /// Where a document actually is: a URL or absolute path verbatim, and a
    /// relative one joined onto its checkout. The single resolution point —
    /// dispatch and every renderer come here rather than joining paths itself.
    pub fn resolve_doc(&self, doc: &Doc) -> Result<String> {
        if doc.is_url() || Path::new(&doc.location).is_absolute() {
            return Ok(doc.location.clone());
        }
        let repo = match doc.repo_id {
            Some(id) => self.repo(id)?,
            None => self.default_repo(doc.project_id)?,
        };
        Ok(Path::new(&repo.path)
            .join(&doc.location)
            .to_string_lossy()
            .into_owned())
    }

    /// Remove a document and every task link to it, in one transaction. Unlike
    /// a repo, a doc is navigational — nothing resolves to nothing when it goes
    /// — so this unlinks rather than refusing, and returns the tasks it freed
    /// so the caller can say how far the removal reached.
    pub fn delete_doc(&mut self, doc_id: i64) -> Result<Vec<i64>> {
        let doc = self.doc(doc_id)?;
        let linked = self.tasks_for_doc(doc_id)?;
        let tx = self.conn.transaction()?;
        for task in &linked {
            log_event(&tx, task.id, "doc-unlinked", Some(doc.label()))?;
        }
        tx.execute("DELETE FROM task_docs WHERE doc_id = ?1", [doc_id])?;
        tx.execute("DELETE FROM docs WHERE id = ?1", [doc_id])?;
        log_global_event(&tx, "doc-removed", Some(&doc.location))?;
        tx.commit()?;
        Ok(linked.into_iter().map(|t| t.id).collect())
    }

    /// Link a task to a document. Returns whether the edge was new, so a
    /// repeated link reads as a no-op rather than an error — and logs the link
    /// on the task's own event trail only when something changed.
    pub fn link_doc(&mut self, task_id: i64, doc_id: i64) -> Result<bool> {
        self.task(task_id)?;
        let doc = self.doc(doc_id)?;
        let changed = self.conn.execute(
            "INSERT OR IGNORE INTO task_docs (task_id, doc_id) VALUES (?1, ?2)",
            params![task_id, doc_id],
        )?;
        if changed > 0 {
            log_event(&self.conn, task_id, "doc-linked", Some(doc.label()))?;
        }
        Ok(changed > 0)
    }

    pub fn unlink_doc(&mut self, task_id: i64, doc_id: i64) -> Result<bool> {
        self.task(task_id)?;
        let doc = self.doc(doc_id)?;
        let changed = self.conn.execute(
            "DELETE FROM task_docs WHERE task_id = ?1 AND doc_id = ?2",
            params![task_id, doc_id],
        )?;
        if changed > 0 {
            log_event(&self.conn, task_id, "doc-unlinked", Some(doc.label()))?;
        }
        Ok(changed > 0)
    }

    /// Replace a task's whole document list — what `set --doc` writes, matching
    /// `--blocked-by`'s replace semantics so the flag can remove a link as well
    /// as add one. Each added and dropped edge is logged individually.
    pub fn set_task_docs(&mut self, task_id: i64, doc_ids: &[i64]) -> Result<Vec<Doc>> {
        self.task(task_id)?;
        let wanted: Vec<Doc> = doc_ids
            .iter()
            .map(|id| self.doc(*id))
            .collect::<Result<_>>()?;
        let current = self.docs_for_task(task_id)?;
        let tx = self.conn.transaction()?;
        for doc in &current {
            if !wanted.iter().any(|d| d.id == doc.id) {
                tx.execute(
                    "DELETE FROM task_docs WHERE task_id = ?1 AND doc_id = ?2",
                    params![task_id, doc.id],
                )?;
                log_event(&tx, task_id, "doc-unlinked", Some(doc.label()))?;
            }
        }
        for doc in &wanted {
            if !current.iter().any(|d| d.id == doc.id) {
                tx.execute(
                    "INSERT INTO task_docs (task_id, doc_id) VALUES (?1, ?2)",
                    params![task_id, doc.id],
                )?;
                log_event(&tx, task_id, "doc-linked", Some(doc.label()))?;
            }
        }
        tx.commit()?;
        self.docs_for_task(task_id)
    }

    /// The documents a task cites, in registration order.
    pub fn docs_for_task(&self, task_id: i64) -> Result<Vec<Doc>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {} FROM docs d JOIN task_docs td ON td.doc_id = d.id
             WHERE td.task_id = ?1 ORDER BY d.id",
            prefixed(DOC_COLUMNS, "d")
        ))?;
        let rows = stmt.query_map([task_id], doc_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    /// Every document link keyed by task id, loaded whole — what the TUI reads
    /// once per refresh so the render path never queries the store, the same
    /// shape as the dependency maps.
    pub fn docs_by_task(&self) -> Result<HashMap<i64, Vec<Doc>>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT td.task_id, {} FROM docs d JOIN task_docs td ON td.doc_id = d.id
             ORDER BY td.task_id, d.id",
            prefixed(DOC_COLUMNS, "d")
        ))?;
        let rows = stmt.query_map([], |row| {
            Ok((row.get::<_, i64>(0)?, doc_from_row_at(row, 1)?))
        })?;
        let mut map: HashMap<i64, Vec<Doc>> = HashMap::new();
        for row in rows {
            let (task_id, doc) = row?;
            map.entry(task_id).or_default().push(doc);
        }
        Ok(map)
    }

    /// The tasks derived from a document — the "which tasks came from this
    /// plan?" query, in id order so a plan's rollout reads chronologically.
    pub fn tasks_for_doc(&self, doc_id: i64) -> Result<Vec<Task>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {} FROM tasks t JOIN task_docs td ON td.task_id = t.id
             WHERE td.doc_id = ?1 ORDER BY t.id",
            prefixed(TASK_COLUMNS, "t")
        ))?;
        let rows = stmt.query_map([doc_id], task_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    // --- tasks ---

    pub fn create_task(&mut self, new: NewTask) -> Result<Task> {
        if !matches!(
            new.state,
            TaskState::Proposed | TaskState::Parked | TaskState::Ready
        ) {
            return Err(Error::Invalid(format!(
                "a task cannot be created in state '{}'",
                new.state
            )));
        }
        if new.human && new.agent.is_some() {
            return Err(Error::Invalid(
                "a human-only task cannot carry an agent override — the override only \
                 selects a dispatch agent, and no agent can execute the task"
                    .into(),
            ));
        }
        if new.human && new.deep {
            return Err(Error::Invalid(
                "a human-only task cannot be deep — deep only selects a dispatch model, \
                 and no agent can execute the task"
                    .into(),
            ));
        }
        // An archived project accepts no new work through any door — `add`,
        // `propose`, and import all create through here (DESIGN.md §5).
        let project = self.project(new.project_id)?;
        if project.archived {
            return Err(Error::ProjectArchived { name: project.name });
        }
        // A task's checkout is chosen from its own project's repos; NULL means
        // the project default, which is what every task created without one gets.
        if let Some(repo_id) = new.repo_id {
            let repo = self.repo(repo_id)?;
            if repo.project_id != new.project_id {
                return Err(Error::Invalid(format!(
                    "repo '{}' belongs to another project",
                    repo.name
                )));
            }
        }
        let tx = self.conn.transaction()?;
        tx.execute(
            "INSERT INTO tasks (project_id, repo_id, title, body, priority, state, agent, human,
                                deep, state_since, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, datetime('now'), datetime('now'))",
            params![
                new.project_id,
                new.repo_id,
                new.title,
                new.body,
                new.priority,
                new.state,
                new.agent,
                new.human,
                new.deep
            ],
        )?;
        let id = tx.last_insert_rowid();
        log_event(&tx, id, "created", Some(new.state.as_str()))?;
        tx.commit()?;
        self.task(id)
    }

    pub fn task(&self, id: i64) -> Result<Task> {
        get_task(&self.conn, id)?.ok_or(Error::TaskNotFound(id))
    }

    pub fn tasks(&self) -> Result<Vec<Task>> {
        let mut stmt = self
            .conn
            .prepare(&format!("SELECT {TASK_COLUMNS} FROM tasks ORDER BY id"))?;
        let rows = stmt.query_map([], task_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    pub fn update_task(&mut self, id: i64, edit: TaskEdit) -> Result<Task> {
        let current = self.task(id)?;
        if edit.human && edit.agent.is_some() {
            return Err(Error::HumanTask {
                id,
                reason: "an agent override is meaningless on a task no agent can execute — \
                         clear one or the other"
                    .into(),
            });
        }
        if edit.human && edit.deep {
            return Err(Error::HumanTask {
                id,
                reason: "the deep flag is meaningless on a task no agent can execute — it \
                         only selects a dispatch model; clear one or the other"
                    .into(),
            });
        }
        // `needs-input`, `review`, and `stalled` are unreachable for human tasks
        // (§6), so a task sitting in one — or one an agent session is still open
        // on — is demonstrably agent-executed and cannot be flagged human.
        if edit.human && !current.human {
            if matches!(
                current.state,
                TaskState::NeedsInput | TaskState::Review | TaskState::Stalled
            ) {
                return Err(Error::HumanTask {
                    id,
                    reason: format!(
                        "a task in state '{}' was executed by an agent; resolve it first",
                        current.state
                    ),
                });
            }
            let open_sessions: i64 = self.conn.query_row(
                "SELECT COUNT(*) FROM sessions WHERE task_id = ?1 AND ended_at IS NULL",
                [id],
                |r| r.get(0),
            )?;
            if open_sessions > 0 {
                return Err(Error::HumanTask {
                    id,
                    reason: "an agent session is still open on it; complete or abort it first"
                        .into(),
                });
            }
        }
        let tx = self.conn.transaction()?;
        tx.execute(
            "UPDATE tasks SET title = ?1, body = ?2, priority = ?3, agent = ?4, human = ?5,
                              deep = ?6
             WHERE id = ?7",
            params![
                edit.title,
                edit.body,
                edit.priority,
                edit.agent,
                edit.human,
                edit.deep,
                id
            ],
        )?;
        // A body edit overwrites the task's whole brief in place, so the log
        // keeps the text it replaced (DESIGN.md §8) — the append-only audit
        // covering the one field whose loss cannot be reconstructed from state.
        // Only a real change is logged, since every `set` lands here.
        if edit.body != current.body && !current.body.is_empty() {
            log_event(&tx, id, "body", Some(&current.body))?;
        }
        tx.commit()?;
        self.task(id)
    }

    /// Re-prioritise a task in isolation (DESIGN.md §7). Unlike `update_task`
    /// this touches only `priority`, and it logs the change. Task state is left
    /// untouched.
    pub fn set_priority(&mut self, id: i64, priority: Priority) -> Result<Task> {
        let changed = self.conn.execute(
            "UPDATE tasks SET priority = ?1 WHERE id = ?2",
            params![priority, id],
        )?;
        if changed == 0 {
            return Err(Error::TaskNotFound(id));
        }
        log_event(&self.conn, id, "priority", Some(&priority.to_string()))?;
        self.task(id)
    }

    /// Flag a task as warranting the agent's strongest model, or clear the flag
    /// (DESIGN.md §8). Like [`set_priority`] this touches one field and logs the
    /// change, so the TUI's toggle needs no full edit; task state is untouched.
    /// Refused on a human task, which is never dispatched and so has no model.
    ///
    /// [`set_priority`]: Store::set_priority
    pub fn set_deep(&mut self, id: i64, deep: bool) -> Result<Task> {
        let task = self.task(id)?;
        if deep && task.human {
            return Err(Error::HumanTask {
                id,
                reason: "the deep flag only selects a dispatch model, and no agent can \
                         execute the task"
                    .into(),
            });
        }
        self.conn.execute(
            "UPDATE tasks SET deep = ?1 WHERE id = ?2",
            params![deep, id],
        )?;
        log_event(
            &self.conn,
            id,
            "deep",
            Some(if deep { "set" } else { "cleared" }),
        )?;
        self.task(id)
    }

    /// Track (or, with `None`, untrack) a GitHub PR on a task (DESIGN.md §11c).
    /// The URL is stored verbatim — validation is the caller's job — and the
    /// change is logged. Leaves task state untouched.
    pub fn set_pr(&mut self, id: i64, pr_url: Option<&str>) -> Result<Task> {
        let changed = self.conn.execute(
            "UPDATE tasks SET pr_url = ?1 WHERE id = ?2",
            params![pr_url, id],
        )?;
        if changed == 0 {
            return Err(Error::TaskNotFound(id));
        }
        log_event(&self.conn, id, "pr", pr_url.or(Some("cleared")))?;
        self.task(id)
    }

    /// Record (or, with `None`, clear) the git branch a task's work lives on —
    /// the intended name a human sets for dispatch to inject, or the name an
    /// agent reports through `voro done --branch`. Stored verbatim (Voro never
    /// runs git) and logged; task state is left untouched.
    pub fn set_branch(&mut self, id: i64, branch: Option<&str>) -> Result<Task> {
        let changed = self.conn.execute(
            "UPDATE tasks SET branch = ?1 WHERE id = ?2",
            params![branch, id],
        )?;
        if changed == 0 {
            return Err(Error::TaskNotFound(id));
        }
        log_event(&self.conn, id, "branch", branch.or(Some("cleared")))?;
        self.task(id)
    }

    /// Set or replace a task's completion summary outside `done` (DESIGN.md §8):
    /// append a `summary` event, which [`latest_summary`] supersedes with, so the
    /// PR body, detail view, and incomplete-report flag all pick up the newest.
    /// This amends a stale PR body or supplies a missing `[incomplete report]`
    /// summary without a `reject` → re-`done` round trip. Allowed only on a
    /// `running` or `review` task; it never touches `tasks.state`.
    ///
    /// [`latest_summary`]: Store::latest_summary
    pub fn set_summary(&mut self, id: i64, summary: &str) -> Result<Task> {
        if summary.trim().is_empty() {
            return Err(Error::Invalid("a summary is required".into()));
        }
        let task = self.task(id)?;
        if !matches!(task.state, TaskState::Running | TaskState::Review) {
            return Err(Error::Invalid(format!(
                "a summary can only be set on a running or review task; task {} is {}",
                id, task.state
            )));
        }
        log_event(&self.conn, id, "summary", Some(summary.trim()))?;
        self.task(id)
    }

    /// How the newest concluded refine round on a task ended (DESIGN.md §6),
    /// read off the `refine` event the `refining → proposed` transition logs.
    /// `None` for a task no round has ever concluded on. This is what the two
    /// row markers are derived from, so a proposal says which of "reworked" and
    /// "the rewrite died" it is rather than leaving the operator to notice an
    /// absence.
    pub fn latest_refine_outcome(&self, task_id: i64) -> Result<Option<RefineOutcome>> {
        let detail: Option<String> = self
            .conn
            .query_row(
                "SELECT detail FROM events WHERE task_id = ?1 AND kind = 'refine'
                 ORDER BY id DESC LIMIT 1",
                [task_id],
                |r| r.get::<_, Option<String>>(0),
            )
            .optional()?
            .flatten();
        detail.map(|d| RefineOutcome::parse(&d)).transpose()
    }

    /// Whether `task_id` is a `proposed` task whose last refine round rewrote
    /// its body (DESIGN.md §6) — what renders the `↻ refined` marker. Gated on
    /// `proposed`, so triaging the task clears it, and on the *concluded* round,
    /// so a proposal is only marked once the improved body exists. Derived
    /// fresh, never stored.
    pub fn refined_flag(&self, task_id: i64) -> Result<bool> {
        self.refine_marker(task_id, RefineOutcome::Applied)
    }

    /// The other half of [`refined_flag`]: a `proposed` task whose last refine
    /// round died without applying anything, which renders the `⚠ refine
    /// failed` marker. Same lifecycle — shown while `proposed`, cleared by
    /// triage — because a failed refine must be visibly different from a
    /// proposal nobody has refined.
    ///
    /// [`refined_flag`]: Store::refined_flag
    pub fn refine_failed_flag(&self, task_id: i64) -> Result<bool> {
        self.refine_marker(task_id, RefineOutcome::Failed)
    }

    /// Correct the outcome of a round that concluded `failed` but whose rewrite
    /// then arrived anyway (DESIGN.md §6): a body replacement landing on a
    /// `proposed` task whose last round failed says that round did apply
    /// something, however late, so the recorded outcome is superseded by
    /// `applied` and the row's marker flips from `⚠ refine failed` to `↻
    /// refined`. A rewritten body sitting under a failure marker is worse than
    /// no marker at all: it teaches the operator to disbelieve the one signal
    /// that exists to say a rewrite they asked for silently never happened.
    ///
    /// This corrects a *concluded* round and nothing else — the task neither
    /// re-enters `refining` nor transitions, and the round's session keeps the
    /// outcome the reconciler observed of its process. Returns whether anything
    /// was corrected, so a caller can say so; a no-op on any other state or any
    /// other last outcome, and idempotent, since the correction it appends is
    /// itself the newest outcome.
    pub fn correct_late_refine(&mut self, task_id: i64) -> Result<bool> {
        if !self.refine_failed_flag(task_id)? {
            return Ok(false);
        }
        log_event(
            &self.conn,
            task_id,
            "refine",
            Some(RefineOutcome::Applied.as_str()),
        )?;
        Ok(true)
    }

    fn refine_marker(&self, task_id: i64, wanted: RefineOutcome) -> Result<bool> {
        let state: Option<TaskState> = self
            .conn
            .query_row("SELECT state FROM tasks WHERE id = ?1", [task_id], |r| {
                r.get(0)
            })
            .optional()?;
        if state != Some(TaskState::Proposed) {
            return Ok(false);
        }
        Ok(self.latest_refine_outcome(task_id)? == Some(wanted))
    }

    /// The newest refine note recorded on a task — the note that rode the
    /// `proposed → refining` transition — for the seed context a refine agent is
    /// launched with and for the detail views.
    pub fn latest_refine_note(&self, task_id: i64) -> Result<Option<String>> {
        Ok(self
            .conn
            .query_row(
                "SELECT detail FROM events WHERE task_id = ?1 AND kind = 'refined'
                 ORDER BY id DESC LIMIT 1",
                [task_id],
                |r| r.get::<_, Option<String>>(0),
            )
            .optional()?
            .flatten())
    }

    // --- deps ---

    /// The task a proposal was discovered from (the `discovered-from` edge of
    /// §5), if any — the context a sloppy proposal is usually missing, which is
    /// what a refine session is seeded with. The newest edge wins if a task
    /// somehow carries several.
    pub fn discovered_from(&self, task_id: i64) -> Result<Option<Task>> {
        let parent: Option<i64> = self
            .conn
            .query_row(
                "SELECT depends_on FROM deps
                 WHERE task_id = ?1 AND kind = 'discovered-from'
                 ORDER BY depends_on DESC LIMIT 1",
                [task_id],
                |r| r.get(0),
            )
            .optional()?;
        parent.map(|id| self.task(id)).transpose()
    }

    pub fn add_dep(&mut self, task_id: i64, depends_on: i64, kind: DepKind) -> Result<()> {
        if kind != DepKind::Blocks && task_id == depends_on {
            return Err(Error::Invalid("a task cannot depend on itself".into()));
        }
        let tx = self.conn.transaction()?;
        if kind == DepKind::Blocks {
            crate::transition::reject_blocks_cycle(&tx, task_id, depends_on)?;
        }
        let inserted = tx.execute(
            "INSERT INTO deps (task_id, depends_on, kind) VALUES (?1, ?2, ?3)
             ON CONFLICT (task_id, depends_on, kind) DO NOTHING",
            params![task_id, depends_on, kind],
        )?;
        if inserted == 0 {
            return Err(Error::Invalid(format!(
                "#{task_id} already has a {kind} dependency on #{depends_on}"
            )));
        }
        if kind == DepKind::Blocks {
            crate::transition::reconcile_readiness(&tx, task_id)?;
        }
        tx.commit()?;
        Ok(())
    }

    /// Drop one edge. The kind is part of the identity of an edge — a pair may
    /// carry several — so removing a blocker must not take the
    /// `discovered-from` edge beside it with it.
    pub fn remove_dep(&mut self, task_id: i64, depends_on: i64, kind: DepKind) -> Result<()> {
        let tx = self.conn.transaction()?;
        let removed = tx.execute(
            "DELETE FROM deps WHERE task_id = ?1 AND depends_on = ?2 AND kind = ?3",
            params![task_id, depends_on, kind],
        )?;
        if removed == 0 {
            return Err(Error::Invalid(format!(
                "#{task_id} has no {kind} dependency on #{depends_on}"
            )));
        }
        if kind == DepKind::Blocks {
            crate::transition::reconcile_readiness(&tx, task_id)?;
        }
        tx.commit()?;
        Ok(())
    }

    /// Every dependency edge of every kind, keyed by the depending task and
    /// resolved to the dependency's current title and state — the forward
    /// direction a detail view renders as `blocked by #N`. One query feeds every
    /// pane, so the render path never issues a per-row lookup.
    pub fn deps_by_task(&self) -> Result<HashMap<i64, Vec<DepRef>>> {
        self.dep_refs(
            "SELECT d.task_id, t.id, t.title, t.state, d.kind
             FROM deps d JOIN tasks t ON t.id = d.depends_on
             ORDER BY d.task_id, t.id, d.kind",
        )
    }

    /// The reverse edges: every dependency keyed by the task depended *on*,
    /// resolved to the depending task — who a task blocks (or spawned).
    pub fn dependents_by_task(&self) -> Result<HashMap<i64, Vec<DepRef>>> {
        self.dep_refs(
            "SELECT d.depends_on, t.id, t.title, t.state, d.kind
             FROM deps d JOIN tasks t ON t.id = d.task_id
             ORDER BY d.depends_on, t.id, d.kind",
        )
    }

    fn dep_refs(&self, sql: &str) -> Result<HashMap<i64, Vec<DepRef>>> {
        let mut stmt = self.conn.prepare(sql)?;
        let rows = stmt.query_map([], |row| {
            let key: i64 = row.get(0)?;
            let dep = DepRef {
                id: row.get(1)?,
                title: row.get(2)?,
                state: row.get(3)?,
                kind: row.get(4)?,
            };
            Ok((key, dep))
        })?;
        let mut map: HashMap<i64, Vec<DepRef>> = HashMap::new();
        for row in rows {
            let (key, dep) = row?;
            map.entry(key).or_default().push(dep);
        }
        Ok(map)
    }

    pub fn deps_of(&self, task_id: i64) -> Result<Vec<Dep>> {
        let mut stmt = self.conn.prepare(
            "SELECT task_id, depends_on, kind FROM deps WHERE task_id = ?1
             ORDER BY depends_on, kind",
        )?;
        let rows = stmt.query_map([task_id], |row| {
            Ok(Dep {
                task_id: row.get(0)?,
                depends_on: row.get(1)?,
                kind: row.get(2)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    // --- sessions ---

    /// Open a session for a running task, stamping `started_at`. `ended_at` and
    /// `outcome` stay NULL until [`end_session`](Store::end_session).
    /// `liveness_source` is which source reconciliation must read the session by
    /// (DESIGN.md §8), which only the caller that spawned the process knows.
    pub fn create_session(
        &mut self,
        task_id: i64,
        agent: &str,
        pid: Option<i64>,
        liveness_source: LivenessSource,
        log_path: Option<&str>,
    ) -> Result<Session> {
        let id = insert_session(&self.conn, task_id, agent, pid, liveness_source, log_path)?;
        self.session(id)
    }

    /// Record the agent's own reference for a session, captured
    /// after launch — the row necessarily exists before the reference does,
    /// so this is an update rather than a `create_session` parameter.
    pub fn set_session_ref(&mut self, id: i64, session_ref: &str) -> Result<Session> {
        let changed = self.conn.execute(
            "UPDATE sessions SET session_ref = ?1 WHERE id = ?2",
            params![session_ref, id],
        )?;
        if changed == 0 {
            return Err(Error::SessionNotFound(id));
        }
        self.session(id)
    }

    /// Record what a confirmed headless send did to a session (DESIGN.md §8):
    /// the process now carrying the turn, and — where the agent forked rather
    /// than resumed in place — the reference the conversation continues under.
    /// One statement, so a reconcile in another window never reads the new
    /// reference beside the old process or the reverse.
    pub fn record_session_send(
        &mut self,
        id: i64,
        session_ref: Option<&str>,
        pid: i64,
    ) -> Result<Session> {
        let changed = self.conn.execute(
            "UPDATE sessions SET pid = ?1, session_ref = COALESCE(?2, session_ref)
             WHERE id = ?3",
            params![pid, session_ref, id],
        )?;
        if changed == 0 {
            return Err(Error::SessionNotFound(id));
        }
        self.session(id)
    }

    /// Close a session with its outcome, stamping `ended_at`.
    pub fn end_session(&mut self, id: i64, outcome: SessionOutcome) -> Result<Session> {
        if set_session_outcome(&self.conn, id, outcome)? == 0 {
            return Err(Error::SessionNotFound(id));
        }
        self.session(id)
    }

    pub fn session(&self, id: i64) -> Result<Session> {
        self.conn
            .query_row(
                &format!("SELECT {SESSION_COLUMNS} FROM sessions WHERE id = ?1"),
                [id],
                session_from_row,
            )
            .optional()?
            .ok_or(Error::SessionNotFound(id))
    }

    pub fn sessions_for(&self, task_id: i64) -> Result<Vec<Session>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {SESSION_COLUMNS} FROM sessions WHERE task_id = ?1 ORDER BY id DESC"
        ))?;
        let rows = stmt.query_map([task_id], session_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    /// Every task's newest session, keyed by task id, in one query — what the
    /// TUI loads per refresh to answer "what is/was this session doing?" without
    /// querying the store mid-draw. Session ids are monotonic, so `max(id)` is
    /// the latest.
    pub fn latest_sessions(&self) -> Result<std::collections::HashMap<i64, Session>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {SESSION_COLUMNS} FROM sessions s
             WHERE s.id = (SELECT max(id) FROM sessions WHERE task_id = s.task_id)"
        ))?;
        let rows = stmt.query_map([], session_from_row)?;
        rows.map(|r| r.map(|s| (s.task_id, s)))
            .collect::<rusqlite::Result<_>>()
            .map_err(Into::into)
    }

    /// Sessions that have not yet ended, newest first.
    pub fn live_sessions(&self) -> Result<Vec<Session>> {
        let mut stmt = self.conn.prepare(&format!(
            "SELECT {SESSION_COLUMNS} FROM sessions WHERE ended_at IS NULL ORDER BY id DESC"
        ))?;
        let rows = stmt.query_map([], session_from_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    /// Whether `task_id` is a `review` task carrying a *half-written* completion
    /// report — a branch with no summary (DESIGN.md §8). A summary with no
    /// branch is not flagged: an investigation, triage or audit produces no code
    /// and its summary is the whole deliverable. Gated on `review`, derived
    /// fresh rather than stored.
    pub fn incomplete_report_flag(&self, task_id: i64) -> Result<bool> {
        let row: Option<(TaskState, Option<String>)> = self
            .conn
            .query_row(
                "SELECT state, branch FROM tasks WHERE id = ?1",
                [task_id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .optional()?;
        let Some((state, branch)) = row else {
            return Ok(false);
        };
        if state != TaskState::Review {
            return Ok(false);
        }
        let has_branch = branch.is_some();
        let has_summary = self.latest_summary(task_id)?.is_some();
        Ok(has_branch && !has_summary)
    }

    /// Rows for the cockpit's running strip (DESIGN.md §9): every `running`,
    /// `refining`, or `waiting` task, joined with its open session if it has
    /// one. The strip filters on task *state*, so `review`/`needs-input` tasks
    /// (session still open) do not appear, while a refine in flight and a
    /// handed-off task both do — an open session does not imply executing
    /// the task (§8), and what the strip shows is work in flight that someone
    /// else owns. A hand-started task with no session shows with `session_id`/
    /// `agent` `NULL`. The one-open-session invariant (§8) bounds the join to one
    /// row per task; elapsed is computed in SQL so the TUI only formats it.
    ///
    /// A `waiting` task measures its elapsed from `state_since` rather than its
    /// session: the session opened when the agent started the work, long before
    /// the hand-off, and what the operator wants from a handed-off row is how
    /// long it has been waiting. Waiting rows sort after the rest, since they
    /// are the ones nobody is actively typing into.
    ///
    /// Archived projects leave the cockpit entirely (§5), the strip included.
    pub fn running_rows(&self) -> Result<Vec<RunningRow>> {
        let mut stmt = self.conn.prepare(
            "WITH strip AS (
                 SELECT s.id AS session_id, t.id AS task_id, t.title, t.state,
                        s.agent, t.pr_url,
                        CASE WHEN t.state = 'waiting' THEN t.state_since
                             ELSE COALESCE(s.started_at, t.state_since) END AS since
                 FROM tasks t
                 JOIN projects p ON p.id = t.project_id
                 LEFT JOIN sessions s ON s.task_id = t.id AND s.ended_at IS NULL
                 WHERE t.state IN ('running','refining','waiting') AND p.archived = 0
             )
             SELECT session_id, task_id, title, state, agent, pr_url, since,
                    CAST(strftime('%s', 'now') - strftime('%s', since) AS INTEGER)
             FROM strip
             ORDER BY (state = 'waiting'), (session_id IS NULL),
                      session_id DESC, task_id DESC",
        )?;
        let rows = stmt.query_map([], |row| {
            Ok(RunningRow {
                session_id: row.get(0)?,
                task_id: row.get(1)?,
                task_title: row.get(2)?,
                task_state: row.get(3)?,
                agent: row.get(4)?,
                pr_url: row.get(5)?,
                started_at: row.get(6)?,
                elapsed_secs: row.get(7)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    // --- events ---

    /// The most recent completion summary a task recorded (DESIGN.md §8): the
    /// detail of its newest `summary` event, logged by `done --summary` or
    /// amended by `set --summary` ([`set_summary`]). This is the PR body when
    /// `pr` opens a pull request. `None` when the task never carried a summary.
    ///
    /// [`set_summary`]: Store::set_summary
    pub fn latest_summary(&self, task_id: i64) -> Result<Option<String>> {
        Ok(self
            .conn
            .query_row(
                "SELECT detail FROM events WHERE task_id = ?1 AND kind = 'summary'
                 ORDER BY id DESC LIMIT 1",
                [task_id],
                |r| r.get::<_, Option<String>>(0),
            )
            .optional()?
            .flatten())
    }

    /// Record the branch revision the operator has just reviewed (DESIGN.md
    /// §8), so the next look at this task can be narrowed to what the rework
    /// added. Written at rejection, when the head is exactly what was judged.
    /// The `events` table carries it, so delta re-review costs no column and no
    /// migration; a later recording supersedes an earlier one the way a summary
    /// does.
    pub fn record_reviewed(&mut self, id: i64, sha: &str) -> Result<()> {
        let sha = sha.trim();
        if sha.is_empty() {
            return Err(Error::Invalid("a reviewed revision is required".into()));
        }
        // Prove the task exists before appending, so a typo'd id leaves no
        // orphan row in an append-only log.
        self.task(id)?;
        log_event(&self.conn, id, crate::review::REVIEWED_EVENT, Some(sha))
    }

    /// The revision recorded by the newest [`record_reviewed`], or `None` for a
    /// task nobody has reviewed and sent back — which is what keeps a first
    /// review showing the whole diff.
    ///
    /// [`record_reviewed`]: Store::record_reviewed
    pub fn last_reviewed(&self, task_id: i64) -> Result<Option<String>> {
        Ok(self
            .conn
            .query_row(
                "SELECT detail FROM events WHERE task_id = ?1 AND kind = ?2
                 ORDER BY id DESC LIMIT 1",
                params![task_id, crate::review::REVIEWED_EVENT],
                |r| r.get::<_, Option<String>>(0),
            )
            .optional()?
            .flatten())
    }

    pub fn events_for(&self, task_id: i64) -> Result<Vec<Event>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, task_id, at, kind, detail FROM events WHERE task_id = ?1 ORDER BY id",
        )?;
        let rows = stmt.query_map([task_id], |row| {
            Ok(Event {
                id: row.get(0)?,
                task_id: row.get(1)?,
                at: row.get(2)?,
                kind: row.get(3)?,
                detail: row.get(4)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }
}

pub(crate) const TASK_COLUMNS: &str = "id, project_id, title, body, priority, state, agent, \
                                       question, pr_url, branch, state_since, created_at, \
                                       closed_at, human, repo_id, deep";

pub(crate) fn get_task(conn: &Connection, id: i64) -> Result<Option<Task>> {
    Ok(conn
        .query_row(
            &format!("SELECT {TASK_COLUMNS} FROM tasks WHERE id = ?1"),
            [id],
            task_from_row,
        )
        .optional()?)
}

pub(crate) fn task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Task> {
    Ok(Task {
        id: row.get(0)?,
        project_id: row.get(1)?,
        title: row.get(2)?,
        body: row.get(3)?,
        priority: row.get(4)?,
        state: row.get(5)?,
        agent: row.get(6)?,
        question: row.get(7)?,
        pr_url: row.get(8)?,
        branch: row.get(9)?,
        state_since: row.get(10)?,
        created_at: row.get(11)?,
        closed_at: row.get(12)?,
        human: row.get(13)?,
        repo_id: row.get(14)?,
        deep: row.get(15)?,
    })
}

pub(crate) const SESSION_COLUMNS: &str = "id, task_id, agent, pid, session_ref, liveness_source, log_path, started_at, ended_at, outcome";

/// A task's currently-open session, if it has one. The one-open-session
/// invariant (DESIGN.md §8) means there is at most one row to find, so this is
/// how a transaction learns *which* session it is about to close.
pub(crate) fn get_open_session(conn: &Connection, task_id: i64) -> Result<Option<Session>> {
    Ok(conn
        .query_row(
            &format!(
                "SELECT {SESSION_COLUMNS} FROM sessions
                 WHERE task_id = ?1 AND ended_at IS NULL"
            ),
            [task_id],
            session_from_row,
        )
        .optional()?)
}

pub(crate) fn get_session(conn: &Connection, id: i64) -> Result<Option<Session>> {
    Ok(conn
        .query_row(
            &format!("SELECT {SESSION_COLUMNS} FROM sessions WHERE id = ?1"),
            [id],
            session_from_row,
        )
        .optional()?)
}

fn session_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
    Ok(Session {
        id: row.get(0)?,
        task_id: row.get(1)?,
        agent: row.get(2)?,
        pid: row.get(3)?,
        session_ref: row.get(4)?,
        liveness_source: row.get(5)?,
        log_path: row.get(6)?,
        started_at: row.get(7)?,
        ended_at: row.get(8)?,
        outcome: row.get(9)?,
    })
}

pub(crate) const PROJECT_COLUMNS: &str = "id, name, weight, viewer, archived";

fn project_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Project> {
    Ok(Project {
        id: row.get(0)?,
        name: row.get(1)?,
        weight: row.get(2)?,
        viewer: row.get(3)?,
        archived: row.get(4)?,
    })
}

pub(crate) const DOC_COLUMNS: &str = "id, project_id, repo_id, title, location, created_at";

fn doc_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Doc> {
    doc_from_row_at(row, 0)
}

/// The same projection read from a wider row — a join that carries the task id
/// alongside the doc columns.
fn doc_from_row_at(row: &rusqlite::Row<'_>, at: usize) -> rusqlite::Result<Doc> {
    Ok(Doc {
        id: row.get(at)?,
        project_id: row.get(at + 1)?,
        repo_id: row.get(at + 2)?,
        title: row.get(at + 3)?,
        location: row.get(at + 4)?,
        created_at: row.get(at + 5)?,
    })
}

/// Qualify a column list with a table alias, so a joined query can reuse the
/// same projection constant its unjoined sibling does.
fn prefixed(columns: &str, alias: &str) -> String {
    columns
        .split(", ")
        .map(|c| format!("{alias}.{c}"))
        .collect::<Vec<_>>()
        .join(", ")
}

pub(crate) const REPO_COLUMNS: &str = "id, project_id, name, path, is_default";

fn repo_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Repo> {
    Ok(Repo {
        id: row.get(0)?,
        project_id: row.get(1)?,
        name: row.get(2)?,
        path: row.get(3)?,
        is_default: row.get(4)?,
    })
}

/// Insert a session row, stamping `started_at`, and return its id. Shared by
/// [`Store::create_session`] and the dispatch transaction.
/// Enforces the one-open-session invariant (DESIGN.md §8): opening a new session
/// first closes any predecessor still open (stamped `aborted`). The partial
/// unique index is the schema-level backstop.
pub(crate) fn insert_session(
    conn: &Connection,
    task_id: i64,
    agent: &str,
    pid: Option<i64>,
    liveness_source: LivenessSource,
    log_path: Option<&str>,
) -> Result<i64> {
    close_open_session(conn, task_id, SessionOutcome::Aborted)?;
    conn.execute(
        "INSERT INTO sessions (task_id, agent, pid, liveness_source, log_path, started_at)
         VALUES (?1, ?2, ?3, ?4, ?5, datetime('now'))",
        params![task_id, agent, pid, liveness_source, log_path],
    )?;
    Ok(conn.last_insert_rowid())
}

/// Close a task's currently-open session, if any, stamping `ended_at` and
/// `outcome`. The one-open-session invariant (DESIGN.md §8) means this touches
/// at most one row. Used to supersede a predecessor and to close the session on
/// a terminal transition. Returns the number of rows closed (0 if none was open).
pub(crate) fn close_open_session(
    conn: &Connection,
    task_id: i64,
    outcome: SessionOutcome,
) -> Result<usize> {
    Ok(conn.execute(
        "UPDATE sessions SET ended_at = datetime('now'), outcome = ?1
         WHERE task_id = ?2 AND ended_at IS NULL",
        params![outcome, task_id],
    )?)
}

/// Stamp `ended_at` and record `outcome` on a session, returning the number of
/// rows changed (0 if the id is unknown). Shared by [`Store::end_session`] and
/// reconciliation.
pub(crate) fn set_session_outcome(
    conn: &Connection,
    id: i64,
    outcome: SessionOutcome,
) -> Result<usize> {
    Ok(conn.execute(
        "UPDATE sessions SET ended_at = datetime('now'), outcome = ?1 WHERE id = ?2",
        params![outcome, id],
    )?)
}

pub(crate) fn log_event(
    conn: &Connection,
    task_id: i64,
    kind: &str,
    detail: Option<&str>,
) -> Result<()> {
    conn.execute(
        "INSERT INTO events (task_id, at, kind, detail) VALUES (?1, datetime('now'), ?2, ?3)",
        params![task_id, kind, detail],
    )?;
    Ok(())
}

/// An audit row for a mutation that belongs to no single task — registering or
/// removing a document. The `events.task_id` column is nullable exactly for
/// this, and the append-only log stays the record of every mutation.
pub(crate) fn log_global_event(conn: &Connection, kind: &str, detail: Option<&str>) -> Result<()> {
    conn.execute(
        "INSERT INTO events (task_id, at, kind, detail)
         VALUES (NULL, datetime('now'), ?1, ?2)",
        params![kind, detail],
    )?;
    Ok(())
}

#[cfg(test)]
mod schema_guard_tests {
    use super::*;

    /// A unique scratch directory per test, cleaned up by the caller.
    fn scratch(tag: &str) -> PathBuf {
        tempfile::Builder::new()
            .prefix(&format!("voro-store-{tag}-"))
            .tempdir()
            .unwrap()
            .keep()
    }

    #[test]
    fn a_cargo_build_directory_is_recognised_in_every_profile() {
        for exe in [
            "/home/u/proj/target/debug/voro",
            "/home/u/proj/target/release/voro",
            "/home/u/proj/target/debug/deps/voro-1a2b3c",
            "/home/u/proj/.claude/worktrees/feature/target/debug/voro",
        ] {
            assert!(
                path_is_cargo_target(Path::new(exe)),
                "{exe} should be a dev build"
            );
        }
        for exe in [
            "/home/u/.cargo/bin/voro",
            "/usr/local/bin/voro",
            "/opt/target-practice/voro",
        ] {
            assert!(
                !path_is_cargo_target(Path::new(exe)),
                "{exe} should not be a dev build"
            );
        }
    }

    #[test]
    fn a_database_from_the_future_is_refused_with_a_way_out() {
        let dir = scratch("future");
        let path = dir.join("voro.db");
        Store::open(&path).unwrap();
        Connection::open(&path)
            .unwrap()
            .pragma_update(None, "user_version", (MIGRATIONS.len() + 1) as i64)
            .unwrap();

        let message = match Store::open(&path) {
            Ok(_) => panic!("a store from the future should not open"),
            Err(e) => e.to_string(),
        };
        assert!(message.contains("schema version"), "{message}");
        // The remedy is the point of the error: a version mismatch the operator
        // cannot act on is the cryptic failure this guard exists to replace.
        // Restoring leads, since running the build that migrated it entrenches
        // an unreleased schema.
        assert!(
            message.contains("Restore a pre-migration snapshot"),
            "{message}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn the_dev_store_is_told_to_reseed_rather_than_reinstall() {
        let remedy = remedy_for_schema_ahead(Some(&Store::dev_db_path()));
        assert!(remedy.contains("voro seed --force"), "{remedy}");
        assert!(!remedy.contains("cargo install"), "{remedy}");
    }

    #[test]
    fn a_migration_snapshots_the_database_beside_it_first() {
        let dir = scratch("snapshot");
        let path = dir.join("voro.db");
        // A store one migration short of current, so opening it migrates.
        let conn = Connection::open(&path).unwrap();
        conn.execute_batch(MIGRATIONS[0]).unwrap();
        conn.pragma_update(None, "user_version", 1i64).unwrap();
        drop(conn);

        Store::open(&path).unwrap();

        let backups: Vec<_> = std::fs::read_dir(Store::backup_dir_for(&path))
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(backups.len(), 1, "{backups:?}");
        assert!(backups[0].starts_with("voro-v1-"), "{backups:?}");

        // The snapshot is the state *before* the migration, which is the only
        // thing that makes it worth keeping.
        let saved = Connection::open(Store::backup_dir_for(&path).join(&backups[0])).unwrap();
        let version: i64 = saved
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, 1);
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The case the counter cannot see: two branches each author a migration
    /// at the same index, so the database and the binary agree on the version
    /// and disagree on the schema.
    #[test]
    fn a_migration_applied_from_a_different_branch_is_refused_at_the_same_version() {
        let dir = scratch("diverged");
        let path = dir.join("voro.db");
        Store::open(&path).unwrap();
        // Rewrite the last applied migration as a rival branch's version of it,
        // leaving user_version untouched — exactly what a colliding 0017 does.
        Connection::open(&path)
            .unwrap()
            .execute(
                "UPDATE schema_migrations SET sql = ?1, applied_by = ?2 WHERE idx = ?3",
                params![
                    "ALTER TABLE projects RENAME COLUMN review_action TO viewer;",
                    "voro 0.1.0 at /home/u/.claude/worktrees/project-viewer/target/debug/voro",
                    MIGRATIONS.len() as i64
                ],
            )
            .unwrap();

        let message = match Store::open(&path) {
            Ok(_) => panic!("a divergent schema should not open"),
            Err(e) => e.to_string(),
        };
        // The counter alone would have said nothing here.
        let version: i64 = Connection::open(&path)
            .unwrap()
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, MIGRATIONS.len() as i64);
        assert!(message.contains("project-viewer"), "{message}");
        assert!(message.contains("Restore"), "{message}");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn the_journal_records_what_was_applied_and_by_whom() {
        let dir = scratch("journal");
        let path = dir.join("voro.db");
        Store::open(&path).unwrap();

        let conn = Connection::open(&path).unwrap();
        let rows: i64 = conn
            .query_row("SELECT COUNT(*) FROM schema_migrations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(rows, MIGRATIONS.len() as i64);
        let (sql, by): (String, String) = conn
            .query_row(
                "SELECT sql, applied_by FROM schema_migrations WHERE idx = 1",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(sql, MIGRATIONS[0]);
        assert!(by.starts_with("voro "), "{by}");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// History from before the journal existed is recorded as unverifiable
    /// rather than invented, and must not read as a divergence.
    #[test]
    fn pre_journal_history_is_backfilled_unverifiable_and_opens_cleanly() {
        let dir = scratch("backfill");
        let path = dir.join("voro.db");
        let conn = Connection::open(&path).unwrap();
        for sql in &MIGRATIONS[..MIGRATIONS.len() - 1] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", (MIGRATIONS.len() - 1) as i64)
            .unwrap();
        drop(conn);

        Store::open(&path).unwrap();
        Store::open(&path).unwrap();

        let conn = Connection::open(&path).unwrap();
        let unverifiable: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM schema_migrations WHERE sql IS NULL",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(unverifiable, (MIGRATIONS.len() - 1) as i64);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_fresh_database_is_not_snapshotted() {
        let dir = scratch("fresh");
        let path = dir.join("voro.db");
        Store::open(&path).unwrap();
        assert!(!Store::backup_dir_for(&path).exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A store one migration short of current, built by replaying the list —
    /// the state a release upgrade or a from-source build finds the operator's
    /// store in.
    fn store_at_previous_version(path: &Path) {
        let conn = Connection::open(path).unwrap();
        for sql in &MIGRATIONS[..MIGRATIONS.len() - 1] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", (MIGRATIONS.len() - 1) as i64)
            .unwrap();
    }

    fn open_as_production(path: &Path, consent: Option<&str>) -> Result<Store> {
        Store::open_at(Connection::open(path).unwrap(), path, path, consent)
    }

    #[test]
    fn the_production_store_refuses_to_migrate_without_consent() {
        let dir = scratch("gate-refuse");
        let path = dir.join("voro.db");
        store_at_previous_version(&path);

        let message = match open_as_production(&path, None) {
            Ok(_) => panic!("a protected store with pending migrations should not open"),
            Err(e) => e.to_string(),
        };
        assert!(message.contains("pending migration"), "{message}");
        assert!(message.contains("voro migrate"), "{message}");
        // Refused means untouched: no migration applied, no snapshot taken.
        let version: i64 = Connection::open(&path)
            .unwrap()
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, (MIGRATIONS.len() - 1) as i64);
        assert!(!Store::backup_dir_for(&path).exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn consent_migrates_the_production_store_and_is_journalled() {
        let dir = scratch("gate-consent");
        let path = dir.join("voro.db");
        store_at_previous_version(&path);

        open_as_production(&path, Some("via voro migrate --yes")).unwrap();

        let conn = Connection::open(&path).unwrap();
        let version: i64 = conn
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, MIGRATIONS.len() as i64);
        let by: String = conn
            .query_row(
                "SELECT applied_by FROM schema_migrations WHERE idx = ?1",
                [MIGRATIONS.len() as i64],
                |r| r.get(0),
            )
            .unwrap();
        assert!(by.contains("via voro migrate --yes"), "{by}");
        // The snapshot still precedes a consented migration.
        assert!(Store::backup_dir_for(&path).exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The marker, not the path, is what makes a moved or restored copy of the
    /// operator's store keep refusing (§5).
    #[test]
    fn the_protected_marker_travels_with_the_file() {
        let dir = scratch("gate-marker");
        let path = dir.join("voro.db");
        // A full open at its "production" path writes the marker.
        open_as_production(&path, None).unwrap();
        let moved = dir.join("restored-copy.db");
        std::fs::rename(&path, &moved).unwrap();
        // Winding the copy back one version makes it pending again; the gate
        // fires before any migration would re-apply, so the state is enough.
        Connection::open(&moved)
            .unwrap()
            .pragma_update(None, "user_version", (MIGRATIONS.len() - 1) as i64)
            .unwrap();

        assert!(matches!(
            Store::open(&moved),
            Err(Error::MigrationsPending { .. })
        ));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_fresh_production_store_is_created_silently_and_marked() {
        let dir = scratch("gate-fresh");
        let path = dir.join("voro.db");
        let store = open_as_production(&path, None).unwrap();
        let marked: String = store
            .conn
            .query_row(
                "SELECT value FROM store_meta WHERE key = 'protected'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(marked, "1");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// An unprotected store — scratch `--db`, the dev store — migrates on open
    /// exactly as before the gate existed.
    #[test]
    fn an_unprotected_store_still_migrates_silently() {
        let dir = scratch("gate-scratch");
        let path = dir.join("scratch.db");
        store_at_previous_version(&path);

        let store = Store::open(&path).unwrap();
        assert_eq!(store.schema_version().unwrap(), MIGRATIONS.len());
        std::fs::remove_dir_all(&dir).ok();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transition::{Action, Triage};

    fn new_ready(project_id: i64) -> NewTask {
        NewTask {
            project_id,
            repo_id: None,
            title: "t".into(),
            body: String::new(),
            priority: Priority::P2,
            state: TaskState::Ready,
            agent: None,
            human: false,
            deep: false,
        }
    }

    #[test]
    fn rename_project_updates_name_and_leaves_task_references_intact() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("old-name", "/tmp/old").unwrap();
        let task = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "t".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();

        let renamed = s.rename_project(p.id, "new-name").unwrap();
        assert_eq!(renamed.id, p.id);
        assert_eq!(renamed.name, "new-name");

        // the task still resolves to the same project by id, under its new name
        let reloaded = s.task(task.id).unwrap();
        assert_eq!(reloaded.project_id, p.id);
        assert_eq!(s.project(reloaded.project_id).unwrap().name, "new-name");
    }

    #[test]
    fn project_viewer_defaults_to_none_and_round_trips() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("proj", "/tmp/proj").unwrap();
        assert_eq!(p.viewer, None);

        let updated = s.set_viewer(p.id, Some("zed")).unwrap();
        assert_eq!(updated.viewer.as_deref(), Some("zed"));
        assert_eq!(s.project(p.id).unwrap().viewer.as_deref(), Some("zed"));
        assert_eq!(s.projects().unwrap()[0].viewer.as_deref(), Some("zed"));

        // Naming no viewer writes NULL, so the column reads back empty
        s.set_viewer(p.id, None).unwrap();
        assert_eq!(s.project(p.id).unwrap().viewer, None);
        let raw: Option<String> = s
            .conn
            .query_row("SELECT viewer FROM projects WHERE id = ?1", [p.id], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(raw, None);

        // A blank name is a typo, not a way to clear the viewer
        assert!(matches!(
            s.set_viewer(p.id, Some("  ")),
            Err(Error::Invalid(_))
        ));
        assert!(matches!(
            s.set_viewer(999, Some("zed")),
            Err(Error::ProjectNotFound(999))
        ));
    }

    /// A database from before migration 0018 carries review actions in the
    /// pre-split spellings (DESIGN.md §5/§8). Opening it must keep the viewer a
    /// project named and read the three spellings that named none as none.
    #[test]
    fn migration_0018_reads_review_actions_as_viewer_names() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..17] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 17).unwrap();
        conn.execute(
            "INSERT INTO projects (name, review_action) VALUES
                 ('named', 'viewer:zed'),
                 ('bare-viewer', 'viewer'),
                 ('auto', 'auto'),
                 ('pinned-to-pr', 'pr'),
                 ('unset', NULL)",
            [],
        )
        .unwrap();

        let mut store = Store::from_connection(conn).unwrap();
        let viewer_of = |store: &mut Store, name: &str| {
            store
                .projects()
                .unwrap()
                .into_iter()
                .find(|p| p.name == name)
                .unwrap()
                .viewer
        };
        assert_eq!(viewer_of(&mut store, "named").as_deref(), Some("zed"));
        for named_none in ["bare-viewer", "auto", "pinned-to-pr", "unset"] {
            assert_eq!(viewer_of(&mut store, named_none), None, "{named_none}");
        }
    }

    #[test]
    fn rename_project_rejects_unknown_id() {
        let mut s = Store::open_in_memory().unwrap();
        assert!(matches!(
            s.rename_project(999, "x"),
            Err(Error::ProjectNotFound(999))
        ));
    }

    #[test]
    fn set_pr_tracks_clears_and_logs() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "review me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        assert!(s.task(t.id).unwrap().pr_url.is_none());

        let tracked = s
            .set_pr(t.id, Some("https://github.com/acme/widget/pull/42"))
            .unwrap();
        assert_eq!(
            tracked.pr_url.as_deref(),
            Some("https://github.com/acme/widget/pull/42")
        );
        // state is untouched by tracking a PR
        assert_eq!(tracked.state, TaskState::Ready);

        let cleared = s.set_pr(t.id, None).unwrap();
        assert!(cleared.pr_url.is_none());

        let events = s.events_for(t.id).unwrap();
        let kinds: Vec<&str> = events.iter().map(|e| e.kind.as_str()).collect();
        assert_eq!(kinds, vec!["created", "pr", "pr"]);
        assert!(matches!(s.set_pr(999, None), Err(Error::TaskNotFound(999))));
    }

    #[test]
    fn set_priority_updates_leaves_state_and_logs() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "reprioritise me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();

        let raised = s.set_priority(t.id, Priority::P0).unwrap();
        assert_eq!(raised.priority, Priority::P0);
        // priority is changed in isolation; state is untouched
        assert_eq!(raised.state, TaskState::Ready);

        let events = s.events_for(t.id).unwrap();
        let last = events.last().unwrap();
        assert_eq!(last.kind, "priority");
        assert_eq!(last.detail.as_deref(), Some("P0"));

        assert!(matches!(
            s.set_priority(999, Priority::P1),
            Err(Error::TaskNotFound(999))
        ));
    }

    #[test]
    fn set_branch_records_clears_and_logs() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "branch me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        assert!(s.task(t.id).unwrap().branch.is_none());

        let named = s.set_branch(t.id, Some("feat/parser")).unwrap();
        assert_eq!(named.branch.as_deref(), Some("feat/parser"));
        // recording a branch never touches task state
        assert_eq!(named.state, TaskState::Ready);

        // reporting a different branch overwrites the intended one
        let renamed = s.set_branch(t.id, Some("feat/parser-v2")).unwrap();
        assert_eq!(renamed.branch.as_deref(), Some("feat/parser-v2"));

        let cleared = s.set_branch(t.id, None).unwrap();
        assert!(cleared.branch.is_none());

        let events = s.events_for(t.id).unwrap();
        let kinds: Vec<&str> = events.iter().map(|e| e.kind.as_str()).collect();
        assert_eq!(kinds, vec!["created", "branch", "branch", "branch"]);
        assert!(matches!(
            s.set_branch(999, None),
            Err(Error::TaskNotFound(999))
        ));
    }

    // --- the human flag and the agent override are mutually exclusive (§3/§6) ---

    /// A store, a project, and a `NewTask` builder for the human-flag tests.
    fn human_fixture() -> (Store, i64) {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        (s, p.id)
    }

    fn new_with(project_id: i64, agent: Option<&str>, human: bool) -> NewTask {
        NewTask {
            project_id,
            repo_id: None,
            title: "hands-on".into(),
            body: String::new(),
            priority: Priority::P2,
            state: TaskState::Ready,
            agent: agent.map(str::to_string),
            human,
            deep: false,
        }
    }

    fn edit_of(task: &Task, agent: Option<&str>, human: bool) -> TaskEdit {
        TaskEdit {
            title: task.title.clone(),
            body: task.body.clone(),
            priority: task.priority,
            agent: agent.map(str::to_string),
            human,
            deep: false,
        }
    }

    #[test]
    fn create_task_refuses_a_human_task_with_an_agent_override() {
        let (mut s, p) = human_fixture();
        let err = s.create_task(new_with(p, Some("codex"), true)).unwrap_err();
        assert!(err.to_string().contains("agent override"), "{err}");
        assert!(s.tasks().unwrap().is_empty());

        assert!(s.create_task(new_with(p, Some("codex"), false)).is_ok());
        let human = s.create_task(new_with(p, None, true)).unwrap();
        assert!(human.human);
    }

    /// The body is the one field an edit overwrites wholesale, so the log keeps
    /// what each edit replaced (DESIGN.md §8) — and only that, since every `set`
    /// passes through here whether or not it touched the body.
    #[test]
    fn update_task_logs_the_body_it_replaced_and_nothing_else() {
        let (mut s, p) = human_fixture();
        let task = s.create_task(new_with(p, None, false)).unwrap();

        // an empty body destroys nothing on its way out
        let write = TaskEdit {
            body: "the brief".into(),
            ..edit_of(&task, None, false)
        };
        let task = s.update_task(task.id, write).unwrap();
        assert!(
            !s.events_for(task.id)
                .unwrap()
                .iter()
                .any(|e| e.kind == "body")
        );

        // an edit that leaves the body alone logs nothing either
        let retitle = TaskEdit {
            title: "renamed".into(),
            ..edit_of(&task, None, false)
        };
        let task = s.update_task(task.id, retitle).unwrap();
        assert!(
            !s.events_for(task.id)
                .unwrap()
                .iter()
                .any(|e| e.kind == "body")
        );

        let rewrite = TaskEdit {
            body: "a rewrite".into(),
            ..edit_of(&task, None, false)
        };
        let task = s.update_task(task.id, rewrite).unwrap();
        assert_eq!(task.body, "a rewrite");
        let logged: Vec<String> = s
            .events_for(task.id)
            .unwrap()
            .into_iter()
            .filter(|e| e.kind == "body")
            .map(|e| e.detail.unwrap_or_default())
            .collect();
        assert_eq!(logged, vec!["the brief".to_string()]);
    }

    #[test]
    fn update_task_guards_the_agent_human_exclusivity_both_ways() {
        let (mut s, p) = human_fixture();

        // an agent override cannot land on a human task
        let human = s.create_task(new_with(p, None, true)).unwrap();
        let err = s
            .update_task(human.id, edit_of(&human, Some("codex"), true))
            .unwrap_err();
        assert!(matches!(err, Error::HumanTask { id, .. } if id == human.id));

        // ...and the flag cannot land while an override is kept
        let agented = s.create_task(new_with(p, Some("codex"), false)).unwrap();
        let err = s
            .update_task(agented.id, edit_of(&agented, Some("codex"), true))
            .unwrap_err();
        assert!(matches!(err, Error::HumanTask { id, .. } if id == agented.id));

        // clearing the override in the same edit is the designed way through
        let flipped = s
            .update_task(agented.id, edit_of(&agented, None, true))
            .unwrap();
        assert!(flipped.human);
        assert!(flipped.agent.is_none());
    }

    #[test]
    fn update_task_refuses_flagging_human_in_agent_executed_states() {
        use crate::transition::Action;

        // needs-input, review, and stalled are unreachable for human tasks
        // (§6), so a task already sitting there cannot be flagged as one.
        for walk in [TaskState::NeedsInput, TaskState::Review, TaskState::Stalled] {
            let (mut s, p) = human_fixture();
            let t = s.create_task(new_with(p, None, false)).unwrap();
            match walk {
                TaskState::NeedsInput => {
                    s.apply(t.id, Action::Start).unwrap();
                    s.apply(t.id, Action::Ask("A or B?".into())).unwrap();
                }
                TaskState::Stalled => {
                    let (_, session) = s
                        .record_dispatch(t.id, "claude", Some(1), LivenessSource::Pid, None)
                        .unwrap();
                    s.reconcile_session(session.id, false, false).unwrap();
                }
                _ => {
                    s.apply(t.id, Action::Start).unwrap();
                    s.apply(t.id, Action::Complete(None)).unwrap();
                }
            }
            assert_eq!(s.task(t.id).unwrap().state, walk);
            let err = s.update_task(t.id, edit_of(&t, None, true)).unwrap_err();
            assert!(
                matches!(err, Error::HumanTask { id, .. } if id == t.id),
                "{walk}: {err}"
            );
            assert!(!s.task(t.id).unwrap().human);
        }
    }

    #[test]
    fn update_task_refuses_flagging_human_while_a_session_is_open() {
        use crate::transition::Action;

        let (mut s, p) = human_fixture();
        let t = s.create_task(new_with(p, None, false)).unwrap();
        s.record_dispatch(t.id, "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();

        let err = s.update_task(t.id, edit_of(&t, None, true)).unwrap_err();
        assert!(matches!(err, Error::HumanTask { id, .. } if id == t.id));

        // once the session is torn down the flip is allowed again
        s.apply(t.id, Action::Abort).unwrap();
        let flipped = s.update_task(t.id, edit_of(&t, None, true)).unwrap();
        assert!(flipped.human);

        // a hand-started running task has no session and can flip freely
        let by_hand = s.create_task(new_with(p, None, false)).unwrap();
        s.apply(by_hand.id, Action::Start).unwrap();
        assert!(
            s.update_task(by_hand.id, edit_of(&by_hand, None, true))
                .unwrap()
                .human
        );
    }

    // --- the deep flag ---

    fn deep_new(project_id: i64, human: bool, deep: bool) -> NewTask {
        NewTask {
            deep,
            ..new_with(project_id, None, human)
        }
    }

    #[test]
    fn set_deep_toggles_the_flag_and_logs_it() {
        let (mut s, p) = human_fixture();
        let t = s.create_task(deep_new(p, false, false)).unwrap();
        assert!(!t.deep);

        assert!(s.set_deep(t.id, true).unwrap().deep);
        assert!(!s.set_deep(t.id, false).unwrap().deep);

        let kinds: Vec<String> = s
            .events_for(t.id)
            .unwrap()
            .into_iter()
            .map(|e| e.kind)
            .collect();
        assert_eq!(kinds, vec!["created", "deep", "deep"]);
        assert!(matches!(
            s.set_deep(999, true),
            Err(Error::TaskNotFound(999))
        ));
    }

    /// Deep only selects a dispatch model, so it is refused on a task no agent
    /// can execute — through every door that can set it.
    #[test]
    fn a_human_task_cannot_be_deep() {
        let (mut s, p) = human_fixture();

        let err = s.create_task(deep_new(p, true, true)).unwrap_err();
        assert!(err.to_string().contains("deep"), "{err}");
        assert!(s.tasks().unwrap().is_empty());

        let human = s.create_task(deep_new(p, true, false)).unwrap();
        let err = s.set_deep(human.id, true).unwrap_err();
        assert!(matches!(err, Error::HumanTask { id, .. } if id == human.id));
        assert!(!s.task(human.id).unwrap().deep);

        let edit = TaskEdit {
            deep: true,
            ..edit_of(&human, None, true)
        };
        let err = s.update_task(human.id, edit).unwrap_err();
        assert!(matches!(err, Error::HumanTask { id, .. } if id == human.id));

        // clearing the flag on a human task is always allowed
        assert!(!s.set_deep(human.id, false).unwrap().deep);
    }

    /// A database from before migration 0013 must open with every existing
    /// task on the workhorse (`deep = 0`), and the CHECK must reject junk.
    #[test]
    fn deep_defaults_off_and_is_constrained() {
        let (mut s, p) = human_fixture();
        let t = s.create_task(deep_new(p, false, false)).unwrap();
        assert!(!t.deep);
        assert!(
            s.conn
                .execute("UPDATE tasks SET deep = 2 WHERE id = ?1", [t.id])
                .is_err()
        );
    }

    /// A database from before migration 0007 must open with every existing
    /// task dispatchable (`human = 0`), and the CHECK must reject junk.
    #[test]
    fn migration_0007_defaults_existing_tasks_to_dispatchable() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..6] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 6).unwrap();
        conn.execute("INSERT INTO projects (name, path) VALUES ('p', '/tmp')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'pre-flag', 'ready', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        assert!(!store.task(1).unwrap().human);

        let junk = store
            .conn
            .execute("UPDATE tasks SET human = 2 WHERE id = 1", []);
        assert!(junk.is_err(), "the CHECK must reject values outside 0/1");
    }

    #[test]
    fn set_summary_appends_a_superseding_summary_event() {
        use crate::transition::Action;

        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "summarise me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();

        // a running task may record its account before `done`
        s.apply(t.id, Action::Start).unwrap();
        let updated = s.set_summary(t.id, "  early account  ").unwrap();
        assert_eq!(updated.state, TaskState::Running);
        assert_eq!(
            s.latest_summary(t.id).unwrap().as_deref(),
            Some("early account")
        );

        // in review, a new summary supersedes the done-time one
        s.apply(t.id, Action::Complete(Some("done-time".into())))
            .unwrap();
        let updated = s.set_summary(t.id, "amended for the PR body").unwrap();
        assert_eq!(updated.state, TaskState::Review);
        assert_eq!(
            s.latest_summary(t.id).unwrap().as_deref(),
            Some("amended for the PR body")
        );

        // every account stays on the append-only log
        let events = s.events_for(t.id).unwrap();
        let summaries = events.iter().filter(|e| e.kind == "summary").count();
        assert_eq!(summaries, 3);
    }

    #[test]
    fn set_summary_clears_the_incomplete_report_flag() {
        use crate::transition::Action;

        // The SessionEnd-fallback shape: review with a branch and no summary.
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "half a report".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        s.apply(t.id, Action::Start).unwrap();
        s.apply(t.id, Action::Complete(None)).unwrap();
        s.set_branch(t.id, Some("feat/x")).unwrap();
        assert!(s.incomplete_report_flag(t.id).unwrap());

        s.set_summary(t.id, "the missing half").unwrap();
        assert!(!s.incomplete_report_flag(t.id).unwrap());
    }

    #[test]
    fn set_summary_is_refused_outside_running_and_review() {
        use crate::transition::Action;

        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "not yet".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        let err = s.set_summary(t.id, "too early").unwrap_err();
        assert!(err.to_string().contains("ready"), "{err}");

        s.apply(t.id, Action::Start).unwrap();
        s.apply(t.id, Action::Complete(None)).unwrap();
        s.apply(t.id, Action::Accept).unwrap();
        let err = s.set_summary(t.id, "too late").unwrap_err();
        assert!(err.to_string().contains("done"), "{err}");

        assert!(s.set_summary(t.id, "   ").is_err());
        assert!(matches!(
            s.set_summary(999, "x"),
            Err(Error::TaskNotFound(999))
        ));
    }

    // --- repos (DESIGN.md §3/§5) ---

    #[test]
    fn creating_a_project_creates_its_default_repo() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let repos = s.repos(p.id).unwrap();
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0].name, "voro");
        assert_eq!(repos[0].path, "/tmp/voro");
        assert!(repos[0].is_default);
        assert_eq!(s.default_repo(p.id).unwrap().id, repos[0].id);
    }

    #[test]
    fn added_repos_are_not_default_and_names_are_unique_per_project() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let oats = s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        assert!(!oats.is_default);
        assert!(s.add_repo(p.id, "oats", "/tmp/elsewhere").is_err());
        assert!(s.add_repo(p.id, "  ", "/tmp/blank").is_err());
        // The same repo name under a different project is fine.
        let other = s.create_project("voro", "/tmp/voro").unwrap();
        assert!(s.add_repo(other.id, "oats", "/tmp/oats").is_ok());
        // Default first, then by name.
        let names: Vec<_> = s.repos(p.id).unwrap().into_iter().map(|r| r.name).collect();
        assert_eq!(names, vec!["odm", "oats"]);
    }

    #[test]
    fn only_one_repo_is_ever_default() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let oats = s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        let promoted = s.set_default_repo(oats.id).unwrap();
        assert!(promoted.is_default);
        let defaults = s
            .repos(p.id)
            .unwrap()
            .into_iter()
            .filter(|r| r.is_default)
            .count();
        assert_eq!(defaults, 1);
        assert_eq!(s.default_repo(p.id).unwrap().name, "oats");
    }

    #[test]
    fn a_projects_last_repo_cannot_be_deleted() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let only = s.default_repo(p.id).unwrap();
        assert!(matches!(
            s.delete_repo(only.id),
            Err(Error::LastRepo { .. })
        ));
    }

    #[test]
    fn the_default_repo_cannot_be_deleted_while_others_remain() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let oats = s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        let default = s.default_repo(p.id).unwrap();
        assert!(matches!(
            s.delete_repo(default.id),
            Err(Error::DefaultRepo { .. })
        ));
        // Promoting the other one first clears the way.
        s.set_default_repo(oats.id).unwrap();
        s.delete_repo(default.id).unwrap();
        assert_eq!(s.repos(p.id).unwrap().len(), 1);
    }

    #[test]
    fn a_repo_a_task_names_cannot_be_deleted() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let oats = s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        let mut new = new_ready(p.id);
        new.repo_id = Some(oats.id);
        let t = s.create_task(new).unwrap();
        assert!(matches!(
            s.delete_repo(oats.id),
            Err(Error::RepoInUse { count: 1, .. })
        ));
        // Re-pointing the task at the default frees the repo.
        s.set_task_repo(t.id, None).unwrap();
        s.delete_repo(oats.id).unwrap();
    }

    #[test]
    fn a_task_resolves_its_own_repo_then_the_project_default() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let oats = s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        let plain = s.create_task(new_ready(p.id)).unwrap();
        assert_eq!(s.repo_for_task(&plain).unwrap().path, "/tmp/odm");

        let pointed = s.set_task_repo(plain.id, Some(oats.id)).unwrap();
        assert_eq!(pointed.repo_id, Some(oats.id));
        assert_eq!(s.repo_for_task(&pointed).unwrap().path, "/tmp/oats");

        // The fallback follows the default, not the original checkout.
        let back = s.set_task_repo(plain.id, None).unwrap();
        s.set_default_repo(oats.id).unwrap();
        assert_eq!(s.repo_for_task(&back).unwrap().path, "/tmp/oats");
    }

    #[test]
    fn a_task_cannot_name_another_projects_repo() {
        let mut s = Store::open_in_memory().unwrap();
        let odm = s.create_project("odm", "/tmp/odm").unwrap();
        let voro = s.create_project("voro", "/tmp/voro").unwrap();
        let foreign = s.default_repo(voro.id).unwrap();
        let mut new = new_ready(odm.id);
        new.repo_id = Some(foreign.id);
        assert!(s.create_task(new).is_err());

        let t = s.create_task(new_ready(odm.id)).unwrap();
        assert!(s.set_task_repo(t.id, Some(foreign.id)).is_err());
    }

    #[test]
    fn an_unknown_repo_name_errors_listing_the_projects_repos() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        let err = s.repo_by_name(p.id, "nope").unwrap_err().to_string();
        assert!(err.contains("odm"), "{err}");
        assert!(err.contains("oats"), "{err}");
    }

    #[test]
    fn deleting_a_project_takes_its_repos_with_it() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        s.add_repo(p.id, "oats", "/tmp/oats").unwrap();
        s.delete_project(p.id).unwrap();
        assert!(s.repos(p.id).unwrap().is_empty());
    }

    #[test]
    fn set_path_updates_the_default_repo() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("proj", "/tmp/old").unwrap();
        let updated = s.set_default_repo_path(p.id, "/tmp/new").unwrap();
        assert_eq!(updated.path, "/tmp/new");
        assert!(updated.is_default);
        assert_eq!(s.default_repo(p.id).unwrap().path, "/tmp/new");
    }

    #[test]
    fn set_path_rejects_unknown_id() {
        let mut s = Store::open_in_memory().unwrap();
        assert!(matches!(
            s.set_default_repo_path(999, "/tmp"),
            Err(Error::ProjectNotFound(999))
        ));
    }

    #[test]
    fn delete_project_removes_a_taskless_project() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("empty", "/tmp/empty").unwrap();
        s.delete_project(p.id).unwrap();
        assert!(matches!(s.project(p.id), Err(Error::ProjectNotFound(_))));
        assert!(s.projects().unwrap().is_empty());
    }

    #[test]
    fn delete_project_rejects_unknown_id() {
        let mut s = Store::open_in_memory().unwrap();
        assert!(matches!(
            s.delete_project(999),
            Err(Error::ProjectNotFound(999))
        ));
    }

    /// Walk a fresh task into `state` through the transition API, mirroring
    /// the equivalent helper in `transition.rs`'s own tests.
    fn task_in_state(s: &mut Store, project_id: i64, state: TaskState) -> i64 {
        use TaskState::*;
        let create = |s: &mut Store, state| {
            s.create_task(NewTask {
                project_id,
                repo_id: None,
                title: format!("task in {state}"),
                body: String::new(),
                priority: Priority::P1,
                state,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap()
            .id
        };
        match state {
            Proposed | Parked | Ready => create(s, state),
            Refining => {
                let id = create(s, Proposed);
                s.record_refine_launch(
                    id,
                    "thin body",
                    "claude",
                    Some(1),
                    LivenessSource::Pid,
                    None,
                )
                .unwrap();
                id
            }
            Running => {
                let id = create(s, Ready);
                s.apply(id, Action::Start).unwrap();
                id
            }
            NeedsInput => {
                let id = task_in_state(s, project_id, Running);
                s.apply(id, Action::Ask("which schema?".into())).unwrap();
                id
            }
            Review => {
                let id = task_in_state(s, project_id, Running);
                s.apply(id, Action::Complete(None)).unwrap();
                id
            }
            Waiting => {
                let id = task_in_state(s, project_id, Review);
                s.apply(id, Action::HandOff).unwrap();
                id
            }
            Stalled => {
                let id = create(s, Ready);
                let (_, session) = s
                    .record_dispatch(id, "claude", Some(1), LivenessSource::Pid, None)
                    .unwrap();
                s.reconcile_session(session.id, false, false).unwrap();
                id
            }
            Done => {
                let id = task_in_state(s, project_id, Review);
                s.apply(id, Action::Accept).unwrap();
                id
            }
            Rejected => {
                let id = create(s, Proposed);
                s.apply(id, Action::Triage(Triage::Reject)).unwrap();
                id
            }
        }
    }

    #[test]
    fn delete_project_refuses_with_a_task_in_any_state() {
        for state in TaskState::ALL {
            let mut s = Store::open_in_memory().unwrap();
            let p = s.create_project("proj", "/tmp/proj").unwrap();
            task_in_state(&mut s, p.id, state);

            let err = s.delete_project(p.id).unwrap_err();
            assert!(
                matches!(err, Error::ProjectHasTasks { id, count } if id == p.id && count == 1),
                "state {state}: expected ProjectHasTasks, got {err}"
            );
            // the refusal must not have touched the project
            assert!(s.project(p.id).is_ok());
        }
    }

    // --- archiving a project (DESIGN.md §5) ---

    #[test]
    fn set_archived_round_trips_and_refuses_noops() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("retiring", "/tmp/retiring").unwrap();
        assert!(!p.archived);

        let archived = s.set_archived(p.id, true).unwrap();
        assert!(archived.archived);
        assert!(s.projects().unwrap()[0].archived);

        // a second archive is heard, not absorbed
        let err = s.set_archived(p.id, true).unwrap_err();
        assert!(err.to_string().contains("already archived"), "{err}");

        let restored = s.set_archived(p.id, false).unwrap();
        assert!(!restored.archived);
        let err = s.set_archived(p.id, false).unwrap_err();
        assert!(err.to_string().contains("not archived"), "{err}");

        assert!(matches!(
            s.set_archived(999, true),
            Err(Error::ProjectNotFound(999))
        ));
    }

    #[test]
    fn create_task_refuses_an_archived_project() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("retired", "/tmp/retired").unwrap();
        s.set_archived(p.id, true).unwrap();

        // every creation door — add, propose, import — routes through here
        for state in [TaskState::Proposed, TaskState::Parked, TaskState::Ready] {
            let err = s
                .create_task(NewTask {
                    project_id: p.id,
                    repo_id: None,
                    title: "too late".into(),
                    body: String::new(),
                    priority: Priority::P2,
                    state,
                    agent: None,
                    human: false,
                    deep: false,
                })
                .unwrap_err();
            assert!(
                matches!(&err, Error::ProjectArchived { name } if name == "retired"),
                "{state}: {err}"
            );
        }
        assert!(s.tasks().unwrap().is_empty());

        s.set_archived(p.id, false).unwrap();
        assert!(
            s.create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "welcome back".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .is_ok()
        );
    }

    #[test]
    fn archive_freezes_task_states_and_history_and_unarchive_restores_them() {
        // Archiving transitions nothing: every task keeps its state, question,
        // and event log, so unarchiving restores the pre-archive view exactly.
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("retiring", "/tmp/retiring").unwrap();
        let tasks: Vec<i64> = TaskState::ALL
            .iter()
            .map(|state| task_in_state(&mut s, p.id, *state))
            .collect();
        let before: Vec<Task> = tasks.iter().map(|id| s.task(*id).unwrap()).collect();
        let events_before: Vec<usize> = tasks
            .iter()
            .map(|id| s.events_for(*id).unwrap().len())
            .collect();

        s.set_archived(p.id, true).unwrap();
        let frozen: Vec<Task> = tasks.iter().map(|id| s.task(*id).unwrap()).collect();
        assert_eq!(frozen, before);

        s.set_archived(p.id, false).unwrap();
        let after: Vec<Task> = tasks.iter().map(|id| s.task(*id).unwrap()).collect();
        assert_eq!(after, before);
        let events_after: Vec<usize> = tasks
            .iter()
            .map(|id| s.events_for(*id).unwrap().len())
            .collect();
        assert_eq!(events_after, events_before);
    }

    #[test]
    fn running_rows_exclude_archived_projects() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("retiring", "/tmp/retiring").unwrap();
        let id = task_in_state(&mut s, p.id, TaskState::Running);
        assert_eq!(s.running_rows().unwrap().len(), 1);

        // archiving hides the strip row; the task itself stays running
        s.set_archived(p.id, true).unwrap();
        assert!(s.running_rows().unwrap().is_empty());
        assert_eq!(s.task(id).unwrap().state, TaskState::Running);

        s.set_archived(p.id, false).unwrap();
        assert_eq!(s.running_rows().unwrap()[0].task_id, id);
    }

    /// A database from before migration 0011 must open with every existing
    /// project active (`archived = 0`), and the CHECK must reject junk.
    #[test]
    fn migration_0011_defaults_existing_projects_to_active() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..10] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 10).unwrap();
        conn.execute("INSERT INTO projects (name, path) VALUES ('p', '/tmp')", [])
            .unwrap();

        let store = Store::from_connection(conn).unwrap();
        assert!(!store.project(1).unwrap().archived);

        let junk = store
            .conn
            .execute("UPDATE projects SET archived = 2 WHERE id = 1", []);
        assert!(junk.is_err(), "the CHECK must reject values outside 0/1");
    }

    /// A database from before migration 0012 must convert in place: every
    /// project's old `path` reappears as its default repo, `projects.path` is
    /// gone, and existing tasks (all `repo_id` NULL) resolve to exactly the
    /// checkouts they had before (DESIGN.md §3/§5).
    #[test]
    fn migration_0012_turns_each_project_path_into_its_default_repo() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..11] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 11).unwrap();
        conn.execute(
            "INSERT INTO projects (name, path) VALUES ('odm', '/tmp/odm'), ('voro', '/tmp/voro')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'old', 'ready', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        for (id, name, path) in [(1, "odm", "/tmp/odm"), (2, "voro", "/tmp/voro")] {
            let repos = store.repos(id).unwrap();
            assert_eq!(repos.len(), 1);
            assert_eq!(repos[0].name, name);
            assert_eq!(repos[0].path, path);
            assert!(repos[0].is_default);
        }
        // The task kept its checkout without naming a repo.
        let task = store.task(1).unwrap();
        assert_eq!(task.repo_id, None);
        assert_eq!(store.repo_for_task(&task).unwrap().path, "/tmp/odm");

        // The column is gone, not merely unread.
        assert!(
            store
                .conn
                .query_row("SELECT path FROM projects WHERE id = 1", [], |r| r
                    .get::<_, String>(0))
                .is_err()
        );
        // The one-default invariant is schema-enforced from here on.
        assert!(
            store
                .conn
                .execute(
                    "INSERT INTO repos (project_id, name, path, is_default)
                     VALUES (1, 'second', '/tmp/second', 1)",
                    [],
                )
                .is_err()
        );
    }

    /// A database from before migration 0015 must open with every dependency
    /// edge intact, and accept a second edge of another kind between a pair the
    /// old primary key allowed only one edge for.
    #[test]
    fn migration_0015_widens_the_dep_key_without_losing_edges() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..14] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 14).unwrap();
        conn.execute("INSERT INTO projects (name) VALUES ('voro')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO repos (project_id, name, path, is_default)
             VALUES (1, 'voro', '/tmp/voro', 1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'source', 'ready', datetime('now'), datetime('now')),
                    (1, 'spawned', 'ready', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO deps (task_id, depends_on, kind) VALUES (2, 1, 'discovered-from')",
            [],
        )
        .unwrap();

        let mut store = Store::from_connection(conn).unwrap();
        let carried = store.deps_of(2).unwrap();
        assert_eq!(carried.len(), 1);
        assert_eq!(carried[0].kind, DepKind::DiscoveredFrom);

        store.set_blocks_deps(2, &[1]).unwrap();
        let kinds: Vec<DepKind> = store.deps_of(2).unwrap().iter().map(|d| d.kind).collect();
        assert_eq!(kinds, vec![DepKind::Blocks, DepKind::DiscoveredFrom]);
    }

    /// A database created at schema version 1 (state still named 'backlog')
    /// must convert on open: rows renamed, deps/events surviving the table
    /// rebuild, version stamped.
    #[test]
    fn migration_0002_converts_backlog_rows() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(MIGRATIONS[0]).unwrap();
        conn.pragma_update(None, "user_version", 1).unwrap();
        conn.execute("INSERT INTO projects (name, path) VALUES ('p', '/tmp')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'blocker', 'ready', datetime('now'), datetime('now')),
                    (1, 'waiting', 'backlog', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();
        conn.execute("INSERT INTO deps (task_id, depends_on) VALUES (2, 1)", [])
            .unwrap();
        conn.execute(
            "INSERT INTO events (task_id, at, kind, detail)
             VALUES (2, datetime('now'), 'created', 'backlog')",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        assert_eq!(store.task(2).unwrap().state, TaskState::Parked);
        assert_eq!(store.task(1).unwrap().state, TaskState::Ready);
        assert_eq!(store.deps_of(2).unwrap().len(), 1);
        // the event log is history and keeps its original wording
        assert_eq!(
            store.events_for(2).unwrap()[0].detail.as_deref(),
            Some("backlog")
        );
        let version: i64 = store
            .conn
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, MIGRATIONS.len() as i64);
        // 0004 gave the sessions table its session_ref column
        let refs: i64 = store
            .conn
            .query_row("SELECT COUNT(session_ref) FROM sessions", [], |r| r.get(0))
            .unwrap();
        assert_eq!(refs, 0);
    }

    /// Migration 0006 must dedupe a task that already carries several open
    /// sessions — keeping the newest open and closing the rest — before it can
    /// create the one-open-session index, and the index must then reject any
    /// further second open row.
    #[test]
    fn migration_0006_dedupes_open_sessions_and_enforces_the_index() {
        let conn = Connection::open_in_memory().unwrap();
        // apply 0001..=0005, i.e. everything before the invariant migration
        for sql in &MIGRATIONS[..5] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 5).unwrap();
        conn.execute("INSERT INTO projects (name, path) VALUES ('p', '/tmp')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'run me', 'running', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();
        // three open sessions on the one task — the exact duplicate state
        for _ in 0..3 {
            conn.execute(
                "INSERT INTO sessions (task_id, agent, started_at) VALUES (1, 'a', datetime('now'))",
                [],
            )
            .unwrap();
        }

        let store = Store::from_connection(conn).unwrap();
        // only the newest open session survives; the rest are closed `aborted`
        let open: Vec<i64> = store
            .sessions_for(1)
            .unwrap()
            .into_iter()
            .filter(|s| s.ended_at.is_none())
            .map(|s| s.id)
            .collect();
        assert_eq!(open, vec![3]);
        assert_eq!(
            store.session(1).unwrap().outcome,
            Some(SessionOutcome::Aborted)
        );
        // and the index now forbids a second open row
        let second = store.conn.execute(
            "INSERT INTO sessions (task_id, agent, started_at) VALUES (1, 'b', datetime('now'))",
            [],
        );
        assert!(second.is_err());
    }

    /// Migration 0008 must backfill exactly the tasks the derived redispatch
    /// flag used to mark — `ready` with a most recent session ended
    /// `failed`/`capped` — into `stalled`, leaving every other shape alone,
    /// and must carry 0007's `human` column through the table rebuild.
    #[test]
    fn migration_0008_backfills_flagged_ready_tasks_to_stalled() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..7] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 7).unwrap();
        conn.execute("INSERT INTO projects (name, path) VALUES ('p', '/tmp')", [])
            .unwrap();
        // 1: ready, last session failed          -> stalled
        // 2: ready, last session capped          -> stalled
        // 3: ready, last session aborted         -> stays ready
        // 4: ready, failed session then aborted  -> stays ready (latest wins)
        // 5: ready, no sessions                  -> stays ready
        // 6: running, last session failed        -> stays running
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 't1', 'ready', datetime('now'), datetime('now')),
                    (1, 't2', 'ready', datetime('now'), datetime('now')),
                    (1, 't3', 'ready', datetime('now'), datetime('now')),
                    (1, 't4', 'ready', datetime('now'), datetime('now')),
                    (1, 't5', 'ready', datetime('now'), datetime('now')),
                    (1, 't6', 'running', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO sessions (task_id, agent, started_at, ended_at, outcome)
             VALUES (1, 'a', datetime('now'), datetime('now'), 'failed'),
                    (2, 'a', datetime('now'), datetime('now'), 'capped'),
                    (3, 'a', datetime('now'), datetime('now'), 'aborted'),
                    (4, 'a', datetime('now'), datetime('now'), 'failed'),
                    (4, 'a', datetime('now'), datetime('now'), 'aborted'),
                    (6, 'a', datetime('now'), datetime('now'), 'failed')",
            [],
        )
        .unwrap();
        conn.execute("UPDATE tasks SET human = 1 WHERE id = 5", [])
            .unwrap();

        let store = Store::from_connection(conn).unwrap();
        assert_eq!(store.task(1).unwrap().state, TaskState::Stalled);
        assert_eq!(store.task(2).unwrap().state, TaskState::Stalled);
        assert_eq!(store.task(3).unwrap().state, TaskState::Ready);
        assert_eq!(store.task(4).unwrap().state, TaskState::Ready);
        assert_eq!(store.task(5).unwrap().state, TaskState::Ready);
        assert_eq!(store.task(6).unwrap().state, TaskState::Running);
        // the rebuild carries the human flag and its CHECK across
        assert!(store.task(5).unwrap().human);
        assert!(!store.task(1).unwrap().human);
        let junk = store
            .conn
            .execute("UPDATE tasks SET human = 2 WHERE id = 5", []);
        assert!(junk.is_err(), "the CHECK must reject values outside 0/1");
    }

    /// Migration 0010 must extend the state CHECK to admit 'waiting' while
    /// carrying every existing task through the table rebuild untouched.
    #[test]
    fn migration_0010_admits_waiting_and_preserves_existing_tasks() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..9] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 9).unwrap();
        conn.execute("INSERT INTO projects (name, path) VALUES ('p', '/tmp')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, agent, pr_url, branch, human,
                                state_since, created_at)
             VALUES (1, 'in review', 'review', 'claude', 'https://x/pull/1', 'feat/x', 1,
                     datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        // the pre-existing row survives the rebuild with every column intact
        let task = store.task(1).unwrap();
        assert_eq!(task.state, TaskState::Review);
        assert_eq!(task.pr_url.as_deref(), Some("https://x/pull/1"));
        assert_eq!(task.branch.as_deref(), Some("feat/x"));
        assert!(task.human);

        // the widened CHECK now admits 'waiting' and still rejects junk
        assert!(
            store
                .conn
                .execute("UPDATE tasks SET state = 'waiting' WHERE id = 1", [])
                .is_ok()
        );
        assert!(
            store
                .conn
                .execute("UPDATE tasks SET state = 'bogus' WHERE id = 1", [])
                .is_err()
        );

        let version: i64 = store
            .conn
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, MIGRATIONS.len() as i64);
    }

    /// A database from before migration 0016 must open with every existing task
    /// intact, and the widened CHECK must admit `refining` while still rejecting
    /// junk (DESIGN.md §6).
    #[test]
    fn migration_0016_admits_refining_and_preserves_existing_tasks() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..15] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 15).unwrap();
        conn.execute("INSERT INTO projects (name) VALUES ('voro')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO repos (project_id, name, path, is_default)
             VALUES (1, 'voro', '/tmp/voro', 1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, repo_id, title, state, agent, pr_url, branch,
                                human, deep, state_since, created_at)
             VALUES (1, 1, 'in review', 'review', 'claude', 'https://x/pull/1', 'feat/x', 1, 1,
                     datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        // the pre-existing row survives the rebuild with every column intact
        let task = store.task(1).unwrap();
        assert_eq!(task.state, TaskState::Review);
        assert_eq!(task.pr_url.as_deref(), Some("https://x/pull/1"));
        assert_eq!(task.branch.as_deref(), Some("feat/x"));
        assert_eq!(task.repo_id, Some(1));
        assert!(task.human);
        assert!(task.deep);

        assert!(
            store
                .conn
                .execute("UPDATE tasks SET state = 'refining' WHERE id = 1", [])
                .is_ok()
        );
        assert!(
            store
                .conn
                .execute("UPDATE tasks SET state = 'bogus' WHERE id = 1", [])
                .is_err()
        );

        let version: i64 = store
            .conn
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, MIGRATIONS.len() as i64);
    }

    /// A project + running task to hang sessions off of.
    fn task_fixture(s: &mut Store) -> i64 {
        s.conn
            .execute("INSERT OR IGNORE INTO projects (name) VALUES ('voro')", [])
            .unwrap();
        let project_id: i64 = s
            .conn
            .query_row("SELECT id FROM projects WHERE name = 'voro'", [], |r| {
                r.get(0)
            })
            .unwrap();
        s.conn
            .execute(
                "INSERT INTO tasks (project_id, title, state, state_since, created_at)
                 VALUES (?1, 'run me', 'running', datetime('now'), datetime('now'))",
                params![project_id],
            )
            .unwrap();
        s.conn.last_insert_rowid()
    }

    /// `events_for` must return the audit trail oldest-first (newest last),
    /// since that's the order the history popup renders it in.
    #[test]
    fn events_for_orders_oldest_first() {
        use crate::transition::Action;

        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let task = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "trace me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        s.apply(task.id, Action::Start).unwrap();
        s.apply(task.id, Action::Ask("A or B?".into())).unwrap();
        s.apply(task.id, Action::Resume).unwrap();

        let events = s.events_for(task.id).unwrap();
        let kinds: Vec<&str> = events.iter().map(|e| e.kind.as_str()).collect();
        assert_eq!(
            kinds,
            vec!["created", "transition", "transition", "transition"]
        );
        // ids strictly increase with insertion order
        assert!(events.windows(2).all(|w| w[0].id < w[1].id));
    }

    #[test]
    fn latest_summary_returns_the_newest_summary_event() {
        use crate::transition::Action;

        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "summary me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        assert_eq!(s.latest_summary(t.id).unwrap(), None);

        s.apply(t.id, Action::Start).unwrap();
        s.apply(t.id, Action::Complete(Some("first pass".into())))
            .unwrap();
        assert_eq!(
            s.latest_summary(t.id).unwrap().as_deref(),
            Some("first pass")
        );

        // a reject-then-redo records a second summary; the newest wins
        s.apply(t.id, Action::RejectWork("redo".into())).unwrap();
        s.apply(t.id, Action::Complete(Some("second pass".into())))
            .unwrap();
        assert_eq!(
            s.latest_summary(t.id).unwrap().as_deref(),
            Some("second pass")
        );
    }

    /// The reviewed revision is what delta re-review compares against
    /// (DESIGN.md §8): absent until the operator sends work back, superseded by
    /// each later rejection, and carried on the event log alone.
    #[test]
    fn last_reviewed_supersedes_and_starts_absent() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "review me".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        assert_eq!(s.last_reviewed(t.id).unwrap(), None);

        s.record_reviewed(t.id, "  aaaa1111  ").unwrap();
        assert_eq!(s.last_reviewed(t.id).unwrap().as_deref(), Some("aaaa1111"));
        s.record_reviewed(t.id, "bbbb2222").unwrap();
        assert_eq!(s.last_reviewed(t.id).unwrap().as_deref(), Some("bbbb2222"));

        assert!(s.record_reviewed(t.id, "   ").is_err());
        assert!(s.record_reviewed(999, "aaaa1111").is_err());
        // and it never touches task state
        assert_eq!(s.task(t.id).unwrap().state, TaskState::Ready);
    }

    #[test]
    fn incomplete_report_flag_marks_a_review_task_with_a_branch_and_no_summary() {
        use crate::transition::Action;

        // Helper: a fresh task carried to `review` with the given branch/summary.
        fn reviewed(branch: Option<&str>, summary: Option<&str>) -> (Store, i64) {
            let mut s = Store::open_in_memory().unwrap();
            let p = s.create_project("voro", "/tmp/voro").unwrap();
            let t = s
                .create_task(NewTask {
                    project_id: p.id,
                    repo_id: None,
                    title: "report me".into(),
                    body: String::new(),
                    priority: Priority::P2,
                    state: TaskState::Ready,
                    agent: None,
                    human: false,
                    deep: false,
                })
                .unwrap();
            s.apply(t.id, Action::Start).unwrap();
            s.apply(t.id, Action::Complete(summary.map(str::to_string)))
                .unwrap();
            if let Some(name) = branch {
                s.set_branch(t.id, Some(name)).unwrap();
            }
            (s, t.id)
        }

        // The still-anomalous half report: a branch but no summary — the classic
        // forgotten-summary flake and the shape the SessionEnd fallback leaves.
        let (s, id) = reviewed(Some("feat/x"), None);
        assert!(
            s.incomplete_report_flag(id).unwrap(),
            "half report: branch, no summary"
        );

        // The legitimate no-code report: a summary and no branch, as an
        // investigation, triage or audit ends. The summary is the deliverable,
        // so this is a complete report and must not be flagged.
        let (s, id) = reviewed(None, Some("already fixed by PR #96; nothing to do"));
        assert!(
            !s.incomplete_report_flag(id).unwrap(),
            "no-code report: summary, no branch"
        );

        // Both present — a complete report, not an anomaly.
        let (s, id) = reviewed(Some("feat/x"), Some("did the thing"));
        assert!(!s.incomplete_report_flag(id).unwrap());

        // Neither present — a legitimate no-artifact (e.g. planning) task.
        let (s, id) = reviewed(None, None);
        assert!(!s.incomplete_report_flag(id).unwrap());
    }

    #[test]
    fn incomplete_report_flag_is_gated_on_review() {
        use crate::transition::Action;

        // A partial report only counts once the task is in `review`: a running
        // task with an intended branch and no summary yet is mid-flight, not a
        // finished-but-incomplete report.
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let t = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "in flight".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        s.set_branch(t.id, Some("feat/x")).unwrap();
        assert!(!s.incomplete_report_flag(t.id).unwrap(), "ready");

        s.apply(t.id, Action::Start).unwrap();
        assert!(!s.incomplete_report_flag(t.id).unwrap(), "running");

        // Only on reaching review does the missing summary become an anomaly.
        s.apply(t.id, Action::Complete(None)).unwrap();
        assert!(s.incomplete_report_flag(t.id).unwrap(), "review");

        // Accepting past review clears it — no PR is opened from `done`.
        s.apply(t.id, Action::Accept).unwrap();
        assert!(!s.incomplete_report_flag(t.id).unwrap(), "done");
    }

    /// A proposal, its priority and deps recorded so a refine can be shown to
    /// leave both alone.
    fn proposal(s: &mut Store, title: &str) -> Task {
        let p = s.projects().unwrap().first().cloned().unwrap_or_else(|| {
            s.create_project("voro", "/tmp/voro").unwrap();
            s.projects().unwrap().remove(0)
        });
        s.create_task(NewTask {
            project_id: p.id,
            repo_id: None,
            title: title.into(),
            body: "thin body".into(),
            priority: Priority::P2,
            state: TaskState::Proposed,
            agent: None,
            human: false,
            deep: false,
        })
        .unwrap()
    }

    /// A refine round launch (DESIGN.md §6): the note rides the transition, the
    /// task leaves the triage queue for `refining`, and everything else about
    /// it — priority, deps, the body being rewritten — is untouched.
    #[test]
    fn record_refine_launch_moves_the_task_and_logs_the_note() {
        let mut s = Store::open_in_memory().unwrap();
        let blocker = proposal(&mut s, "blocker");
        let t = proposal(&mut s, "refine me");
        s.add_dep(t.id, blocker.id, DepKind::Blocks).unwrap();
        let before = s.task(t.id).unwrap();

        let (after, session) = s
            .record_refine_launch(
                t.id,
                "  name the files it touches  ",
                "claude",
                Some(4321),
                LivenessSource::Pid,
                Some("/var/log/refine.log"),
            )
            .unwrap();

        assert_eq!(after.state, TaskState::Refining);
        assert_eq!(after.priority, before.priority);
        assert_eq!(after.body, before.body);
        assert_eq!(s.deps_of(t.id).unwrap().len(), 1);
        assert_eq!(session.pid, Some(4321));
        assert_eq!(session.log_path.as_deref(), Some("/var/log/refine.log"));
        assert!(session.ended_at.is_none());
        assert_eq!(
            s.latest_refine_note(t.id).unwrap().as_deref(),
            Some("name the files it touches")
        );
        // Neither marker shows while the round is in flight — there is nothing
        // to say about a rewrite that has not happened yet.
        assert!(!s.refined_flag(t.id).unwrap());
        assert!(!s.refine_failed_flag(t.id).unwrap());
    }

    /// The interactive flavour carries no note, so nothing is logged for one —
    /// the brief is the conversation itself.
    #[test]
    fn a_note_less_refine_launch_logs_no_note() {
        let mut s = Store::open_in_memory().unwrap();
        let t = proposal(&mut s, "refine me");
        s.record_refine_launch(t.id, "", "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();
        assert_eq!(s.latest_refine_note(t.id).unwrap(), None);
        assert_eq!(s.task(t.id).unwrap().state, TaskState::Refining);
    }

    /// Each conclusion picks the marker the returned proposal carries, and the
    /// newest round wins — a failed round after a successful one says so.
    #[test]
    fn the_markers_read_the_round_that_just_concluded() {
        use crate::transition::{Action, Triage};

        let mut s = Store::open_in_memory().unwrap();
        let t = proposal(&mut s, "refine me");

        for (outcome, refined, failed) in [
            (RefineOutcome::Applied, true, false),
            (RefineOutcome::Failed, false, true),
            (RefineOutcome::Cancelled, false, false),
            (RefineOutcome::Applied, true, false),
        ] {
            s.record_refine_launch(t.id, "note", "claude", Some(1), LivenessSource::Pid, None)
                .unwrap();
            let after = s.conclude_refine(t.id, outcome).unwrap();
            assert_eq!(after.state, TaskState::Proposed, "{outcome}");
            assert_eq!(s.refined_flag(t.id).unwrap(), refined, "{outcome}");
            assert_eq!(s.refine_failed_flag(t.id).unwrap(), failed, "{outcome}");
            assert_eq!(s.latest_refine_outcome(t.id).unwrap(), Some(outcome));
        }

        // Triage is what clears the markers — both are gated on `proposed`.
        s.apply(t.id, Action::Triage(Triage::Parked)).unwrap();
        assert!(!s.refined_flag(t.id).unwrap());
        assert!(!s.refine_failed_flag(t.id).unwrap());
    }

    /// The late-rewrite backstop (DESIGN.md §6): a round concluded `failed`
    /// whose rewrite lands afterwards has its outcome corrected to applied, so
    /// the improved body is not read under a marker saying no rewrite happened.
    #[test]
    fn a_late_rewrite_corrects_a_failed_round_to_applied() {
        let mut s = Store::open_in_memory().unwrap();
        let t = proposal(&mut s, "refine me");
        s.record_refine_launch(t.id, "note", "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();
        s.conclude_refine(t.id, RefineOutcome::Failed).unwrap();
        assert!(s.refine_failed_flag(t.id).unwrap());

        assert!(s.correct_late_refine(t.id).unwrap());
        assert!(s.refined_flag(t.id).unwrap());
        assert!(!s.refine_failed_flag(t.id).unwrap());
        assert_eq!(
            s.latest_refine_outcome(t.id).unwrap(),
            Some(RefineOutcome::Applied)
        );
        // A correction transitions nothing and reopens nothing.
        assert_eq!(s.task(t.id).unwrap().state, TaskState::Proposed);
        assert_eq!(
            s.sessions_for(t.id).unwrap()[0].outcome,
            Some(SessionOutcome::Failed),
            "the session keeps the outcome the reconciler observed"
        );
        // Idempotent: the correction is itself the newest outcome.
        assert!(!s.correct_late_refine(t.id).unwrap());
    }

    /// The correction is confined to the one case it exists for: any other last
    /// outcome, and any state but `proposed`, is left alone.
    #[test]
    fn correcting_a_round_is_a_no_op_off_the_failed_case() {
        use crate::transition::{Action, Triage};

        for outcome in [RefineOutcome::Applied, RefineOutcome::Cancelled] {
            let mut s = Store::open_in_memory().unwrap();
            let t = proposal(&mut s, "refine me");
            s.record_refine_launch(t.id, "note", "claude", Some(1), LivenessSource::Pid, None)
                .unwrap();
            s.conclude_refine(t.id, outcome).unwrap();

            assert!(!s.correct_late_refine(t.id).unwrap(), "{outcome}");
            assert_eq!(s.latest_refine_outcome(t.id).unwrap(), Some(outcome));
        }

        // A task nobody ever refined, and a failed round already triaged away.
        let mut s = Store::open_in_memory().unwrap();
        let t = proposal(&mut s, "never refined");
        assert!(!s.correct_late_refine(t.id).unwrap());
        assert_eq!(s.latest_refine_outcome(t.id).unwrap(), None);

        s.record_refine_launch(t.id, "note", "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();
        s.conclude_refine(t.id, RefineOutcome::Failed).unwrap();
        s.apply(t.id, Action::Triage(Triage::Ready)).unwrap();
        assert!(!s.correct_late_refine(t.id).unwrap());
        assert_eq!(
            s.latest_refine_outcome(t.id).unwrap(),
            Some(RefineOutcome::Failed)
        );
    }

    /// A concluded round closes its session with the matching outcome, whichever
    /// trigger fired (DESIGN.md §6/§8).
    #[test]
    fn concluding_a_round_closes_its_session_with_the_matching_outcome() {
        for (outcome, session_outcome) in [
            (RefineOutcome::Applied, SessionOutcome::Completed),
            (RefineOutcome::Failed, SessionOutcome::Failed),
            (RefineOutcome::Cancelled, SessionOutcome::Aborted),
        ] {
            let mut s = Store::open_in_memory().unwrap();
            let t = proposal(&mut s, "refine me");
            let (_, session) = s
                .record_refine_launch(t.id, "note", "claude", Some(1), LivenessSource::Pid, None)
                .unwrap();

            s.conclude_refine(t.id, outcome).unwrap();
            let closed = s.session(session.id).unwrap();
            assert!(closed.ended_at.is_some(), "{outcome}");
            assert_eq!(closed.outcome, Some(session_outcome), "{outcome}");
        }
    }

    /// The round's guard rails: a task past `proposed`/`ready` cannot start
    /// one, and one that is not `refining` cannot conclude one.
    #[test]
    fn refine_transitions_are_refused_from_the_wrong_state() {
        use crate::transition::{Action, Triage};

        let mut s = Store::open_in_memory().unwrap();
        let t = proposal(&mut s, "refine me");
        assert!(matches!(
            s.conclude_refine(t.id, RefineOutcome::Applied),
            Err(Error::InvalidTransition { .. })
        ));

        s.apply(t.id, Action::Triage(Triage::Parked)).unwrap();
        assert!(matches!(
            s.record_refine_launch(t.id, "too late", "claude", None, LivenessSource::Pid, None),
            Err(Error::InvalidTransition { .. })
        ));
        // The refused launch wrote nothing — no session, no state change.
        assert_eq!(s.task(t.id).unwrap().state, TaskState::Parked);
        assert!(s.sessions_for(t.id).unwrap().is_empty());
    }

    #[test]
    fn discovered_from_resolves_the_parent_proposal() {
        let mut s = Store::open_in_memory().unwrap();
        let parent = proposal(&mut s, "parent");
        let child = proposal(&mut s, "child");
        assert!(s.discovered_from(child.id).unwrap().is_none());

        s.add_dep(child.id, parent.id, DepKind::DiscoveredFrom)
            .unwrap();
        assert_eq!(
            s.discovered_from(child.id).unwrap().map(|t| t.id),
            Some(parent.id)
        );
        // A plain blocker is not a parent: only `discovered-from` carries the
        // context a proposal was written against.
        let blocker = proposal(&mut s, "blocker");
        assert!(s.discovered_from(blocker.id).unwrap().is_none());
    }

    #[test]
    fn incomplete_report_flag_is_false_for_a_missing_task() {
        let s = Store::open_in_memory().unwrap();
        assert!(!s.incomplete_report_flag(999).unwrap());
    }

    #[test]
    fn session_create_end_round_trip() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);

        let opened = s
            .create_session(
                task_id,
                "claude",
                Some(4321),
                LivenessSource::Pid,
                Some("/var/log/s.log"),
            )
            .unwrap();
        assert_eq!(opened.task_id, task_id);
        assert_eq!(opened.agent, "claude");
        assert_eq!(opened.pid, Some(4321));
        assert_eq!(opened.log_path.as_deref(), Some("/var/log/s.log"));
        assert!(!opened.started_at.is_empty());
        assert!(opened.ended_at.is_none());
        assert!(opened.outcome.is_none());

        let ended = s.end_session(opened.id, SessionOutcome::Completed).unwrap();
        assert_eq!(ended.id, opened.id);
        assert!(ended.ended_at.is_some());
        assert_eq!(ended.outcome, Some(SessionOutcome::Completed));

        assert_eq!(s.session(opened.id).unwrap(), ended);
    }

    /// `latest_sessions` maps each task to its newest session only, and tasks
    /// with no session history stay absent.
    #[test]
    fn latest_sessions_keeps_only_the_newest_per_task() {
        let mut s = Store::open_in_memory().unwrap();
        let with_history = task_fixture(&mut s);
        let sessionless = task_fixture(&mut s);

        let first = s
            .create_session(
                with_history,
                "claude",
                None,
                LivenessSource::Pid,
                Some("/var/log/first.log"),
            )
            .unwrap();
        s.end_session(first.id, SessionOutcome::Failed).unwrap();
        let second = s
            .create_session(
                with_history,
                "codex",
                None,
                LivenessSource::Pid,
                Some("/var/log/second.log"),
            )
            .unwrap();

        let latest = s.latest_sessions().unwrap();
        assert_eq!(latest.len(), 1);
        assert_eq!(latest[&with_history].id, second.id);
        assert_eq!(
            latest[&with_history].log_path.as_deref(),
            Some("/var/log/second.log")
        );
        assert!(!latest.contains_key(&sessionless));
    }

    #[test]
    fn session_optional_fields_are_null() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let opened = s
            .create_session(task_id, "codex", None, LivenessSource::Pid, None)
            .unwrap();
        assert!(opened.pid.is_none());
        assert!(opened.session_ref.is_none());
        assert!(opened.log_path.is_none());
    }

    #[test]
    fn set_session_ref_records_and_rejects_unknown_ids() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let opened = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        assert!(opened.session_ref.is_none());

        let updated = s
            .set_session_ref(opened.id, "3f6c0e6e-1111-2222-3333-444455556666")
            .unwrap();
        assert_eq!(
            updated.session_ref.as_deref(),
            Some("3f6c0e6e-1111-2222-3333-444455556666")
        );
        assert_eq!(s.session(opened.id).unwrap(), updated);

        assert!(matches!(
            s.set_session_ref(999, "x"),
            Err(Error::SessionNotFound(999))
        ));
    }

    /// Each launch records which source reconciliation must read it by
    /// (DESIGN.md §8), and it survives the round trip: a headless
    /// launch under a supervisor is listing-authoritative, an interactive round
    /// is not, and neither is inferred from anything else on the row.
    #[test]
    fn a_session_records_the_liveness_source_it_was_launched_with() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let listing = s
            .create_session(task_id, "claude", Some(1), LivenessSource::Listing, None)
            .unwrap();
        assert_eq!(listing.liveness_source, LivenessSource::Listing);
        assert_eq!(
            s.session(listing.id).unwrap().liveness_source,
            LivenessSource::Listing
        );

        let pid = s
            .create_session(task_id, "manual", Some(1), LivenessSource::Pid, None)
            .unwrap();
        assert_eq!(pid.liveness_source, LivenessSource::Pid);
        assert_eq!(
            s.live_sessions().unwrap()[0].liveness_source,
            pid.liveness_source
        );

        // A ref captured later says nothing about the source: that was decided
        // at launch, which is the whole point of recording it.
        s.set_session_ref(pid.id, "uuid").unwrap();
        assert_eq!(
            s.session(pid.id).unwrap().liveness_source,
            LivenessSource::Pid
        );
    }

    /// The dispatch and refine transactions carry the flavour through to the
    /// row they open, so the reconciler reads what the launcher spawned.
    #[test]
    fn dispatch_and_refine_launches_carry_their_liveness_source() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("proj", "/tmp/proj").unwrap();
        let ready = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "run me".into(),
                body: String::new(),
                priority: Priority::P1,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        let (_, dispatched) = s
            .record_dispatch(ready.id, "claude", Some(1), LivenessSource::Listing, None)
            .unwrap();
        assert_eq!(dispatched.liveness_source, LivenessSource::Listing);

        let proposal = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "sloppy".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Proposed,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap();
        let (_, headless) = s
            .record_refine_launch(
                proposal.id,
                "name the files",
                "claude",
                Some(2),
                LivenessSource::Listing,
                None,
            )
            .unwrap();
        assert_eq!(headless.liveness_source, LivenessSource::Listing);

        s.conclude_refine(proposal.id, RefineOutcome::Cancelled)
            .unwrap();
        let (_, interactive) = s
            .record_refine_launch(
                proposal.id,
                "",
                "claude",
                Some(3),
                LivenessSource::Pid,
                None,
            )
            .unwrap();
        assert_eq!(interactive.liveness_source, LivenessSource::Pid);
    }

    /// A database from before migration 0017 must open with every existing
    /// session listing-authoritative — what a dispatch of an agent with a
    /// `sessions` verb already was, and the direction that leaves a session
    /// alone rather than finalising a live one — and the CHECK must reject a
    /// source that is neither.
    #[test]
    fn migration_0017_defaults_existing_sessions_to_the_listing() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..16] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 16).unwrap();
        conn.execute("INSERT INTO projects (name) VALUES ('p')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO repos (project_id, name, path, is_default)
             VALUES (1, 'p', '/tmp/p', 1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'dispatched', 'running', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO sessions (task_id, agent, pid, started_at)
             VALUES (1, 'claude', 4242, datetime('now'))",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        assert_eq!(
            store.session(1).unwrap().liveness_source,
            LivenessSource::Listing
        );

        let junk = store.conn.execute(
            "UPDATE sessions SET liveness_source = 'guess' WHERE id = 1",
            [],
        );
        assert!(junk.is_err(), "the CHECK must reject an unknown source");
    }

    /// A confirmed send moves the session's process to the one carrying the
    /// turn, and follows the fork when the agent opened a new reference — but a
    /// send that resumed in place must not blank the reference it already had.
    #[test]
    fn record_session_send_moves_the_pid_and_follows_a_fork() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let opened = s
            .create_session(task_id, "claude", Some(1234), LivenessSource::Pid, None)
            .unwrap();
        s.set_session_ref(opened.id, "first-ref").unwrap();

        let resumed = s.record_session_send(opened.id, None, 4321).unwrap();
        assert_eq!(resumed.pid, Some(4321));
        assert_eq!(resumed.session_ref.as_deref(), Some("first-ref"));

        let forked = s
            .record_session_send(opened.id, Some("forked-ref"), 5678)
            .unwrap();
        assert_eq!(forked.pid, Some(5678));
        assert_eq!(forked.session_ref.as_deref(), Some("forked-ref"));
        assert_eq!(s.session(opened.id).unwrap(), forked);

        assert!(matches!(
            s.record_session_send(999, None, 1),
            Err(Error::SessionNotFound(999))
        ));
    }

    #[test]
    fn end_session_rejects_unknown_id() {
        let mut s = Store::open_in_memory().unwrap();
        assert!(matches!(
            s.end_session(999, SessionOutcome::Aborted),
            Err(Error::SessionNotFound(999))
        ));
    }

    #[test]
    fn sessions_for_returns_newest_first() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let first = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        let second = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();

        let sessions = s.sessions_for(task_id).unwrap();
        assert_eq!(
            sessions.iter().map(|s| s.id).collect::<Vec<_>>(),
            vec![second.id, first.id]
        );
    }

    #[test]
    fn live_sessions_excludes_ended() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let done = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        let live = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        s.end_session(done.id, SessionOutcome::Failed).unwrap();

        let ids = s.live_sessions().unwrap();
        assert_eq!(ids.iter().map(|s| s.id).collect::<Vec<_>>(), vec![live.id]);
    }

    #[test]
    fn running_rows_join_current_task_fields() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let session = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].session_id, Some(session.id));
        assert_eq!(rows[0].task_id, task_id);
        assert_eq!(rows[0].task_title, "run me");
        assert_eq!(rows[0].task_state, TaskState::Running);
        assert_eq!(rows[0].agent.as_deref(), Some("claude"));
        assert!(rows[0].elapsed_secs >= 0);
    }

    #[test]
    fn running_rows_exclude_ended_sessions_and_order_newest_first() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let done = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        let live = s
            .create_session(task_id, "codex", None, LivenessSource::Pid, None)
            .unwrap();
        s.end_session(done.id, SessionOutcome::Completed).unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(
            rows.iter().map(|r| r.session_id).collect::<Vec<_>>(),
            vec![Some(live.id)]
        );
        assert_eq!(rows[0].agent.as_deref(), Some("codex"));
    }

    #[test]
    fn running_rows_compute_elapsed_from_started_at() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let session = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        s.conn
            .execute(
                "UPDATE sessions SET started_at = datetime('now', '-90 seconds') WHERE id = ?1",
                params![session.id],
            )
            .unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        // allow a couple of seconds of test-execution slack either side
        assert!(
            (85..=95).contains(&rows[0].elapsed_secs),
            "expected ~90s elapsed, got {}",
            rows[0].elapsed_secs
        );
    }

    /// A task can be `running` with no live session — started by hand, so no
    /// session was ever opened. The running strip must still surface it
    /// (DESIGN.md §9), with no session id or agent and elapsed measured from
    /// when it entered `running`.
    #[test]
    fn running_rows_include_running_task_without_live_session() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        s.conn
            .execute(
                "UPDATE tasks SET state_since = datetime('now', '-90 seconds') WHERE id = ?1",
                params![task_id],
            )
            .unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].session_id, None);
        assert_eq!(rows[0].agent, None);
        assert_eq!(rows[0].task_id, task_id);
        assert_eq!(rows[0].task_state, TaskState::Running);
        assert!(
            (85..=95).contains(&rows[0].elapsed_secs),
            "expected ~90s in running, got {}",
            rows[0].elapsed_secs
        );
    }

    /// A running task whose only session has ended is session-less too, so it
    /// stays visible rather than dropping off the strip.
    #[test]
    fn running_rows_include_task_whose_sessions_all_ended() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        let done = s
            .create_session(task_id, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        s.end_session(done.id, SessionOutcome::Failed).unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].session_id, None);
        assert_eq!(rows[0].task_id, task_id);
    }

    /// Live sessions sort ahead of session-less running tasks, so what an agent
    /// is actively driving stays at the top of the strip.
    #[test]
    fn running_rows_order_live_sessions_before_session_less_tasks() {
        let mut s = Store::open_in_memory().unwrap();
        let live_task = task_fixture(&mut s);
        let session = s
            .create_session(live_task, "claude", None, LivenessSource::Pid, None)
            .unwrap();
        let orphan_task = task_fixture(&mut s);

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].session_id, Some(session.id));
        assert_eq!(rows[0].task_id, live_task);
        assert_eq!(rows[1].session_id, None);
        assert_eq!(rows[1].task_id, orphan_task);
    }

    /// A refine round is work under way, so it rides the strip beside dispatched
    /// tasks — with the round's session and the elapsed time since it opened —
    /// and leaves it the moment the round concludes (DESIGN.md §6/§9).
    #[test]
    fn running_rows_include_a_refining_task() {
        let mut s = Store::open_in_memory().unwrap();
        let t = proposal(&mut s, "refine me");
        let (_, session) = s
            .record_refine_launch(
                t.id,
                "thin body",
                "claude",
                Some(1),
                LivenessSource::Pid,
                None,
            )
            .unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].task_id, t.id);
        assert_eq!(rows[0].task_state, TaskState::Refining);
        assert_eq!(rows[0].session_id, Some(session.id));
        assert_eq!(rows[0].agent.as_deref(), Some("claude"));

        s.conclude_refine(t.id, RefineOutcome::Applied).unwrap();
        assert!(s.running_rows().unwrap().is_empty());
    }

    /// A hand-off is work in flight someone else owns, so it rides the strip
    /// too (DESIGN.md §9) — but its elapsed counts from the hand-off rather
    /// than from the session, which opened when the agent started the work and
    /// says nothing about how long the PR has been sitting there.
    #[test]
    fn running_rows_measure_a_waiting_task_from_the_hand_off() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let id = s
            .create_task(NewTask {
                project_id: p.id,
                repo_id: None,
                title: "handed off".into(),
                body: String::new(),
                priority: Priority::P2,
                state: TaskState::Ready,
                agent: None,
                human: false,
                deep: false,
            })
            .unwrap()
            .id;
        let (_, opened) = s
            .record_dispatch(id, "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();
        s.apply(id, Action::Complete(None)).unwrap();
        s.apply(id, Action::HandOff).unwrap();
        s.set_pr(id, Some("https://github.com/o/r/pull/7")).unwrap();
        let session = opened.id;
        s.conn
            .execute(
                "UPDATE sessions SET started_at = datetime('now', '-2 hours') WHERE id = ?1",
                params![session],
            )
            .unwrap();
        s.conn
            .execute(
                "UPDATE tasks SET state_since = datetime('now', '-90 seconds') WHERE id = ?1",
                params![id],
            )
            .unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].task_id, id);
        assert_eq!(rows[0].task_state, TaskState::Waiting);
        assert_eq!(rows[0].session_id, Some(session));
        assert_eq!(
            rows[0].pr_url.as_deref(),
            Some("https://github.com/o/r/pull/7")
        );
        assert!(
            (85..=95).contains(&rows[0].elapsed_secs),
            "expected ~90s waiting, got {} (the session's own age is 2h)",
            rows[0].elapsed_secs
        );
    }

    /// Work an agent is driving sorts ahead of the hand-offs, which are the
    /// rows nobody is typing into.
    #[test]
    fn running_rows_sort_waiting_after_work_under_way() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let waiting = task_in_state(&mut s, p.id, TaskState::Waiting);
        let running = task_in_state(&mut s, p.id, TaskState::Running);
        let refining = task_in_state(&mut s, p.id, TaskState::Refining);

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 3);
        assert_eq!(rows.last().unwrap().task_id, waiting);
        let ahead: Vec<i64> = rows[..2].iter().map(|r| r.task_id).collect();
        assert!(
            ahead.contains(&running) && ahead.contains(&refining),
            "{ahead:?}"
        );
    }

    /// Archiving retires the whole project from the cockpit (DESIGN.md §5), and
    /// the strip's newest row kind is no exception.
    #[test]
    fn running_rows_exclude_a_waiting_task_in_an_archived_project() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("retiring", "/tmp/retiring").unwrap();
        let id = task_in_state(&mut s, p.id, TaskState::Waiting);
        assert_eq!(s.running_rows().unwrap().len(), 1);

        s.set_archived(p.id, true).unwrap();
        assert!(s.running_rows().unwrap().is_empty());
        assert_eq!(s.task(id).unwrap().state, TaskState::Waiting);
    }

    /// The strip filters on task state: a task that has left `running` —
    /// review, done, rejected — never renders, even a `review` task whose
    /// session is deliberately still open (DESIGN.md §8/§9).
    #[test]
    fn running_rows_exclude_tasks_that_left_running() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let new = |title: &str| NewTask {
            project_id: p.id,
            repo_id: None,
            title: title.into(),
            body: String::new(),
            priority: Priority::P2,
            state: TaskState::Ready,
            agent: None,
            human: false,
            deep: false,
        };

        // review keeps its session open, yet must not appear in the strip
        let review = s.create_task(new("review")).unwrap().id;
        s.record_dispatch(review, "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();
        s.apply(review, Action::Complete(None)).unwrap();
        assert!(s.sessions_for(review).unwrap()[0].ended_at.is_none());

        // done and rejected have their sessions closed by the transition
        let done = s.create_task(new("done")).unwrap().id;
        s.record_dispatch(done, "claude", Some(2), LivenessSource::Pid, None)
            .unwrap();
        s.apply(done, Action::Complete(None)).unwrap();
        s.apply(done, Action::Accept).unwrap();

        let rejected = s.create_task(new("rejected")).unwrap().id;
        s.record_dispatch(rejected, "claude", Some(3), LivenessSource::Pid, None)
            .unwrap();
        s.apply(rejected, Action::Abort).unwrap();
        s.apply(rejected, Action::Abandon).unwrap();

        let running = s.create_task(new("running")).unwrap().id;
        s.record_dispatch(running, "claude", Some(4), LivenessSource::Pid, None)
            .unwrap();

        let rows = s.running_rows().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].task_id, running);
    }

    /// A `done` task left carrying an open session must stay out of the strip
    /// purely on its state.
    #[test]
    fn running_rows_ignore_a_stale_open_session_on_a_closed_task() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        s.create_session(task_id, "claude", Some(1), LivenessSource::Pid, None)
            .unwrap();
        s.conn
            .execute("UPDATE tasks SET state = 'done' WHERE id = ?1", [task_id])
            .unwrap();
        assert!(s.running_rows().unwrap().is_empty());
    }

    #[test]
    fn session_outcome_serialises_for_all_variants() {
        let mut s = Store::open_in_memory().unwrap();
        let task_id = task_fixture(&mut s);
        for outcome in SessionOutcome::ALL {
            let opened = s
                .create_session(task_id, "claude", None, LivenessSource::Pid, None)
                .unwrap();
            let ended = s.end_session(opened.id, outcome).unwrap();
            assert_eq!(ended.outcome, Some(outcome));
        }
    }

    /// A unique scratch database path under the OS temp dir.
    fn scratch_db() -> PathBuf {
        tempfile::Builder::new()
            .prefix("voro-dataversion-")
            .tempdir()
            .unwrap()
            .keep()
            .join("voro.db")
    }

    #[test]
    fn data_version_tracks_external_commits_only() {
        let path = scratch_db();
        let mut a = Store::open(&path).unwrap();
        let mut b = Store::open(&path).unwrap();

        let start = a.data_version().unwrap();

        // Our own writes must not move the version this connection observes.
        a.create_project("alpha", "/tmp/alpha").unwrap();
        assert_eq!(a.data_version().unwrap(), start);

        // A commit from another connection must move it.
        b.create_project("beta", "/tmp/beta").unwrap();
        assert_ne!(a.data_version().unwrap(), start);

        drop(a);
        drop(b);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn dep_maps_resolve_both_directions_with_title_state_and_kind() {
        use crate::model::{DepKind, DepRef, Priority};
        use crate::transition::Action;

        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let new = |title: &str| NewTask {
            project_id: p.id,
            repo_id: None,
            title: title.into(),
            body: String::new(),
            priority: Priority::P2,
            state: TaskState::Ready,
            agent: None,
            human: false,
            deep: false,
        };
        let blocker = s.create_task(new("blocker")).unwrap();
        s.apply(blocker.id, Action::Start).unwrap();
        s.apply(blocker.id, Action::Complete(None)).unwrap();
        s.apply(blocker.id, Action::Accept).unwrap();
        let source = s.create_task(new("source")).unwrap();
        let task = s.create_task(new("task")).unwrap();
        s.add_dep(task.id, blocker.id, DepKind::Blocks).unwrap();
        s.add_dep(task.id, source.id, DepKind::DiscoveredFrom)
            .unwrap();

        // Forward: the task's own deps, every kind, resolved to the
        // dependency's title and state.
        let deps = s.deps_by_task().unwrap();
        assert_eq!(
            deps[&task.id],
            vec![
                DepRef {
                    id: blocker.id,
                    title: "blocker".into(),
                    state: TaskState::Done,
                    kind: DepKind::Blocks,
                },
                DepRef {
                    id: source.id,
                    title: "source".into(),
                    state: TaskState::Ready,
                    kind: DepKind::DiscoveredFrom,
                },
            ]
        );
        assert!(!deps[&task.id][0].is_open());
        assert!(!deps.contains_key(&blocker.id));

        // Reverse: keyed by the task depended on, resolving the dependant.
        let dependents = s.dependents_by_task().unwrap();
        assert_eq!(
            dependents[&blocker.id],
            vec![DepRef {
                id: task.id,
                title: "task".into(),
                state: TaskState::Ready,
                kind: DepKind::Blocks,
            }]
        );
        assert_eq!(dependents[&source.id].len(), 1);
        assert_eq!(dependents[&source.id][0].kind, DepKind::DiscoveredFrom);
        assert!(!dependents.contains_key(&task.id));
    }

    // --- docs (DESIGN.md §3/§5) ---

    #[test]
    fn a_doc_links_tasks_across_projects_and_answers_both_directions() {
        // The case the table exists for: one plan doc spawning work in several
        // projects, so the link cannot be constrained to the doc's own project.
        let mut s = Store::open_in_memory().unwrap();
        let plan = s.create_project("augere", "/tmp/augere").unwrap();
        let other = s.create_project("mote", "/tmp/mote").unwrap();
        let doc = s
            .create_doc(plan.id, None, "docs/strategy.md", Some("Strategy"))
            .unwrap();

        let a = s.create_task(new_ready(plan.id)).unwrap();
        let b = s.create_task(new_ready(other.id)).unwrap();
        let c = s.create_task(new_ready(other.id)).unwrap();
        for task in [&a, &b, &c] {
            assert!(s.link_doc(task.id, doc.id).unwrap());
        }
        // A repeated link is a no-op rather than an error.
        assert!(!s.link_doc(a.id, doc.id).unwrap());

        let derived: Vec<i64> = s
            .tasks_for_doc(doc.id)
            .unwrap()
            .into_iter()
            .map(|t| t.id)
            .collect();
        assert_eq!(derived, vec![a.id, b.id, c.id]);
        assert_eq!(s.docs_for_task(b.id).unwrap(), vec![doc.clone()]);
        assert_eq!(s.docs_by_task().unwrap()[&c.id], vec![doc.clone()]);

        assert!(s.unlink_doc(b.id, doc.id).unwrap());
        assert!(!s.unlink_doc(b.id, doc.id).unwrap());
        assert_eq!(s.tasks_for_doc(doc.id).unwrap().len(), 2);
        assert!(s.docs_for_task(b.id).unwrap().is_empty());
    }

    #[test]
    fn every_doc_link_and_unlink_lands_on_the_task_event_trail() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let doc = s.create_doc(p.id, None, "docs/DESIGN.md", None).unwrap();
        let t = s.create_task(new_ready(p.id)).unwrap();

        s.link_doc(t.id, doc.id).unwrap();
        s.unlink_doc(t.id, doc.id).unwrap();
        // A no-op link writes nothing, so the trail records changes only.
        s.unlink_doc(t.id, doc.id).unwrap();

        let kinds: Vec<String> = s
            .events_for(t.id)
            .unwrap()
            .into_iter()
            .map(|e| e.kind)
            .collect();
        assert_eq!(kinds, vec!["created", "doc-linked", "doc-unlinked"]);
    }

    #[test]
    fn set_task_docs_replaces_the_whole_list_and_logs_both_directions() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let one = s.create_doc(p.id, None, "docs/a.md", None).unwrap();
        let two = s.create_doc(p.id, None, "docs/b.md", None).unwrap();
        let t = s.create_task(new_ready(p.id)).unwrap();

        s.set_task_docs(t.id, &[one.id]).unwrap();
        // Replace, not append: `a` goes as `b` arrives.
        let now = s.set_task_docs(t.id, &[two.id]).unwrap();
        assert_eq!(now, vec![two.clone()]);

        let events: Vec<(String, Option<String>)> = s
            .events_for(t.id)
            .unwrap()
            .into_iter()
            .map(|e| (e.kind, e.detail))
            .collect();
        assert_eq!(
            events,
            vec![
                ("created".into(), Some("ready".into())),
                ("doc-linked".into(), Some("docs/a.md".into())),
                ("doc-unlinked".into(), Some("docs/a.md".into())),
                ("doc-linked".into(), Some("docs/b.md".into())),
            ]
        );

        // Clearing the list is the empty replacement.
        assert!(s.set_task_docs(t.id, &[]).unwrap().is_empty());
    }

    #[test]
    fn an_absolute_path_inside_a_checkout_is_stored_relative_to_it() {
        // Storing it relative is what makes the link survive the checkout
        // moving, which is why an operator may paste an absolute path.
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("augere", "/tmp/augere").unwrap();
        let doc = s
            .create_doc(p.id, None, "/tmp/augere/docs/strategy.md", None)
            .unwrap();
        assert_eq!(doc.location, "docs/strategy.md");
        assert_eq!(s.resolve_doc(&doc).unwrap(), "/tmp/augere/docs/strategy.md");

        // ...and it follows the checkout when that moves.
        s.set_default_repo_path(p.id, "/srv/augere").unwrap();
        assert_eq!(
            s.resolve_doc(&s.doc(doc.id).unwrap()).unwrap(),
            "/srv/augere/docs/strategy.md"
        );
    }

    #[test]
    fn a_relative_doc_resolves_against_the_repo_it_names() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("odm", "/tmp/odm").unwrap();
        let oats = s.add_repo(p.id, "oats", "/tmp/oats").unwrap();

        let default = s.create_doc(p.id, None, "docs/plan.md", None).unwrap();
        assert_eq!(s.resolve_doc(&default).unwrap(), "/tmp/odm/docs/plan.md");

        let named = s
            .create_doc(p.id, Some(oats.id), "notes/plan.md", None)
            .unwrap();
        assert_eq!(s.resolve_doc(&named).unwrap(), "/tmp/oats/notes/plan.md");

        // The longest containing checkout wins for an absolute path, so a repo
        // nested inside another is not swallowed by its parent.
        let nested = s.add_repo(p.id, "inner", "/tmp/odm/vendor").unwrap();
        let doc = s
            .create_doc(p.id, None, "/tmp/odm/vendor/docs/x.md", None)
            .unwrap();
        assert_eq!(doc.repo_id, Some(nested.id));
        assert_eq!(doc.location, "docs/x.md");
    }

    #[test]
    fn a_url_resolves_verbatim_and_takes_no_repo() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let repo = s.default_repo(p.id).unwrap();

        let doc = s
            .create_doc(p.id, None, "https://example.com/plan", Some("Plan"))
            .unwrap();
        assert!(doc.is_url());
        assert!(doc.repo_id.is_none());
        assert_eq!(s.resolve_doc(&doc).unwrap(), "https://example.com/plan");
        assert_eq!(doc.label(), "Plan");

        // A URL resolves on its own, so pairing it with a checkout is refused
        // rather than silently ignored.
        assert!(
            s.create_doc(p.id, Some(repo.id), "https://example.com/other", None)
                .is_err()
        );
    }

    #[test]
    fn a_doc_outside_every_checkout_stays_absolute() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let doc = s
            .create_doc(p.id, None, "/etc/notes/plan.md", None)
            .unwrap();
        assert_eq!(doc.location, "/etc/notes/plan.md");
        assert!(doc.repo_id.is_none());
        assert_eq!(s.resolve_doc(&doc).unwrap(), "/etc/notes/plan.md");
        // With --repo given, though, a path outside it is a mistake, not an
        // external document.
        let repo = s.default_repo(p.id).unwrap();
        assert!(
            s.create_doc(p.id, Some(repo.id), "/etc/notes/other.md", None)
                .is_err()
        );
    }

    #[test]
    fn a_doc_is_registered_once_per_project_and_labels_itself() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let other = s.create_project("mote", "/tmp/mote").unwrap();
        let doc = s.create_doc(p.id, None, "docs/plan.md", None).unwrap();
        // With no title, the location is the only name it has.
        assert_eq!(doc.label(), "docs/plan.md");
        assert!(s.create_doc(p.id, None, "docs/plan.md", None).is_err());
        // The same relative location under another project is a different doc,
        // since it resolves against that project's checkout.
        let twin = s.create_doc(other.id, None, "docs/plan.md", None).unwrap();
        assert_eq!(s.docs_at("docs/plan.md").unwrap().len(), 2);
        assert_ne!(doc.id, twin.id);
        assert_eq!(s.docs(p.id).unwrap(), vec![doc]);
        assert!(s.create_doc(p.id, None, "   ", None).is_err());
    }

    #[test]
    fn removing_a_doc_unlinks_its_tasks_rather_than_refusing() {
        // Unlike a repo, a doc is navigational — nothing resolves to nothing
        // when it goes — so removal frees its links instead of being refused.
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let doc = s.create_doc(p.id, None, "docs/plan.md", None).unwrap();
        let a = s.create_task(new_ready(p.id)).unwrap();
        let b = s.create_task(new_ready(p.id)).unwrap();
        s.link_doc(a.id, doc.id).unwrap();
        s.link_doc(b.id, doc.id).unwrap();

        let freed = s.delete_doc(doc.id).unwrap();
        assert_eq!(freed, vec![a.id, b.id]);
        assert!(s.doc(doc.id).is_err());
        assert!(s.docs_for_task(a.id).unwrap().is_empty());
        assert!(s.docs_by_task().unwrap().is_empty());
        assert_eq!(
            s.events_for(a.id).unwrap().last().unwrap().kind,
            "doc-unlinked"
        );
    }

    #[test]
    fn linking_names_a_task_and_a_doc_that_exist() {
        let mut s = Store::open_in_memory().unwrap();
        let p = s.create_project("voro", "/tmp/voro").unwrap();
        let doc = s.create_doc(p.id, None, "docs/plan.md", None).unwrap();
        let t = s.create_task(new_ready(p.id)).unwrap();
        assert!(s.link_doc(999, doc.id).is_err());
        assert!(s.link_doc(t.id, 999).is_err());
        assert!(s.set_task_docs(t.id, &[999]).is_err());
        // A refused replacement leaves the list as it was.
        assert!(s.docs_for_task(t.id).unwrap().is_empty());
    }

    /// A database from before migration 0014 must open with every existing
    /// task intact and no documents registered — docs are purely additive.
    #[test]
    fn migration_0014_leaves_existing_tasks_untouched() {
        let conn = Connection::open_in_memory().unwrap();
        for sql in &MIGRATIONS[..13] {
            conn.execute_batch(sql).unwrap();
        }
        conn.pragma_update(None, "user_version", 13).unwrap();
        conn.execute("INSERT INTO projects (name) VALUES ('legacy')", [])
            .unwrap();
        conn.execute(
            "INSERT INTO repos (project_id, name, path, is_default)
             VALUES (1, 'legacy', '/tmp/legacy', 1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO tasks (project_id, title, state, state_since, created_at)
             VALUES (1, 'old work', 'ready', datetime('now'), datetime('now'))",
            [],
        )
        .unwrap();

        let store = Store::from_connection(conn).unwrap();
        let task = store.task(1).unwrap();
        assert_eq!(task.title, "old work");
        assert_eq!(task.state, TaskState::Ready);
        assert!(store.all_docs().unwrap().is_empty());
        assert!(store.docs_for_task(1).unwrap().is_empty());
    }
}