kanzo 0.4.3

Self-hosted kanban for humans and agents. One 5.0 MB binary, starts in 3 ms, zero setup.
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
//! The database uses a rollback journal (`journal_mode = TRUNCATE`), not WAL. With a
//! connection per operation, WAL would set up and tear down its `-wal` and `-shm` files
//! on every request; the rollback journal makes a read touch no extra files at all and
//! measured about 3x faster per operation.

use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use std::time::Duration;

use rusqlite::functions::FunctionFlags;
use rusqlite::types::Value;
use rusqlite::{Connection, OptionalExtension, Row, params};
use serde::Serialize;

/// The oldest schema version whose Kanzo can still use a database at the latest one.
/// Adding a table or a column with a default leaves older versions working, so a board
/// synced from a newer Kanzo still opens in an older one. Raise it to the new version
/// only for a migration that older code can't live with, like a renamed column.
const COMPATIBLE_FROM: usize = 4;

const MIGRATIONS: &[&str] = &[
    include_str!("schema.sql"),
    "ALTER TABLE projects ADD COLUMN color TEXT;",
    "ALTER TABLE tasks ADD COLUMN tags TEXT NOT NULL DEFAULT '';",
    // The old projects.repo column stays, empty: SQLite can only drop it by rebuilding the table.
    "CREATE TABLE project_repos (
         repo       TEXT PRIMARY KEY,
         project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE
     );
     CREATE INDEX project_repos_by_project ON project_repos(project_id);
     INSERT INTO project_repos (repo, project_id) SELECT repo, id FROM projects WHERE repo IS NOT NULL;
     UPDATE projects SET repo = NULL;
     CREATE TRIGGER project_repos_insert AFTER INSERT ON project_repos BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;
     CREATE TRIGGER project_repos_delete AFTER DELETE ON project_repos BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",
    "CREATE TABLE images (
         id         INTEGER PRIMARY KEY AUTOINCREMENT,
         task_id    INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
         comment_id INTEGER REFERENCES comments(id) ON DELETE CASCADE,
         file       TEXT NOT NULL,
         created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
     );
     CREATE INDEX images_by_task ON images(task_id);
     CREATE TRIGGER images_insert AFTER INSERT ON images BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;
     CREATE TRIGGER images_delete AFTER DELETE ON images BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",
    "ALTER TABLE tasks ADD COLUMN human INTEGER NOT NULL DEFAULT 0;",
    "ALTER TABLE tasks ADD COLUMN url TEXT NOT NULL DEFAULT '';",
    "CREATE TABLE task_waits (
         task_id     INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
         waits_on_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
         PRIMARY KEY (task_id, waits_on_id)
     ) WITHOUT ROWID;
     CREATE INDEX task_waits_by_blocker ON task_waits(waits_on_id);
     CREATE TRIGGER task_waits_insert AFTER INSERT ON task_waits BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;
     CREATE TRIGGER task_waits_delete AFTER DELETE ON task_waits BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",
    "ALTER TABLE projects ADD COLUMN position REAL;",
    // What changed, for services that react to the board (`/api/events`). Written by the
    // same transaction as the change, so no change is lost and none is reported twice.
    // Task and project are plain ids: an event outlives a deleted task.
    "CREATE TABLE events (
         id          INTEGER PRIMARY KEY AUTOINCREMENT,
         at          TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
         kind        TEXT NOT NULL,
         task_id     INTEGER NOT NULL,
         project_id  INTEGER NOT NULL,
         project     TEXT NOT NULL DEFAULT '',
         status_from TEXT,
         status_to   TEXT,
         author      TEXT,
         -- Tells this board's event apart from one with the same id in another copy of the board.
         nonce       INTEGER NOT NULL DEFAULT (random())
     );
     CREATE INDEX events_by_project ON events(project_id, id);
     CREATE TRIGGER events_task_created AFTER INSERT ON tasks BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_to)
         VALUES ('task.created', new.id, new.project_id, (SELECT slug FROM projects WHERE id = new.project_id), new.status);
     END;
     CREATE TRIGGER events_task_moved AFTER UPDATE OF status ON tasks WHEN old.status IS NOT new.status BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_from, status_to)
         VALUES ('task.moved', new.id, new.project_id, (SELECT slug FROM projects WHERE id = new.project_id),
                 old.status, new.status);
     END;
     CREATE TRIGGER events_task_updated AFTER UPDATE ON tasks
     WHEN old.status IS new.status AND (old.title IS NOT new.title OR old.description IS NOT new.description
         OR old.tags IS NOT new.tags OR old.url IS NOT new.url OR old.human IS NOT new.human
         OR old.project_id IS NOT new.project_id) BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_to)
         VALUES ('task.updated', new.id, new.project_id, (SELECT slug FROM projects WHERE id = new.project_id), new.status);
     END;
     -- A deleted project reports its tasks before they go, while its slug is still known.
     CREATE TRIGGER events_project_deleted BEFORE DELETE ON projects BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_from)
         SELECT 'task.deleted', t.id, t.project_id, old.slug, t.status FROM tasks t WHERE t.project_id = old.id ORDER BY t.id;
     END;
     CREATE TRIGGER events_task_deleted AFTER DELETE ON tasks
     WHEN EXISTS (SELECT 1 FROM projects WHERE id = old.project_id) BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_from)
         VALUES ('task.deleted', old.id, old.project_id, (SELECT slug FROM projects WHERE id = old.project_id), old.status);
     END;
     CREATE TRIGGER events_comment_added AFTER INSERT ON comments BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_to, author)
         SELECT 'comment.added', t.id, t.project_id, p.slug, t.status, new.author
         FROM tasks t JOIN projects p ON p.id = t.project_id WHERE t.id = new.task_id;
     END;
     -- Edits to Waits on write their one event in update_task. This covers the other way they
     -- change: a task it waits on was deleted, while the waiting task stays.
     CREATE TRIGGER events_blocker_deleted AFTER DELETE ON task_waits
     WHEN NOT EXISTS (SELECT 1 FROM tasks WHERE id = old.waits_on_id) BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_to)
         SELECT 'task.updated', t.id, t.project_id, p.slug, t.status
         FROM tasks t JOIN projects p ON p.id = t.project_id WHERE t.id = old.task_id;
     END;
     -- Keeps the last `events_kept` (Settings), 1000 when unset.
     CREATE TRIGGER events_keep_recent AFTER INSERT ON events BEGIN
         DELETE FROM events
         WHERE id <= new.id - coalesce((SELECT CAST(value AS INTEGER) FROM meta WHERE key = 'events_kept'), 1000);
     END;",
    // An agent handed the task to the user; its next move to another column clears it.
    "ALTER TABLE tasks ADD COLUMN escalated INTEGER NOT NULL DEFAULT 0;",
    // Where a repo lives, like gitlab.com, for links to it. Empty is GitHub, as for a repo
    // linked as owner/repo, or before this.
    "ALTER TABLE project_repos ADD COLUMN host TEXT;",
    // A task's priority: 0 for P0, the highest, to 3 for P3. NULL, as on most tasks, is none.
    // events_task_updated lists the columns it watches, so it learns this one too.
    "ALTER TABLE tasks ADD COLUMN priority INTEGER;
     DROP TRIGGER events_task_updated;
     CREATE TRIGGER events_task_updated AFTER UPDATE ON tasks
     WHEN old.status IS new.status AND (old.title IS NOT new.title OR old.description IS NOT new.description
         OR old.tags IS NOT new.tags OR old.url IS NOT new.url OR old.human IS NOT new.human
         OR old.project_id IS NOT new.project_id OR old.priority IS NOT new.priority) BEGIN
         INSERT INTO events (kind, task_id, project_id, project, status_to)
         VALUES ('task.updated', new.id, new.project_id, (SELECT slug FROM projects WHERE id = new.project_id), new.status);
     END;",
];

const PROJECT_COLORS: &[&str] = &["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"];

const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";

#[derive(Debug)]
pub enum Error {
    NotFound(String),
    Invalid(String),
    Busy(String),
    Db(rusqlite::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::NotFound(m) | Error::Invalid(m) | Error::Busy(m) => f.write_str(m),
            Error::Db(e) => write!(f, "database error: {e}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Db(e) => Some(e),
            _ => None,
        }
    }
}

impl From<rusqlite::Error> for Error {
    fn from(e: rusqlite::Error) -> Self {
        Error::Db(e)
    }
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone, Serialize)]
pub struct Project {
    pub id: i64,
    pub slug: String,
    pub name: String,
    pub repos: Vec<String>,
    /// Each repo's page, in the order of `repos`.
    pub repo_urls: Vec<String>,
    pub color: Option<String>,
    pub created_at: String,
    pub open: i64,
    pub total: i64,
}

#[derive(Debug, Clone, Serialize)]
pub struct Task {
    pub id: i64,
    pub project: String,
    pub title: String,
    pub description: String,
    pub tags: Vec<String>,
    /// A link to anything, like the task's pull request; empty when there is none.
    pub url: String,
    pub human: bool,
    /// 0 for P0, the highest, to 3. Left out when there is none, as on most tasks.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<i64>,
    /// An agent handed it to the user, until it next moves to another column. Left out when not, as on most tasks.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub escalated: bool,
    pub status: String,
    pub position: f64,
    pub created_at: String,
    pub updated_at: String,
    pub comments: i64,
    /// The tasks this one waits on that aren't done yet. Left out when there are none, as on most tasks.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub waiting_on: Vec<i64>,
}

impl Task {
    pub fn key(&self) -> String {
        format!("{}#{}", self.project, self.id)
    }
}

/// Events `/api/events` keeps unless Settings says otherwise: enough for a reader that
/// was away a while, about 80 KB on disk.
pub const EVENTS_KEPT: i64 = 1000;
const EVENTS_KEPT_RANGE: std::ops::RangeInclusive<i64> = 100..=100_000;

/// A page of events after a reader's cursor.
#[derive(Debug, Clone, Serialize)]
pub struct EventPage {
    pub events: Vec<Event>,
    /// The cursor to pass as `since` next time.
    pub last: String,
    /// The cursor names no event of this board: it was dropped (only the last `events_kept`
    /// are kept), or the board was replaced, as by `kanzo sync`. Read the board again, then
    /// go on from `last`.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub reset: bool,
}

/// `0` before the first event, else `<id>.<nonce in hex>`.
fn cursor(id: i64, nonce: i64) -> String {
    if id == 0 { "0".into() } else { format!("{id}.{:x}", nonce as u64) }
}

/// One change on the board, as `/api/events` reports it.
#[derive(Debug, Clone, Serialize)]
pub struct Event {
    pub id: i64,
    pub at: String,
    /// `task.created`, `task.moved`, `task.updated`, `task.deleted` or `comment.added`.
    pub kind: String,
    /// Like `api#12`, with the project's slug when the event was written.
    pub task: String,
    pub project: String,
    /// The column before a move or a delete.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// The column after the change.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    /// Who wrote the comment, for `comment.added`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
}

/// A task another one waits on or blocks.
#[derive(Debug, Clone, Serialize)]
pub struct TaskLink {
    pub id: i64,
    pub project: String,
    pub title: String,
    pub status: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct Comment {
    pub id: i64,
    pub task_id: i64,
    pub author: String,
    pub body: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct Image {
    pub id: i64,
    pub task_id: i64,
    pub comment_id: Option<i64>,
    pub file: String,
}

#[derive(Debug, Default)]
pub struct TaskPatch {
    pub title: Option<String>,
    pub description: Option<String>,
    pub status: Option<String>,
    pub project_id: Option<i64>,
    pub tags: Option<String>,
    pub url: Option<String>,
    pub human: Option<bool>,
    /// P0 to P3, or 0 to 3; "" clears it.
    pub priority: Option<String>,
    /// Task keys, comma-separated; it replaces the list.
    pub waits_on: Option<String>,
    /// Without it, a move to another column clears it.
    pub escalated: Option<bool>,
}

/// The most a comment saved with a task edit (`update_task`'s `comment`) can hold: 16 KiB of
/// UTF-8, after trimming. Enough for a short Completed / Remaining / Verified / Next step note.
/// `add_comment` keeps having no limit of its own.
pub const HANDOFF_MAX: usize = 16 * 1024;

/// A comment saved in the same write as a task edit.
pub struct NewComment<'a> {
    pub author: &'a str,
    pub body: &'a str,
}

const STATUSES: [&str; 4] = ["todo", "doing", "review", "done"];

pub const DONE: &str = STATUSES[3];

pub const BACKLOG: &str = "backlog";

/// What a task shows besides its id, title and status; each can be turned off in Settings.
const PROPERTIES: [&str; 10] =
    ["description", "priority", "tags", "url", "human", "waiting", "created", "updated", "comments", "images"];

/// How next_task ranks before the column's order: a task without a priority counts as P2, the usual
/// middle, so P0 and P1 go before it, P3 after, and P2 by its place in the column.
const BY_PRIORITY: &str = "coalesce(t.priority, 2), ";

pub struct Store {
    conn: Connection,
    statuses: Vec<String>,
    /// Declared after `conn` so it is released after the connection closes.
    _lock: Option<std::fs::File>,
}

impl Store {
    pub fn open(path: &Path, lock: Option<std::fs::File>) -> Result<Self> {
        let conn = Connection::open(path)?;
        // The board and any number of agents share this file; wait instead of failing.
        conn.busy_timeout(Duration::from_secs(5))?;
        // Per connection, not stored in the file. Also turns a WAL database from an
        // older kanzo back into a rollback-journal one once nothing else has it open.
        // `synchronous` stays at SQLite's default FULL, which keeps the file intact
        // when a board loses power.
        conn.pragma_update_and_check(None, "journal_mode", "TRUNCATE", |_| Ok(()))?;
        conn.pragma_update(None, "foreign_keys", "ON")?;
        // Before the first migration there is no meta table, and so no backlog.
        let backlog = conn
            .query_row("SELECT value FROM meta WHERE key = 'backlog'", [], |r| r.get::<_, String>(0))
            .is_ok_and(|v| v == "1");
        let statuses = backlog.then_some(BACKLOG).into_iter().chain(STATUSES).map(String::from).collect();
        Ok(Self { conn, statuses, _lock: lock })
    }

    pub fn statuses(&self) -> &[String] {
        &self.statuses
    }

    pub fn set_backlog(&self, on: bool) -> Result<()> {
        self.write(|c| {
            let left: i64 = c.query_row("SELECT count(*) FROM tasks WHERE status = ?1", [BACKLOG], |r| r.get(0))?;
            if !on && left > 0 {
                return Err(Error::Invalid(format!("move the {left} {} out of backlog first", tasks(left))));
            }
            c.execute(
                "INSERT INTO meta (key, value) VALUES ('backlog', ?1) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                [if on { "1" } else { "0" }],
            )?;
            // Other open boards redraw their columns.
            c.execute("UPDATE meta SET value = value + 1 WHERE key = 'changes'", [])?;
            Ok(())
        })
    }

    /// The properties turned off in Settings: off the board, and out of what agents get.
    pub fn hidden_properties(&self) -> Result<Vec<String>> {
        let hidden: Option<String> = self
            .conn
            .query_row("SELECT value FROM meta WHERE key = 'hidden_properties'", [], |r| r.get(0))
            .optional()?;
        Ok(hidden.unwrap_or_default().split(',').filter(|p| !p.is_empty()).map(String::from).collect())
    }

    pub fn set_property(&self, property: &str, visible: bool) -> Result<()> {
        if !PROPERTIES.contains(&property) {
            return Err(Error::Invalid(format!("unknown property {property:?}")));
        }
        self.write(|c| {
            let mut hidden = self.hidden_properties()?;
            hidden.retain(|p| p != property);
            if !visible {
                hidden.push(property.to_string());
            }
            c.execute(
                "INSERT INTO meta (key, value) VALUES ('hidden_properties', ?1) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                [hidden.join(",")],
            )?;
            // Other open boards redraw their tasks.
            c.execute("UPDATE meta SET value = value + 1 WHERE key = 'changes'", [])?;
            Ok(())
        })
    }

    /// Immediate, so concurrent writers queue up on the busy timeout instead of failing halfway.
    fn write<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        self.conn.execute_batch("BEGIN IMMEDIATE")?;
        match f(&self.conn) {
            Ok(v) => {
                self.conn.execute_batch("COMMIT")?;
                Ok(v)
            }
            Err(e) => {
                let _ = self.conn.execute_batch("ROLLBACK");
                Err(e)
            }
        }
    }

    /// Writes nothing when up to date, so starting `kanzo mcp` for every agent session
    /// costs no disk write.
    pub fn migrate(&self) -> Result<()> {
        let meta = |c: &Connection, key: &str| -> rusqlite::Result<Option<usize>> {
            Ok(c.query_row("SELECT value FROM meta WHERE key = ?1", [key], |r| r.get::<_, String>(0))
                .optional()?
                .and_then(|v| v.parse().ok()))
        };
        let latest = MIGRATIONS.len();
        let current =
            (meta(&self.conn, "schema_version").unwrap_or(None), meta(&self.conn, "compatible").unwrap_or(None));
        if current == (Some(latest), Some(COMPATIBLE_FROM)) {
            return Ok(());
        }
        self.write(|c| {
            c.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)", [])?;
            let version = meta(c, "schema_version")?.unwrap_or(0);
            if version > latest {
                // From a newer Kanzo, maybe synced from another machine: use it as it is
                // when this version can, without touching its schema.
                if meta(c, "compatible")?.is_some_and(|oldest| oldest <= latest) {
                    return Ok(());
                }
                return Err(Error::Invalid(
                    "this board was saved by a newer version of Kanzo; update this one with `kanzo update`".into(),
                ));
            }
            for sql in &MIGRATIONS[version..] {
                c.execute_batch(sql)?;
            }
            c.execute(
                "INSERT INTO meta (key, value) VALUES ('schema_version', ?1), ('compatible', ?2)
                 ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                [latest.to_string(), COMPATIBLE_FROM.to_string()],
            )?;
            Ok(())
        })
    }

    pub fn changes(&self) -> Result<i64> {
        Ok(self
            .conn
            .prepare_cached("SELECT CAST(value AS INTEGER) FROM meta WHERE key = 'changes'")?
            .query_row([], |r| r.get(0))?)
    }

    /// The events after the id `since`, oldest first, at most `limit`. Readers come through
    /// `events_after`, which also checks that their cursor names an event of this board.
    pub fn events_since(&self, since: i64, project_id: Option<i64>, limit: usize) -> Result<Vec<Event>> {
        let mut stmt = self.conn.prepare_cached(
            "SELECT id, at, kind, task_id, project, status_from, status_to, author FROM events
             WHERE id > ?1 AND (?2 IS NULL OR project_id = ?2)
             ORDER BY id LIMIT ?3",
        )?;
        let rows = stmt.query_map(params![since, project_id, limit as i64], |r| {
            let project: String = r.get(4)?;
            Ok(Event {
                id: r.get(0)?,
                at: r.get(1)?,
                kind: r.get(2)?,
                task: format!("{project}#{}", r.get::<_, i64>(3)?),
                project,
                from: r.get(5)?,
                to: r.get(6)?,
                author: r.get(7)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    #[cfg(test)]
    pub fn conn_for_tests(&self) -> &Connection {
        &self.conn
    }

    /// The id of the newest event, 0 when there is none.
    #[cfg(test)]
    pub fn last_event(&self) -> Result<i64> {
        Ok(self.conn.prepare_cached("SELECT coalesce(max(id), 0) FROM events")?.query_row([], |r| r.get(0))?)
    }

    /// How many of the newest events `/api/events` keeps.
    pub fn events_kept(&self) -> Result<i64> {
        let kept: Option<i64> = self
            .conn
            .query_row("SELECT CAST(value AS INTEGER) FROM meta WHERE key = 'events_kept'", [], |r| r.get(0))
            .optional()?;
        Ok(kept.unwrap_or(EVENTS_KEPT))
    }

    pub fn set_events_kept(&self, kept: i64) -> Result<()> {
        if !EVENTS_KEPT_RANGE.contains(&kept) {
            let (min, max) = (EVENTS_KEPT_RANGE.start(), EVENTS_KEPT_RANGE.end());
            return Err(Error::Invalid(format!("keep between {min} and {max} events")));
        }
        self.write(|c| {
            c.execute(
                "INSERT INTO meta (key, value) VALUES ('events_kept', ?1) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                [kept.to_string()],
            )?;
            // Fewer at once, not only when the next event comes.
            c.execute("DELETE FROM events WHERE id <= (SELECT max(id) FROM events) - ?1", [kept])?;
            c.execute("UPDATE meta SET value = value + 1 WHERE key = 'changes'", [])?;
            Ok(())
        })
    }

    /// The events after `since`, a cursor from an earlier page; without one, an empty page
    /// that says where to start. Read in one transaction, so the page and its cursor agree.
    pub fn events_after(&self, since: Option<&str>, project_id: Option<i64>, limit: usize) -> Result<EventPage> {
        let _read = self.conn.unchecked_transaction()?;
        let newest: (i64, i64) = self.conn.query_row(
            "SELECT coalesce(max(id), 0), coalesce((SELECT nonce FROM events ORDER BY id DESC LIMIT 1), 0) FROM events",
            [],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )?;
        let newest = cursor(newest.0, newest.1);
        let Some(since) = since else {
            return Ok(EventPage { events: Vec::new(), last: newest, reset: false });
        };
        let after = if since == "0" {
            // `0` came from a board with no events yet; if some were dropped since, the
            // reader missed them.
            let oldest: i64 = self.conn.query_row("SELECT coalesce(min(id), 1) FROM events", [], |r| r.get(0))?;
            if oldest > 1 {
                return Ok(EventPage { events: Vec::new(), last: newest, reset: true });
            }
            0
        } else {
            let parsed = since
                .split_once('.')
                .and_then(|(id, nonce)| Some((id.parse::<i64>().ok()?, u64::from_str_radix(nonce, 16).ok()? as i64)));
            let Some((id, nonce)) = parsed else {
                return Err(Error::Invalid(format!("since {since:?} is not a cursor from /api/events")));
            };
            let found: Option<i64> =
                self.conn.query_row("SELECT nonce FROM events WHERE id = ?1", [id], |r| r.get(0)).optional()?;
            if found != Some(nonce) {
                return Ok(EventPage { events: Vec::new(), last: newest, reset: true });
            }
            id
        };
        let events = self.events_since(after, project_id, limit)?;
        let last = match events.last() {
            Some(e) => {
                let nonce: i64 = self.conn.query_row("SELECT nonce FROM events WHERE id = ?1", [e.id], |r| r.get(0))?;
                cursor(e.id, nonce)
            }
            // Nothing for this reader up to the newest event.
            None => newest,
        };
        Ok(EventPage { events, last, reset: false })
    }

    /// The ids of the oldest and the newest kept event, both 0 when there is none.
    #[cfg(test)]
    pub fn event_range(&self) -> Result<(i64, i64)> {
        Ok(self
            .conn
            .prepare_cached("SELECT coalesce(min(id), 0), coalesce(max(id), 0) FROM events")?
            .query_row([], |r| Ok((r.get(0)?, r.get(1)?)))?)
    }

    pub fn now(&self) -> Result<String> {
        Ok(self.conn.query_row(&format!("SELECT {NOW}"), [], |r| r.get(0))?)
    }

    /// Makes `kanzo.db` complete on its own: rolls back a write that a crashed process
    /// left half done, and folds in a WAL left by an older kanzo.
    pub fn settle(&self) -> Result<()> {
        self.conn.query_row("SELECT count(*) FROM meta", [], |r| r.get::<_, i64>(0))?;
        Ok(())
    }

    const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name,
            (SELECT group_concat(repo, ',' ORDER BY r.rowid) FROM project_repos r WHERE r.project_id = p.id),
            p.color, p.created_at,
            (SELECT count(*) FROM tasks t WHERE t.project_id = p.id AND t.status <> ?1),
            (SELECT count(*) FROM tasks t WHERE t.project_id = p.id),
            (SELECT group_concat('https://' || coalesce(host, 'github.com') || '/' || repo, ',' ORDER BY r.rowid)
             FROM project_repos r WHERE r.project_id = p.id)
        FROM projects p";

    fn project_row(r: &Row) -> rusqlite::Result<Project> {
        let list = |i| -> rusqlite::Result<Vec<String>> {
            Ok(r.get::<_, Option<String>>(i)?.map(|s| s.split(',').map(String::from).collect()).unwrap_or_default())
        };
        Ok(Project {
            id: r.get(0)?,
            slug: r.get(1)?,
            name: r.get(2)?,
            repos: list(3)?,
            repo_urls: list(8)?,
            color: r.get(4)?,
            created_at: r.get(5)?,
            open: r.get(6)?,
            total: r.get(7)?,
        })
    }

    pub fn list_projects(&self) -> Result<Vec<Project>> {
        let sql = format!("{} ORDER BY p.position IS NULL, p.position, p.slug", Self::PROJECT_SELECT);
        let mut stmt = self.conn.prepare(&sql)?;
        let rows = stmt.query_map([DONE], Self::project_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    fn project_where(&self, clause: &str, value: &str) -> Result<Option<Project>> {
        let sql = format!("{} WHERE {clause}", Self::PROJECT_SELECT);
        Ok(self.conn.query_row(&sql, params![DONE, value], Self::project_row).optional()?)
    }

    pub fn project_by_slug(&self, slug: &str) -> Result<Option<Project>> {
        self.project_where("p.slug = ?2", &slug.trim().to_ascii_lowercase())
    }

    pub fn project_by_repo(&self, repo: &str) -> Result<Option<Project>> {
        match repo_from_url(repo) {
            Some(repo) => self.project_where("p.id = (SELECT project_id FROM project_repos WHERE repo = ?2)", &repo),
            None => Ok(None),
        }
    }

    pub fn find_project(&self, name: &str) -> Result<Project> {
        let found = match self.project_by_slug(name)? {
            Some(p) => Some(p),
            None if name.contains('/') => self.project_by_repo(name)?,
            None => None,
        };
        found.ok_or_else(|| {
            let known = self.list_projects().unwrap_or_default();
            let names: Vec<_> = known.iter().map(|p| p.slug.as_str()).collect();
            let hint = if names.is_empty() {
                "there are no projects yet".to_string()
            } else {
                format!("projects: {}", names.join(", "))
            };
            Error::NotFound(format!("no project {name:?} ({hint})"))
        })
    }

    pub fn create_project(&self, slug: &str, name: &str, repo: Option<&str>) -> Result<Project> {
        let slug = slug.trim().to_ascii_lowercase();
        if !valid_slug(&slug) {
            return Err(Error::Invalid(format!(
                "project slug {slug:?} must be 1-32 lowercase letters, digits or -, starting with a letter or digit"
            )));
        }
        let name = match name.trim() {
            "" => slug.clone(),
            n => n.to_string(),
        };
        let repo = repo.map(str::trim).filter(|r| !r.is_empty());
        let host = repo.and_then(host_from_url);
        let repo = repo.map(clean_repo).transpose()?;
        // Checked in the write's transaction, so nobody can take the slug or the repo in between.
        self.write(|c| {
            if self.project_by_slug(&slug)?.is_some() {
                return Err(Error::Invalid(format!("project {slug} already exists")));
            }
            if let Some(r) = &repo {
                self.check_repo_free(r)?;
            }
            c.execute("INSERT INTO projects (slug, name) VALUES (?1, ?2)", params![slug, name])?;
            if let Some(r) = &repo {
                c.execute(
                    "INSERT INTO project_repos (repo, project_id, host) VALUES (?1, ?2, ?3)",
                    params![r, c.last_insert_rowid(), host],
                )?;
            }
            Ok(())
        })?;
        self.find_project(&slug)
    }

    pub fn link_repo(&self, slug: &str, repo: &str) -> Result<Project> {
        let project = self.find_project(slug)?;
        let host = host_from_url(repo);
        let repo = clean_repo(repo)?;
        if project.repos.contains(&repo) {
            return Ok(project);
        }
        self.write(|c| {
            self.check_repo_free(&repo)?;
            c.execute(
                "INSERT INTO project_repos (repo, project_id, host) VALUES (?1, ?2, ?3)",
                params![repo, project.id, host],
            )?;
            Ok(())
        })?;
        self.find_project(&project.slug)
    }

    pub fn unlink_repo(&self, slug: &str, repo: &str) -> Result<Project> {
        let project = self.find_project(slug)?;
        let repo = repo_from_url(repo).unwrap_or_else(|| repo.trim().to_ascii_lowercase());
        let removed = self
            .conn
            .execute("DELETE FROM project_repos WHERE repo = ?1 AND project_id = ?2", params![repo, project.id])?;
        if removed == 0 {
            return Err(Error::NotFound(format!("repo {repo} is not linked to project {}", project.slug)));
        }
        self.find_project(&project.slug)
    }

    fn check_repo_free(&self, repo: &str) -> Result<()> {
        match self.project_by_repo(repo)? {
            Some(other) => Err(Error::Invalid(format!("repo {repo} is already linked to project {}", other.slug))),
            None => Ok(()),
        }
    }

    pub fn rename_project(&self, slug: &str, name: &str) -> Result<Project> {
        let name = squash(name);
        if name.is_empty() {
            return Err(Error::Invalid("project name is empty".into()));
        }
        let project = self.find_project(slug)?;
        self.conn.execute("UPDATE projects SET name = ?1 WHERE id = ?2", params![name, project.id])?;
        self.find_project(&project.slug)
    }

    pub fn set_project_color(&self, slug: &str, color: &str) -> Result<Project> {
        if !PROJECT_COLORS.contains(&color) {
            return Err(Error::Invalid(format!("unknown color {color:?}; use one of: {}", PROJECT_COLORS.join(", "))));
        }
        let project = self.find_project(slug)?;
        self.conn.execute("UPDATE projects SET color = ?1 WHERE id = ?2", params![color, project.id])?;
        self.find_project(&project.slug)
    }

    /// Before `before`, or last. A project never moved has no position and comes after those that
    /// have one, by slug, so only a move that lands among those has to number them all.
    pub fn move_project(&self, slug: &str, before: Option<&str>) -> Result<Project> {
        let project = self.find_project(slug)?;
        let before = before.map(|b| self.find_project(b)).transpose()?;
        if before.as_ref().is_some_and(|b| b.id == project.id) {
            return Ok(project);
        }
        self.write(|c| {
            let mut others: Vec<(i64, Option<f64>)> = c
                .prepare("SELECT id, position FROM projects WHERE id <> ?1 ORDER BY position IS NULL, position, slug")?
                .query_map([project.id], |r| Ok((r.get(0)?, r.get(1)?)))?
                .collect::<rusqlite::Result<_>>()?;
            let at = before.and_then(|b| others.iter().position(|o| o.0 == b.id)).unwrap_or(others.len());
            let position = match (at.checked_sub(1).map(|i| others[i].1), others.get(at).map(|o| o.1)) {
                (None, Some(Some(next))) => Some(next - 1.0),
                (None, _) => Some(1.0),
                (Some(Some(prev)), Some(Some(next))) if next - prev >= 1e-9 => Some((prev + next) / 2.0),
                (Some(Some(prev)), Some(None) | None) => Some(prev + 1.0),
                _ => None,
            };
            let mut update = c.prepare("UPDATE projects SET position = ?1 WHERE id = ?2")?;
            if let Some(position) = position {
                update.execute(params![position, project.id])?;
            } else {
                others.insert(at, (project.id, None));
                for (i, (id, _)) in others.iter().enumerate() {
                    update.execute(params![(i + 1) as f64, id])?;
                }
            }
            Ok(())
        })?;
        self.find_project(&project.slug)
    }

    pub fn delete_project(&self, slug: &str) -> Result<Project> {
        let project = self.find_project(slug)?;
        // Tasks and comments go with it through ON DELETE CASCADE.
        self.conn.execute("DELETE FROM projects WHERE id = ?1", [project.id])?;
        Ok(project)
    }

    const TASK_SELECT: &str = "SELECT t.id, p.slug, t.title, t.description, t.status, t.position,
            t.created_at, t.updated_at, (SELECT count(*) FROM comments c WHERE c.task_id = t.id), t.tags, t.human,
            t.url, t.escalated, t.priority
        FROM tasks t JOIN projects p ON p.id = t.project_id";

    fn task_row(r: &Row) -> rusqlite::Result<Task> {
        Ok(Task {
            id: r.get(0)?,
            project: r.get(1)?,
            title: r.get(2)?,
            description: r.get(3)?,
            tags: r.get::<_, String>(9)?.split(',').filter(|t| !t.is_empty()).map(String::from).collect(),
            url: r.get(11)?,
            human: r.get(10)?,
            priority: r.get(13)?,
            escalated: r.get(12)?,
            status: r.get(4)?,
            position: r.get(5)?,
            created_at: r.get(6)?,
            updated_at: r.get(7)?,
            comments: r.get(8)?,
            waiting_on: Vec::new(),
        })
    }

    /// One query for all of them, not a subquery per task: on a board of 3,000 tasks that took
    /// /api/board from 5.3 ms to 7.3 ms even with nothing waiting. Now tasks pay only for actual links.
    fn add_waiting(&self, tasks: &mut [Task]) -> Result<()> {
        let mut stmt = self.conn.prepare_cached(
            "SELECT w.task_id, w.waits_on_id FROM task_waits w JOIN tasks b ON b.id = w.waits_on_id
             WHERE b.status <> 'done' ORDER BY w.waits_on_id",
        )?;
        let mut rows = stmt.query([])?;
        let mut waiting: HashMap<i64, Vec<i64>> = HashMap::new();
        while let Some(r) = rows.next()? {
            waiting.entry(r.get(0)?).or_default().push(r.get(1)?);
        }
        if !waiting.is_empty() {
            for t in tasks {
                t.waiting_on = waiting.remove(&t.id).unwrap_or_default();
            }
        }
        Ok(())
    }

    pub fn list_tasks(&self, project_id: Option<i64>, status: Option<&str>) -> Result<Vec<Task>> {
        Ok(self.list_tasks_keeping_done(project_id, status, None)?.0)
    }

    /// The done column only grows, so only its newest `keep_done` tasks are read.
    pub fn list_tasks_keeping_done(
        &self,
        project_id: Option<i64>,
        status: Option<&str>,
        keep_done: Option<usize>,
    ) -> Result<(Vec<Task>, usize)> {
        let done = DONE;
        // SQLite reads a negative LIMIT as no limit.
        let limit = keep_done.map_or(-1, |n| n as i64);
        let sql = format!(
            "{} WHERE (?1 IS NULL OR t.project_id = ?1) AND (?2 IS NULL OR t.status = ?2)
               AND (t.status <> ?3 OR t.id IN (SELECT id FROM tasks WHERE status = ?3
                    AND (?1 IS NULL OR project_id = ?1) ORDER BY position DESC LIMIT ?4))
             ORDER BY t.position",
            Self::TASK_SELECT
        );
        let mut stmt = self.conn.prepare(&sql)?;
        let mut tasks: Vec<Task> = stmt
            .query_map(params![project_id, status, done, limit], Self::task_row)?
            .collect::<rusqlite::Result<_>>()?;
        self.add_waiting(&mut tasks)?;
        let column = |t: &Task| self.statuses().iter().position(|s| *s == t.status).unwrap_or(usize::MAX);
        tasks.sort_by_key(column);
        let hidden = match keep_done {
            Some(keep) if status.is_none_or(|s| s == done) => {
                let all: i64 = self.conn.query_row(
                    "SELECT count(*) FROM tasks WHERE status = ?1 AND (?2 IS NULL OR project_id = ?2)",
                    params![done, project_id],
                    |r| r.get(0),
                )?;
                usize::try_from(all).unwrap_or(0).saturating_sub(keep)
            }
            _ => 0,
        };
        Ok((tasks, hidden))
    }

    // SQLite's LIKE ignores case only for ASCII. Registered per query, not in open, because
    // every operation opens a connection and only filters need this.
    fn add_has_word(&self) -> Result<()> {
        let flags = FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC;
        self.conn.create_scalar_function("has_word", 2, flags, |c| {
            Ok(c.get_raw(0).as_str()?.to_lowercase().contains(c.get_raw(1).as_str()?))
        })?;
        Ok(())
    }

    /// The tasks agents have escalated to the user, as id, project and title, for the board's
    /// push notifications.
    pub fn escalated(&self) -> Result<Vec<(i64, String, String)>> {
        let mut stmt = self.conn.prepare(
            "SELECT t.id, p.slug, t.title FROM tasks t JOIN projects p ON p.id = t.project_id
             WHERE t.escalated ORDER BY t.id",
        )?;
        Ok(stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<rusqlite::Result<_>>()?)
    }

    pub fn search(&self, query: &str, limit: Option<usize>) -> Result<Vec<Task>> {
        self.search_seeing(query, limit, &[])
    }

    /// Finds nothing through a property Settings hides from agents.
    pub fn search_for_agent(&self, query: &str) -> Result<Vec<Task>> {
        self.search_seeing(query, None, &self.hidden_properties()?)
    }

    fn search_seeing(&self, query: &str, limit: Option<usize>, hidden: &[String]) -> Result<Vec<Task>> {
        self.add_has_word()?;
        let filter = Filter::new(query, 2, hidden);
        // SQLite reads a negative LIMIT as no limit.
        let limit = limit.map_or(-1, |n| n as i64);
        let sql = format!(
            "{} WHERE 1{} ORDER BY t.status = ?1, t.updated_at DESC, t.id DESC LIMIT {limit}",
            Self::TASK_SELECT,
            filter.sql
        );
        let mut values: Vec<String> = vec![DONE.to_string()];
        values.extend(filter.values);
        let mut stmt = self.conn.prepare(&sql)?;
        let rows = stmt.query_map(rusqlite::params_from_iter(values.iter()), Self::task_row)?;
        let mut tasks: Vec<Task> = rows.collect::<rusqlite::Result<_>>()?;
        self.add_waiting(&mut tasks)?;
        Ok(tasks)
    }

    pub fn get_task(&self, id: i64) -> Result<Task> {
        let sql = format!("{} WHERE t.id = ?1", Self::TASK_SELECT);
        let mut task = self
            .conn
            .prepare_cached(&sql)?
            .query_row([id], Self::task_row)
            .optional()?
            .ok_or_else(|| Error::NotFound(format!("no task #{id}")))?;
        task.waiting_on = self.task_links(id, false)?.into_iter().filter(|t| t.status != DONE).map(|t| t.id).collect();
        Ok(task)
    }

    pub fn find_task(&self, key: &str) -> Result<Task> {
        let (slug, id) = parse_task_key(key)?;
        let task = self.get_task(id)?;
        if let Some(slug) = slug
            && slug != task.project
        {
            return Err(Error::NotFound(format!("no task {key} (#{id} is {})", task.key())));
        }
        Ok(task)
    }

    pub fn check_status(&self, status: &str) -> Result<()> {
        if self.statuses().iter().any(|s| s == status) {
            Ok(())
        } else {
            Err(Error::Invalid(format!("unknown status {status:?}; use one of: {}", self.statuses().join(", "))))
        }
    }

    fn end_of_column(c: &Connection, status: &str, except: i64) -> Result<f64> {
        let max: Option<f64> = c.query_row(
            "SELECT max(position) FROM tasks WHERE status = ?1 AND id <> ?2",
            params![status, except],
            |r| r.get(0),
        )?;
        Ok(max.map_or(1.0, |m| m.floor() + 1.0))
    }

    #[cfg(test)]
    pub fn create_task(&self, project: i64, title: &str, description: &str) -> Result<Task> {
        self.create_task_in(project, title, TaskPatch { description: Some(description.into()), ..Default::default() })
    }

    // One write, or an agent could take a task before it's human, or before it waits.
    // Uses description, status, tags, human, priority, waits_on.
    pub fn create_task_in(&self, project_id: i64, title: &str, patch: TaskPatch) -> Result<Task> {
        let title = clean_title(title)?;
        let status = patch.status.as_deref().unwrap_or(STATUSES[0]);
        self.check_status(status)?;
        let description = patch.description.as_deref().unwrap_or("").trim();
        let tags = clean_tags(patch.tags.as_deref().unwrap_or("")).join(",");
        let priority = patch.priority.as_deref().map(clean_priority).transpose()?.flatten();
        let id = self.write(|c| {
            let position = Self::end_of_column(c, status, 0)?;
            c.execute(
                "INSERT INTO tasks (project_id, title, description, status, position, tags, human, priority) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![project_id, title, description, status, position, tags, patch.human.unwrap_or(false), priority],
            )?;
            let id = c.last_insert_rowid();
            if let Some(keys) = &patch.waits_on {
                // Part of task.created.
                self.set_waits(c, id, keys)?;
            }
            Ok(id)
        })?;
        self.get_task(id)
    }

    /// Replaces what a task waits on. Part of the task's write, so a refused list changes nothing.
    /// Whether it changed anything.
    fn set_waits(&self, c: &Connection, id: i64, keys: &str) -> Result<bool> {
        let mut ids = Vec::new();
        for key in keys.split(',').map(str::trim).filter(|k| !k.is_empty()) {
            ids.push(self.find_task(key)?.id);
        }
        ids.sort_unstable();
        ids.dedup();
        if ids.iter().copied().eq(self.task_links(id, false)?.iter().map(|t| t.id)) {
            return Ok(false);
        }
        c.execute("DELETE FROM task_waits WHERE task_id = ?1", [id])?;
        for other in ids {
            let loops: bool = c.query_row(
                "WITH RECURSIVE chain(id) AS (
                     SELECT ?1 UNION SELECT w.waits_on_id FROM task_waits w JOIN chain ON w.task_id = chain.id
                 ) SELECT EXISTS (SELECT 1 FROM chain WHERE id = ?2)",
                [other, id],
                |r| r.get(0),
            )?;
            if loops {
                return Err(Error::Invalid(format!("#{id} can't wait on #{other}: that would make a loop")));
            }
            c.execute("INSERT INTO task_waits (task_id, waits_on_id) VALUES (?1, ?2)", [id, other])?;
        }
        c.execute(&format!("UPDATE tasks SET updated_at = {NOW} WHERE id = ?1"), [id])?;
        Ok(true)
    }

    /// What a task waits on, done or not, or with `blocks`, the tasks waiting on it.
    pub fn task_links(&self, id: i64, blocks: bool) -> Result<Vec<TaskLink>> {
        let (this, other) = if blocks { ("waits_on_id", "task_id") } else { ("task_id", "waits_on_id") };
        let sql = format!(
            "SELECT t.id, p.slug, t.title, t.status FROM task_waits w JOIN tasks t ON t.id = w.{other}
             JOIN projects p ON p.id = t.project_id WHERE w.{this} = ?1 ORDER BY t.id"
        );
        let mut stmt = self.conn.prepare_cached(&sql)?;
        let rows = stmt.query_map([id], |r| {
            Ok(TaskLink { id: r.get(0)?, project: r.get(1)?, title: r.get(2)?, status: r.get(3)? })
        })?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    pub fn update_task(&self, id: i64, patch: TaskPatch) -> Result<Task> {
        self.update_task_with_comment(id, patch, None)
    }

    /// The edit and the comment, if any, are one write: both are saved or neither, and a refused
    /// comment or edit changes nothing, not even the change counter.
    pub fn update_task_with_comment(&self, id: i64, patch: TaskPatch, comment: Option<NewComment<'_>>) -> Result<Task> {
        let edit = self.check_edit(&patch)?;
        let comment = comment.as_ref().map(check_handoff).transpose()?;
        self.write(|c| {
            self.apply_edit(c, id, &edit)?;
            if let Some(comment) = &comment {
                Self::insert_comment(c, id, comment.author, comment.body)?;
            }
            Ok(())
        })?;
        self.get_task(id)
    }

    /// Refuses what is wrong with a patch before a write begins, so nothing waits on the lock for it.
    fn check_edit<'a>(&self, patch: &'a TaskPatch) -> Result<Edit<'a>> {
        let title = patch.title.as_deref().map(clean_title).transpose()?;
        let url = patch.url.as_deref().map(clean_url).transpose()?;
        if let Some(s) = &patch.status {
            self.check_status(s)?;
        }
        let tags = patch.tags.as_deref().map(|t| clean_tags(t).join(","));
        let priority = patch.priority.as_deref().map(clean_priority).transpose()?;
        Ok(Edit { patch, title, url, tags, priority })
    }

    /// Runs in the caller's write, on its connection `c`: a later failure there undoes it.
    fn apply_edit(&self, c: &Connection, id: i64, edit: &Edit) -> Result<()> {
        let patch = edit.patch;
        let current = self.get_task(id)?;
        let before: i64 = c.query_row("SELECT coalesce(max(id), 0) FROM events", [], |r| r.get(0))?;
        // Only what the patch changes is written, and only then is the task newer.
        let status = patch.status.as_deref().filter(|s| *s != current.status);
        let position = status.map(|s| Self::end_of_column(c, s, id)).transpose()?;
        // A move ends an escalation, unless the same edit escalates again.
        let escalated = patch.escalated.or(status.map(|_| false));
        // One statement, so one edit is one event: task.moved when the status changes too.
        c.execute(
            &format!(
                "UPDATE tasks SET title = coalesce(?1, title), project_id = coalesce(?2, project_id),
                   human = coalesce(?3, human), tags = coalesce(?4, tags),
                   description = coalesce(?5, description), url = coalesce(?7, url),
                   status = coalesce(?8, status), position = coalesce(?9, position),
                   escalated = coalesce(?10, escalated), priority = iif(?11, ?12, priority), updated_at = {NOW}
                 WHERE id = ?6 AND (coalesce(?1, title), coalesce(?2, project_id), coalesce(?3, human),
                   coalesce(?4, tags), coalesce(?5, description), coalesce(?7, url), coalesce(?8, status),
                   coalesce(?10, escalated), iif(?11, ?12, priority))
                   -- IS NOT, as a priority can be NULL, which <> can't tell apart.
                   IS NOT (title, project_id, human, tags, description, url, status, escalated, priority)"
            ),
            params![
                edit.title,
                patch.project_id,
                patch.human,
                edit.tags,
                patch.description.as_deref().map(str::trim),
                id,
                edit.url,
                status,
                position,
                escalated,
                edit.priority.is_some(),
                edit.priority.flatten()
            ],
        )?;
        // The events trigger doesn't watch escalated: one that changes in place is written here.
        let escalation = status.is_none() && escalated.is_some_and(|e| e != current.escalated);
        let waits = match &patch.waits_on {
            Some(keys) => self.set_waits(c, id, keys)?,
            None => false,
        };
        if escalation || waits {
            // One event per edit: only when the rest of the patch wrote none.
            c.execute(
                "INSERT INTO events (kind, task_id, project_id, project, status_to)
                 SELECT 'task.updated', t.id, t.project_id, p.slug, t.status FROM tasks t
                 JOIN projects p ON p.id = t.project_id
                 WHERE t.id = ?1 AND NOT EXISTS (SELECT 1 FROM events WHERE id > ?2 AND task_id = ?1)",
                [id, before],
            )?;
        }
        Ok(())
    }

    /// In one write: all or nothing, and about 60 times faster than one write per task. Tags are
    /// added and removed, not replaced, so each task keeps its others.
    pub fn update_tasks(&self, ids: &[i64], status: Option<&str>, add_tags: &str, remove_tags: &str) -> Result<()> {
        if let Some(s) = status {
            self.check_status(s)?;
        }
        let (add, remove) = (clean_tags(add_tags), clean_tags(remove_tags));
        self.write(|c| {
            for &id in ids {
                let task = self.get_task(id)?;
                let mut tags = task.tags.clone();
                tags.retain(|t| !remove.contains(t));
                for tag in &add {
                    if !tags.contains(tag) {
                        tags.push(tag.clone());
                    }
                }
                let moved = status.filter(|s| *s != task.status);
                if tags == task.tags && moved.is_none() {
                    continue;
                }
                let position = moved.map(|s| Self::end_of_column(c, s, id)).transpose()?;
                // One statement per task, so one event per task.
                c.execute(
                    &format!(
                        "UPDATE tasks SET tags = ?1, status = coalesce(?2, status), position = coalesce(?3, position),
                           escalated = escalated AND ?2 IS NULL, updated_at = {NOW} WHERE id = ?4"
                    ),
                    params![tags.join(","), moved, position, id],
                )?;
            }
            Ok(())
        })
    }

    pub fn move_task(&self, id: i64, status: &str, before: Option<i64>) -> Result<Task> {
        self.check_status(status)?;
        self.write(|c| self.place(c, id, status, before))?;
        self.get_task(id)
    }

    /// In one write, so nobody sees the group half moved. They keep the order of `ids`.
    pub fn move_tasks(&self, ids: &[i64], status: &str, before: Option<i64>) -> Result<()> {
        self.check_status(status)?;
        let before = before.filter(|b| !ids.contains(b));
        self.write(|c| ids.iter().try_for_each(|&id| self.place(c, id, status, before)))
    }

    fn place(&self, c: &Connection, id: i64, status: &str, before: Option<i64>) -> Result<()> {
        let current = self.get_task(id)?;
        let before = before.filter(|b| *b != id);
        let anchor: Option<(i64, f64)> = match before {
            Some(b) => c
                .query_row("SELECT position FROM tasks WHERE id = ?1 AND status = ?2", params![b, status], |r| r.get(0))
                .optional()?
                .map(|p| (b, p)),
            None => None,
        };
        let position = match anchor {
            None => Self::end_of_column(c, status, id)?,
            Some((before, mut next)) => {
                let prev_of = |next: f64| -> Result<Option<f64>> {
                    Ok(c.query_row(
                        "SELECT max(position) FROM tasks WHERE status = ?1 AND position < ?2 AND id <> ?3",
                        params![status, next, id],
                        |r| r.get(0),
                    )?)
                };
                let mut prev = prev_of(next)?;
                if prev.is_some_and(|p| next - p < 1e-9) {
                    // Out of float room between two neighbours.
                    Self::renumber(c, status)?;
                    next = c.query_row("SELECT position FROM tasks WHERE id = ?1", [before], |r| r.get(0))?;
                    prev = prev_of(next)?;
                }
                match prev {
                    Some(p) => (p + next) / 2.0,
                    None => next - 1.0,
                }
            }
        };
        // Another column makes the task newer and ends its escalation; a new place in the same one doesn't.
        let touched =
            if current.status != status { format!(", escalated = 0, updated_at = {NOW}") } else { String::new() };
        c.execute(
            &format!("UPDATE tasks SET status = ?1, position = ?2{touched} WHERE id = ?3"),
            params![status, position, id],
        )?;
        Ok(())
    }

    fn renumber(c: &Connection, status: &str) -> Result<()> {
        let ids: Vec<i64> = c
            .prepare("SELECT id FROM tasks WHERE status = ?1 ORDER BY position")?
            .query_map([status], |r| r.get(0))?
            .collect::<rusqlite::Result<_>>()?;
        let mut update = c.prepare("UPDATE tasks SET position = ?1 WHERE id = ?2")?;
        for (i, id) in ids.iter().enumerate() {
            update.execute(params![(i + 1) as f64, id])?;
        }
        Ok(())
    }

    #[cfg(test)]
    pub fn next_task(&self, project_id: Option<i64>) -> Result<Option<Task>> {
        self.next_task_matching(project_id, "")
    }

    /// The todo tasks for agents that match `query`, from FROM on, with its values. `hidden` is
    /// what Settings turns off, which agents can't filter through.
    fn agents_todo(&self, project_id: Option<i64>, query: &str, hidden: &[String]) -> Result<(String, Vec<Value>)> {
        let filter = if query.trim().is_empty() {
            Filter::default()
        } else {
            self.add_has_word()?;
            Filter::new(query, 3, hidden)
        };
        let sql = format!(
            "FROM tasks t JOIN projects p ON p.id = t.project_id
             WHERE t.status = ?1 AND t.human = 0 AND (?2 IS NULL OR t.project_id = ?2){}",
            filter.sql
        );
        let mut values: Vec<Value> = vec![STATUSES[0].to_string().into(), project_id.into()];
        values.extend(filter.values.into_iter().map(Value::from));
        Ok((sql, values))
    }

    /// How many tasks `next_task` skips because they wait on others.
    pub fn waiting_in_todo(&self, project_id: Option<i64>, query: &str) -> Result<i64> {
        let (todo, values) = self.agents_todo(project_id, query, &self.hidden_properties()?)?;
        let sql = format!("SELECT count(*) {todo} AND {WAITING}");
        Ok(self.conn.query_row(&sql, rusqlite::params_from_iter(values), |r| r.get(0))?)
    }

    /// Higher priorities first, then the top of the column. With priority hidden in Settings, only
    /// the column, as agents can't see it then.
    pub fn next_task_matching(&self, project_id: Option<i64>, query: &str) -> Result<Option<Task>> {
        let hidden = self.hidden_properties()?;
        let (todo, values) = self.agents_todo(project_id, query, &hidden)?;
        let first = if hidden.iter().any(|p| p == "priority") { "" } else { BY_PRIORITY };
        let to = STATUSES[1];
        let id = self.write(|c| {
            let sql = format!("SELECT t.id {todo} AND NOT {WAITING} ORDER BY {first}t.position LIMIT 1");
            let id: Option<i64> = c.query_row(&sql, rusqlite::params_from_iter(values), |r| r.get(0)).optional()?;
            if let Some(id) = id {
                let position = Self::end_of_column(c, to, id)?;
                c.execute(
                    &format!(
                        "UPDATE tasks SET status = ?1, position = ?2, escalated = 0, updated_at = {NOW}
                         WHERE id = ?3"
                    ),
                    params![to, position, id],
                )?;
            }
            Ok(id)
        })?;
        id.map(|id| self.get_task(id)).transpose()
    }

    pub fn delete_task(&self, id: i64) -> Result<Task> {
        let task = self.get_task(id)?;
        self.conn.execute("DELETE FROM tasks WHERE id = ?1", [id])?;
        Ok(task)
    }

    pub fn delete_tasks(&self, ids: &[i64]) -> Result<()> {
        self.write(|c| {
            for id in ids {
                c.execute("DELETE FROM tasks WHERE id = ?1", [id])?;
            }
            Ok(())
        })
    }

    pub fn list_comments(&self, task_id: i64) -> Result<Vec<Comment>> {
        let mut stmt = self.conn.prepare_cached(&format!("{} WHERE task_id = ?1 ORDER BY id", Self::COMMENT_SELECT))?;
        let rows = stmt.query_map([task_id], Self::comment_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    const COMMENT_SELECT: &str = "SELECT id, task_id, author, body, created_at FROM comments";

    fn comment_row(r: &Row) -> rusqlite::Result<Comment> {
        Ok(Comment { id: r.get(0)?, task_id: r.get(1)?, author: r.get(2)?, body: r.get(3)?, created_at: r.get(4)? })
    }

    pub fn add_comment(&self, task_id: i64, author: &str, body: &str, images: &[String]) -> Result<Comment> {
        let body = body.trim();
        if body.is_empty() && images.is_empty() {
            return Err(Error::Invalid("comment body is empty".into()));
        }
        images.iter().try_for_each(|f| check_image(f))?;
        let author = clean_author(author);
        self.get_task(task_id)?;
        let id = self.write(|c| {
            let id = Self::insert_comment(c, task_id, author, body)?;
            let mut insert = c.prepare("INSERT INTO images (task_id, comment_id, file) VALUES (?1, ?2, ?3)")?;
            for file in images {
                insert.execute(params![task_id, id, file])?;
            }
            Ok(id)
        })?;
        self.get_comment(id)
    }

    /// Runs in the caller's write, on its connection `c`. `author` and `body` are already clean.
    fn insert_comment(c: &Connection, task_id: i64, author: &str, body: &str) -> Result<i64> {
        let sql = "INSERT INTO comments (task_id, author, body) VALUES (?1, ?2, ?3)";
        c.execute(sql, params![task_id, author, body])?;
        Ok(c.last_insert_rowid())
    }

    fn get_comment(&self, id: i64) -> Result<Comment> {
        self.conn
            .query_row(&format!("{} WHERE id = ?1", Self::COMMENT_SELECT), [id], Self::comment_row)
            .optional()?
            .ok_or_else(|| Error::NotFound(format!("no comment {id}")))
    }

    pub fn delete_comment(&self, id: i64) -> Result<Comment> {
        let comment = self.get_comment(id)?;
        self.conn.execute("DELETE FROM comments WHERE id = ?1", [id])?;
        Ok(comment)
    }

    pub fn add_image(&self, task_id: i64, file: &str) -> Result<Image> {
        check_image(file)?;
        self.get_task(task_id)?;
        self.conn.execute("INSERT INTO images (task_id, file) VALUES (?1, ?2)", params![task_id, file])?;
        Ok(Image { id: self.conn.last_insert_rowid(), task_id, comment_id: None, file: file.into() })
    }

    pub fn list_images(&self, task_id: i64) -> Result<Vec<Image>> {
        let mut stmt = self.conn.prepare_cached(&format!("{} WHERE task_id = ?1 ORDER BY id", Self::IMAGE_SELECT))?;
        let rows = stmt.query_map([task_id], Self::image_row)?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    const IMAGE_SELECT: &str = "SELECT id, task_id, comment_id, file FROM images";

    fn image_row(r: &Row) -> rusqlite::Result<Image> {
        Ok(Image { id: r.get(0)?, task_id: r.get(1)?, comment_id: r.get(2)?, file: r.get(3)? })
    }

    pub fn delete_image(&self, id: i64) -> Result<Image> {
        let image = self
            .conn
            .query_row(&format!("{} WHERE id = ?1", Self::IMAGE_SELECT), [id], Self::image_row)
            .optional()?
            .ok_or_else(|| Error::NotFound(format!("no image {id}")))?;
        self.conn.execute("DELETE FROM images WHERE id = ?1", [id])?;
        Ok(image)
    }

    pub fn image_files(&self, of: ImagesOf) -> Result<Vec<String>> {
        let (sql, id) = match of {
            ImagesOf::Tasks(ids) => {
                let mut files = Vec::new();
                for id in ids {
                    files.extend(self.image_files(ImagesOf::Task(id))?);
                }
                return Ok(files);
            }
            ImagesOf::Image(id) => ("SELECT file FROM images WHERE id = ?1", id),
            ImagesOf::Comment(id) => ("SELECT DISTINCT file FROM images WHERE comment_id = ?1", id),
            ImagesOf::Task(id) => ("SELECT DISTINCT file FROM images WHERE task_id = ?1", id),
            ImagesOf::Project(id) => {
                ("SELECT DISTINCT i.file FROM images i JOIN tasks t ON t.id = i.task_id WHERE t.project_id = ?1", id)
            }
        };
        let mut stmt = self.conn.prepare_cached(sql)?;
        let rows = stmt.query_map([id], |r| r.get(0))?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    pub fn unused_images(&self, files: Vec<String>) -> Result<Vec<String>> {
        let mut used = self.conn.prepare_cached("SELECT EXISTS (SELECT 1 FROM images WHERE file = ?1)")?;
        let mut unused = Vec::new();
        for file in files {
            if !used.query_row([&file], |r| r.get::<_, bool>(0))? {
                unused.push(file);
            }
        }
        Ok(unused)
    }
}

pub enum ImagesOf {
    Image(i64),
    Comment(i64),
    Task(i64),
    Tasks(Vec<i64>),
    Project(i64),
}

pub const IMAGE_TYPES: [(&str, &str); 4] =
    [("png", "image/png"), ("jpg", "image/jpeg"), ("gif", "image/gif"), ("webp", "image/webp")];

pub fn tasks(n: i64) -> &'static str {
    if n == 1 { "task" } else { "tasks" }
}

pub fn valid_image_file(file: &str) -> bool {
    match file.split_once('.') {
        Some((hash, ext)) => {
            hash.len() == 16
                && hash.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
                && IMAGE_TYPES.iter().any(|(e, _)| *e == ext)
        }
        None => false,
    }
}

fn check_image(file: &str) -> Result<()> {
    if valid_image_file(file) { Ok(()) } else { Err(Error::Invalid(format!("{file:?} is not an image Kanzo saved"))) }
}

fn valid_slug(s: &str) -> bool {
    let b = s.as_bytes();
    !b.is_empty()
        && b.len() <= 32
        && b[0].is_ascii_alphanumeric()
        && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
}

pub fn short_time(ts: &str) -> String {
    match (ts.get(..10), ts.get(11..16)) {
        (Some(d), Some(t)) => format!("{d} {t} UTC"),
        _ => ts.to_string(),
    }
}

const COMMENT_COUNT: &str = "(SELECT count(*) FROM comments WHERE task_id = t.id)";
const IMAGE_COUNT: &str = "(SELECT count(*) FROM images WHERE task_id = t.id)";
/// Computed, never stored: reopening a task blocks what waits on it again, with nothing to keep in step.
const WAITING: &str = "EXISTS (SELECT 1 FROM task_waits w JOIN tasks b ON b.id = w.waits_on_id
    WHERE w.task_id = t.id AND b.status <> 'done')";
const QUALIFIERS: [&str; 16] = [
    "tag",
    "status",
    "project",
    "title",
    "description",
    "url",
    "comment",
    "id",
    "comments",
    "images",
    "created",
    "updated",
    "priority",
    "is",
    "has",
    "no",
];

/// A query as SQL to add to a WHERE clause: every part must match. A part is a word,
/// `"some words"`, or a qualifier from the README's table, which `-` negates. Anything that
/// isn't a complete qualifier, like `http://x` or `created:soon`, is a word.
#[derive(Default)]
struct Filter {
    sql: String,
    values: Vec<String>,
    first: usize,
}

impl Filter {
    fn new(query: &str, first: usize, hidden: &[String]) -> Self {
        let mut filter = Self { first, ..Default::default() };
        for (part, quoted) in query_parts(query).into_iter().take(10) {
            let part = part.to_lowercase();
            let qualifier = if quoted { None } else { filter.qualifier(&part, hidden) };
            let clause = qualifier.unwrap_or_else(|| filter.word(&part, hidden));
            if !clause.is_empty() {
                filter.sql.push_str(&format!(" AND {clause}"));
            }
        }
        filter
    }

    fn bind(&mut self, value: &str) -> String {
        self.values.push(value.to_string());
        format!("?{}", self.first + self.values.len() - 1)
    }

    fn word(&mut self, word: &str, hidden: &[String]) -> String {
        let seen = |property: &str| !hidden.iter().any(|h| h == property);
        let n = self.bind(word);
        let mut text = String::from("p.slug || '#' || t.id || ' ' || t.title");
        if seen("description") {
            text.push_str(" || ' ' || t.description");
        }
        if seen("tags") {
            text.push_str(" || ' ' || t.tags");
        }
        let mut sql = format!("has_word({text}, {n})");
        if seen("comments") {
            sql.push_str(&format!(" OR t.id IN (SELECT task_id FROM comments WHERE has_word(body, {n}))"));
        }
        format!("({sql})")
    }

    /// `None` when `part` is a plain word. Empty while its value is still being typed.
    fn qualifier(&mut self, part: &str, hidden: &[String]) -> Option<String> {
        let (negated, part) = part.strip_prefix('-').map_or((false, part), |rest| (true, rest));
        let (name, value) = part.split_once(':')?;
        let property = match name {
            "tag" => "tags",
            "comment" => "comments",
            "is" | "has" | "no" => value,
            other => other,
        };
        if hidden.iter().any(|h| h == property) {
            return None;
        }
        if value.is_empty() && QUALIFIERS.contains(&name) {
            return Some(String::new());
        }
        let sql = match (name, value) {
            ("tag", tag) => format!("has_word(',' || t.tags || ',', {})", self.bind(&format!(",{tag},"))),
            ("status", status) => format!("t.status = {}", self.bind(status)),
            ("project", slug) => format!("p.slug = {}", self.bind(slug)),
            ("title", word) => format!("has_word(t.title, {})", self.bind(word)),
            ("description", word) => format!("has_word(t.description, {})", self.bind(word)),
            ("url", word) => format!("has_word(t.url, {})", self.bind(word)),
            ("comment", word) => {
                format!("t.id IN (SELECT task_id FROM comments WHERE has_word(body, {}))", self.bind(word))
            }
            ("id", range) => range_sql("t.id", range, number)?,
            ("comments", range) => range_sql(COMMENT_COUNT, range, number)?,
            ("images", range) => range_sql(IMAGE_COUNT, range, number)?,
            ("created", range) => range_sql("substr(t.created_at, 1, 10)", range, date)?,
            ("updated", range) => range_sql("substr(t.updated_at, 1, 10)", range, date)?,
            // Never NULL, so a task without one matches -priority:P0.
            ("priority", range) => {
                let level = |text: &str| priority_level(text).map(|n| n.to_string());
                format!("coalesce({}, 0)", range_sql("t.priority", range, level)?)
            }
            ("is", "human") => "t.human".to_string(),
            ("is", "waiting") => WAITING.to_string(),
            ("is", "escalated") => "t.escalated".to_string(),
            ("has" | "no", "description") => "t.description <> ''".to_string(),
            ("has" | "no", "tags") => "t.tags <> ''".to_string(),
            ("has" | "no", "url") => "t.url <> ''".to_string(),
            ("has" | "no", "priority") => "t.priority IS NOT NULL".to_string(),
            ("has" | "no", "comments") => format!("{COMMENT_COUNT} > 0"),
            ("has" | "no", "images") => format!("{IMAGE_COUNT} > 0"),
            _ => return None,
        };
        Some(if negated != (name == "no") { format!("NOT ({sql})") } else { sql })
    }
}

/// Splits on spaces outside double quotes, and drops the quotes: `tag:"needs review"` is one
/// part. True when the part starts with a quote, which makes it a word whatever it says.
fn query_parts(query: &str) -> Vec<(String, bool)> {
    let mut parts = Vec::new();
    let (mut part, mut quoted, mut starts_quoted) = (String::new(), false, false);
    for c in query.chars() {
        match c {
            '"' => {
                starts_quoted |= part.is_empty() && !quoted;
                quoted = !quoted;
            }
            c if c.is_whitespace() && !quoted => {
                if !part.is_empty() {
                    parts.push((std::mem::take(&mut part), starts_quoted));
                }
                starts_quoted = false;
            }
            c => part.push(c),
        }
    }
    if !part.is_empty() {
        parts.push((part, starts_quoted));
    }
    parts
}

/// `5`, `>5`, `>=5`, `<5`, `<=5` or `5..9`. `side` only lets through what's safe in SQL.
fn range_sql(column: &str, range: &str, side: fn(&str) -> Option<String>) -> Option<String> {
    if let Some((from, to)) = range.split_once("..") {
        return Some(format!("{column} BETWEEN {} AND {}", side(from)?, side(to)?));
    }
    for op in [">=", "<=", ">", "<"] {
        if let Some(rest) = range.strip_prefix(op) {
            return Some(format!("{column} {op} {}", side(rest)?));
        }
    }
    Some(format!("{column} = {}", side(range)?))
}

fn number(text: &str) -> Option<String> {
    text.parse::<i64>().ok().map(|n| n.to_string())
}

fn date(text: &str) -> Option<String> {
    let dashes = |i: usize, b: u8| if i == 4 || i == 7 { b == b'-' } else { b.is_ascii_digit() };
    (text.len() == 10 && text.bytes().enumerate().all(|(i, b)| dashes(i, b))).then(|| format!("'{text}'"))
}

fn clean_tags(input: &str) -> Vec<String> {
    let mut tags: Vec<String> = Vec::new();
    for tag in input.split(',') {
        let tag = squash(tag).to_lowercase();
        if !tag.is_empty() && !tags.contains(&tag) {
            tags.push(tag);
        }
    }
    tags
}

/// Any site will do, but only http and https: the board makes it a link people click.
fn clean_url(input: &str) -> Result<String> {
    let url = input.trim();
    if url.is_empty() {
        return Ok(String::new());
    }
    let host = url
        .split_once("://")
        .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
        .and_then(|(_, rest)| rest.split(['/', '?', '#']).next());
    if host.is_none_or(str::is_empty) || url.chars().any(char::is_whitespace) {
        return Err(Error::Invalid(format!("URL {url:?} should start with http:// or https://")));
    }
    Ok(url.to_string())
}

fn clean_repo(repo: &str) -> Result<String> {
    repo_from_url(repo).ok_or_else(|| Error::Invalid(format!("repo {:?} should look like owner/repo", repo.trim())))
}

fn squash(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for word in s.split_whitespace() {
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(word);
    }
    out
}

fn clean_title(title: &str) -> Result<String> {
    let title = squash(title);
    if title.is_empty() {
        return Err(Error::Invalid("task title is empty".into()));
    }
    Ok(title)
}

fn clean_author(author: &str) -> &str {
    match author.trim() {
        "" => "me",
        a => a,
    }
}

/// An explicitly passed handoff comment must have something in it and fit `HANDOFF_MAX` bytes.
fn check_handoff<'a>(comment: &NewComment<'a>) -> Result<NewComment<'a>> {
    let body = comment.body.trim();
    if body.is_empty() {
        return Err(Error::Invalid("comment is empty".into()));
    }
    if body.len() > HANDOFF_MAX {
        let (size, most) = (body.len(), HANDOFF_MAX);
        return Err(Error::Invalid(format!("comment is {size} bytes; the most is {most} (16 KiB)")));
    }
    Ok(NewComment { author: clean_author(comment.author), body })
}

/// A patch with its text cleaned and its status checked.
struct Edit<'a> {
    patch: &'a TaskPatch,
    title: Option<String>,
    url: Option<String>,
    tags: Option<String>,
    /// Some(None) clears it.
    priority: Option<Option<i64>>,
}

/// A priority as typed, in a task or a query: `P1`, `p1` or `1` is 1.
fn priority_level(text: &str) -> Option<i64> {
    match text.strip_prefix(['P', 'p']).unwrap_or(text) {
        "0" => Some(0),
        "1" => Some(1),
        "2" => Some(2),
        "3" => Some(3),
        _ => None,
    }
}

/// A task's priority, P0 to P3; empty is none.
fn clean_priority(input: &str) -> Result<Option<i64>> {
    let text = input.trim();
    if text.is_empty() {
        return Ok(None);
    }
    match priority_level(text) {
        Some(n) => Ok(Some(n)),
        None => Err(Error::Invalid(format!("unknown priority {text:?}; use one of: P0 (highest), P1, P2, P3"))),
    }
}

fn parse_task_key(key: &str) -> Result<(Option<String>, i64)> {
    let key = key.trim();
    let (slug, num) = match key.rsplit_once('#') {
        Some((s, n)) => (Some(s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()), n),
        None => (None, key),
    };
    let id = num
        .trim()
        .parse::<i64>()
        .map_err(|_| Error::Invalid(format!("{key:?} is not a task id; use a form like api#12 or 12")))?;
    Ok((slug, id))
}

pub fn repo_from_url(input: &str) -> Option<String> {
    let s = input.trim();
    let (host, path) = if let Some((_, rest)) = s.split_once("://") {
        rest.split_once('/')?
    } else {
        s.split_once(':').unwrap_or(("", s))
    };
    // A repo is its whole path, as GitLab nests them. A pasted page goes past it: on GitLab
    // after /-/, and on GitHub after owner/repo.
    let mut parts: Vec<&str> = path.split("/-/").next()?.split('/').filter(|p| !p.is_empty()).collect();
    if host.to_ascii_lowercase().ends_with("github.com") {
        parts.truncate(2);
    }
    let last = parts.last_mut()?;
    *last = last.strip_suffix(".git").unwrap_or(*last);
    let ok = |p: &str| p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    (parts.len() >= 2 && parts.iter().all(|p| ok(p))).then(|| parts.join("/").to_ascii_lowercase())
}

/// The website a repo's URL names, like gitlab.com, without the user or password. None for
/// owner/repo, and for an SSH alias from ~/.ssh/config, like github-work: it has no dot.
pub fn host_from_url(input: &str) -> Option<String> {
    let s = input.trim();
    let authority = match s.split_once("://") {
        Some((_, rest)) => rest.split('/').next()?,
        None => s.split_once(':')?.0,
    };
    let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
    let host = host.split(':').next()?;
    let ok = host.contains('.') && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.'));
    ok.then(|| host.to_ascii_lowercase())
}

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

    fn store() -> (tempfile::TempDir, Store) {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(&dir.path().join("kanzo.db"), None).unwrap();
        store.migrate().unwrap();
        (dir, store)
    }

    fn titles(tasks: &[Task]) -> Vec<&str> {
        tasks.iter().map(|t| t.title.as_str()).collect()
    }

    fn kinds(s: &Store, since: i64) -> Vec<(String, String, Option<String>, Option<String>)> {
        s.events_since(since, None, 100).unwrap().into_iter().map(|e| (e.kind, e.task, e.from, e.to)).collect()
    }

    #[test]
    fn events_report_what_changed_once() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "first", "").unwrap();
        let key = format!("api#{}", t.id);
        let todo = || Some("todo".to_string());
        assert_eq!(kinds(&s, 0), [("task.created".into(), key.clone(), None, todo())]);

        let start = s.last_event().unwrap();
        s.move_task(t.id, "doing", None).unwrap();
        s.update_task(t.id, TaskPatch { title: Some("renamed".into()), ..Default::default() }).unwrap();
        s.add_comment(t.id, "agent", "[Start] here", &[]).unwrap();
        let events = s.events_since(start, None, 100).unwrap();
        let doing = Some("doing".to_string());
        assert_eq!(
            events.iter().map(|e| (e.kind.as_str(), e.from.clone(), e.to.clone())).collect::<Vec<_>>(),
            [
                ("task.moved", todo(), doing.clone()),
                ("task.updated", None, doing.clone()),
                ("comment.added", None, doing)
            ]
        );
        assert_eq!(events[2].author.as_deref(), Some("agent"));
        assert!(events.windows(2).all(|w| w[0].id < w[1].id));

        let start = s.last_event().unwrap();
        s.move_task(t.id, "doing", None).unwrap();
        assert!(kinds(&s, start).is_empty(), "reordering in the same column is no event");

        s.delete_task(t.id).unwrap();
        assert_eq!(kinds(&s, start), [("task.deleted".into(), key, Some("doing".into()), None)]);
    }

    #[test]
    fn events_filter_by_project_and_limit() {
        let (_dir, s) = store();
        let a = s.create_project("api", "", None).unwrap();
        let b = s.create_project("web", "", None).unwrap();
        for i in 0..3 {
            s.create_task(a.id, &format!("a{i}"), "").unwrap();
            s.create_task(b.id, &format!("b{i}"), "").unwrap();
        }
        let web = s.events_since(0, Some(b.id), 100).unwrap();
        assert_eq!(web.len(), 3);
        assert!(web.iter().all(|e| e.project == "web"));
        let first_two = s.events_since(0, None, 2).unwrap();
        assert_eq!(first_two.len(), 2);
        assert_eq!(s.events_since(first_two[1].id, None, 100).unwrap().len(), 4);
        assert_eq!(s.last_event().unwrap(), s.events_since(0, None, 100).unwrap().last().unwrap().id);
    }

    #[test]
    fn editing_waits_on_is_one_update() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let blocked = s.create_task(p.id, "blocked", "").unwrap();
        let b = s.create_task(p.id, "b", "").unwrap();
        let c = s.create_task(p.id, "c", "").unwrap();
        let key = format!("api#{}", blocked.id);
        let updated = || vec![("task.updated".to_string(), key.clone(), None, Some("todo".to_string()))];

        let start = s.last_event().unwrap();
        s.update_task(blocked.id, waits(&format!("#{}", b.id))).unwrap();
        assert_eq!(kinds(&s, start), updated());

        let start = s.last_event().unwrap();
        s.update_task(blocked.id, waits(&format!("#{}, #{}", b.id, c.id))).unwrap();
        assert_eq!(kinds(&s, start), updated(), "replacing the list is still one event");

        let start = s.last_event().unwrap();
        s.update_task(blocked.id, waits(&format!("#{}, #{}", c.id, b.id))).unwrap();
        assert!(kinds(&s, start).is_empty(), "the same list is no change");

        let start = s.last_event().unwrap();
        let patch = TaskPatch { title: Some("renamed".into()), waits_on: Some(String::new()), ..Default::default() };
        s.update_task(blocked.id, patch).unwrap();
        assert_eq!(kinds(&s, start), updated(), "title and waits on together are one event");

        s.update_task(blocked.id, waits(&format!("#{}", b.id))).unwrap();
        let start = s.last_event().unwrap();
        s.delete_task(b.id).unwrap();
        let after = kinds(&s, start);
        assert_eq!(after.len(), 2);
        assert!(after.iter().any(|e| e.0 == "task.deleted" && e.1 == format!("api#{}", b.id)));
        assert!(after.contains(&updated()[0]), "losing what it waits on is an update");
    }

    #[test]
    fn a_bulk_edit_with_a_move_is_one_event_per_task() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let a = s.create_task(p.id, "a", "").unwrap();
        let b = s.create_task(p.id, "b", "").unwrap();
        let start = s.last_event().unwrap();
        s.update_tasks(&[a.id, b.id], Some("doing"), "bug", "").unwrap();
        let events = kinds(&s, start);
        assert_eq!(events.len(), 2);
        assert!(events.iter().all(|e| e.0 == "task.moved"));
        let start = s.last_event().unwrap();
        s.update_tasks(&[a.id, b.id], None, "", "bug").unwrap();
        assert!(kinds(&s, start).iter().all(|e| e.0 == "task.updated"));
        let start = s.last_event().unwrap();
        s.update_tasks(&[a.id], Some("doing"), "", "").unwrap();
        assert!(kinds(&s, start).is_empty(), "no change, no event");
    }

    #[test]
    fn deleting_a_project_reports_its_tasks_with_its_slug() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t1 = s.create_task(p.id, "one", "").unwrap();
        let t2 = s.create_task(p.id, "two", "").unwrap();
        s.update_task(t2.id, waits(&format!("#{}", t1.id))).unwrap();
        let start = s.last_event().unwrap();
        s.delete_project("api").unwrap();
        let todo = Some("todo".to_string());
        assert_eq!(
            kinds(&s, start),
            [
                ("task.deleted".into(), format!("api#{}", t1.id), todo.clone(), None),
                ("task.deleted".into(), format!("api#{}", t2.id), todo, None),
            ]
        );
    }

    #[test]
    fn only_the_last_events_kept_in_settings_are_kept() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let add = |n: i64| {
            s.conn
                .execute_batch(&format!(
                    "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {n})
                     INSERT INTO events (kind, task_id, project_id, project) SELECT 'task.created', i, {}, 'api' FROM n;",
                    p.id
                ))
                .unwrap();
        };
        add(1050);
        assert_eq!(s.events_kept().unwrap(), 1000);
        assert_eq!(s.event_range().unwrap(), (51, 1050));

        // More is kept from now on, fewer at once.
        s.set_events_kept(2000).unwrap();
        add(1500);
        assert_eq!(s.event_range().unwrap(), (551, 2550));
        s.set_events_kept(300).unwrap();
        assert_eq!(s.event_range().unwrap(), (2251, 2550));
        assert_eq!(s.events_kept().unwrap(), 300);

        assert!(matches!(s.set_events_kept(99), Err(Error::Invalid(_))));
        assert!(matches!(s.set_events_kept(100_001), Err(Error::Invalid(_))));
    }

    #[test]
    fn a_reader_at_zero_starts_over_once_events_were_dropped() {
        let (_dir, s) = store();
        let start = s.events_after(None, None, 500).unwrap();
        assert_eq!(start.last, "0");
        let p = s.create_project("api", "", None).unwrap();
        s.create_task(p.id, "one", "").unwrap();
        assert_eq!(s.events_after(Some("0"), None, 500).unwrap().events.len(), 1);

        s.set_events_kept(100).unwrap();
        for i in 0..100 {
            s.create_task(p.id, &format!("t{i}"), "").unwrap();
        }
        let page = s.events_after(Some("0"), None, 500).unwrap();
        assert!(page.reset && page.events.is_empty());
        assert_ne!(page.last, "0");
    }

    #[test]
    fn migrate_is_idempotent() {
        let (_dir, s) = store();
        s.migrate().unwrap();
        let v: String =
            s.conn.query_row("SELECT value FROM meta WHERE key = 'schema_version'", [], |r| r.get(0)).unwrap();
        assert_eq!(v, MIGRATIONS.len().to_string());
    }

    fn waits(keys: &str) -> TaskPatch {
        TaskPatch { waits_on: Some(keys.into()), ..Default::default() }
    }

    #[test]
    fn next_task_skips_a_task_until_what_it_waits_on_is_done() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let blocked = s.create_task_in(p.id, "blocked", TaskPatch { tags: Some("bug".into()), ..Default::default() });
        let blocked = blocked.unwrap();
        let blocker = s.create_task(p.id, "blocker", "").unwrap();
        let other = s.create_task(p.id, "other", "").unwrap();
        s.move_task(blocker.id, "review", None).unwrap();
        s.update_task(blocked.id, waits(&format!("#{}, api#{}", blocker.id, other.id))).unwrap();
        assert_eq!(s.get_task(blocked.id).unwrap().waiting_on, [blocker.id, other.id]);

        assert_eq!(s.next_task_matching(None, "tag:bug").unwrap().map(|t| t.id), None);
        assert_eq!(s.waiting_in_todo(None, "tag:bug").unwrap(), 1);
        assert_eq!(s.waiting_in_todo(None, "tag:nope").unwrap(), 0);
        assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(other.id));
        s.move_task(other.id, "done", None).unwrap();
        assert_eq!(s.get_task(blocked.id).unwrap().waiting_on, [blocker.id]);
        assert_eq!(s.next_task(None).unwrap().map(|t| t.id), None, "review isn't done");

        s.move_task(blocker.id, "done", None).unwrap();
        assert!(s.get_task(blocked.id).unwrap().waiting_on.is_empty());
        s.move_task(blocker.id, "doing", None).unwrap();
        assert_eq!(s.next_task(None).unwrap().map(|t| t.id), None, "reopening blocks it again");
        s.move_task(blocker.id, "done", None).unwrap();
        assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(blocked.id));
    }

    #[test]
    fn a_loop_or_a_bad_key_changes_nothing() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let [a, b, c] = ["a", "b", "c"].map(|t| s.create_task(p.id, t, "").unwrap().id);
        s.update_task(a, waits(&b.to_string())).unwrap();
        s.update_task(b, waits(&c.to_string())).unwrap();
        for keys in [a.to_string(), format!("{c}"), "999".to_string(), format!("nope#{a}")] {
            assert!(s.update_task(c, waits(&keys)).is_err(), "{keys}");
            assert!(s.get_task(c).unwrap().waiting_on.is_empty(), "{keys}");
        }
        assert!(s.update_task(a, waits(&format!("{c}, {a}"))).is_err());
        assert_eq!(s.get_task(a).unwrap().waiting_on, [b], "a refused list keeps the old one");

        let new = TaskPatch { waits_on: Some("999".into()), ..Default::default() };
        assert!(s.create_task_in(p.id, "bad", new).is_err());
        assert_eq!(s.list_tasks(None, None).unwrap().len(), 3, "a bad key creates no task");

        s.update_task(a, waits("")).unwrap();
        assert!(s.get_task(a).unwrap().waiting_on.is_empty());
    }

    /// All a task edit with a comment could change: the change counter, the task and its comments.
    fn state(s: &Store, id: i64) -> (i64, String, usize) {
        (s.changes().unwrap(), format!("{:?}", s.get_task(id).unwrap()), s.list_comments(id).unwrap().len())
    }

    fn handoff() -> TaskPatch {
        TaskPatch {
            status: Some("review".into()),
            escalated: Some(true),
            tags: Some("handoff".into()),
            ..Default::default()
        }
    }

    fn note(body: &str) -> Option<NewComment<'_>> {
        Some(NewComment { author: "codex", body })
    }

    #[test]
    fn a_handoff_saves_the_edit_the_escalation_and_the_comment_together() {
        let (dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Ship it", "").unwrap();
        let before = s.changes().unwrap();
        let start = s.last_event().unwrap();

        let after = s.update_task_with_comment(t.id, handoff(), note("  Completed: a\nRemaining: b \n")).unwrap();
        assert_eq!((after.status.as_str(), after.escalated, after.comments), ("review", true, 1));
        assert!(!after.human, "the human flag is left as it was");
        assert_eq!(after.tags, ["handoff"]);
        assert!(s.changes().unwrap() > before);
        let kinds: Vec<String> = kinds(&s, start).into_iter().map(|e| e.0).collect();
        assert_eq!(kinds, ["task.moved", "comment.added"]);

        // A new connection, as after a restart, finds all of it.
        let again = Store::open(&dir.path().join("kanzo.db"), None).unwrap();
        let task = again.get_task(t.id).unwrap();
        assert_eq!((task.status.as_str(), task.escalated), ("review", true));
        let comments = again.list_comments(t.id).unwrap();
        assert_eq!(comments.len(), 1);
        assert_eq!((comments[0].author.as_str(), comments[0].body.as_str()), ("codex", "Completed: a\nRemaining: b"));
    }

    #[test]
    fn a_comment_can_go_with_an_edit_that_changes_nothing() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Ship it", "").unwrap();
        let note = Some(NewComment { author: " ", body: "Still on it" });
        s.update_task_with_comment(t.id, TaskPatch::default(), note).unwrap();
        assert_eq!(s.get_task(t.id).unwrap().status, "todo");
        assert_eq!(s.list_comments(t.id).unwrap()[0].author, "me", "a blank author is `me`, as in add_comment");
    }

    #[test]
    fn a_refused_comment_changes_nothing_not_even_the_counter() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Ship it", "").unwrap();
        let before = state(&s, t.id);

        // 8193 characters, but 16386 bytes: the limit counts bytes.
        let wide = "é".repeat(HANDOFF_MAX / 2 + 1);
        assert!(wide.chars().count() < HANDOFF_MAX);
        let long = "x".repeat(HANDOFF_MAX + 1);
        for body in ["", " \n\t ", long.as_str(), wide.as_str()] {
            let err = s.update_task_with_comment(t.id, handoff(), note(body)).unwrap_err();
            assert!(matches!(err, Error::Invalid(_)), "{err}");
            assert_eq!(state(&s, t.id), before, "{} bytes", body.len());
        }

        // Exactly the limit fits, measured after trimming; add_comment keeps its own, no limit.
        let fits = format!("  {}\n", "é".repeat(HANDOFF_MAX / 2));
        s.update_task_with_comment(t.id, TaskPatch::default(), note(&fits)).unwrap();
        assert_eq!(s.list_comments(t.id).unwrap()[0].body.len(), HANDOFF_MAX);
        s.add_comment(t.id, "me", &long, &[]).unwrap();
    }

    #[test]
    fn a_refused_edit_changes_nothing_and_saves_no_comment() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let [a, b] = ["a", "b"].map(|t| s.create_task(p.id, t, "").unwrap().id);
        s.update_task(a, waits(&b.to_string())).unwrap();
        let before = state(&s, b);

        // The status and the escalation are written before the list of waits is refused.
        let patches = [
            TaskPatch { waits_on: Some(a.to_string()), ..handoff() },
            TaskPatch { waits_on: Some("999".into()), ..handoff() },
            TaskPatch { status: Some("nope".into()), ..handoff() },
            TaskPatch { title: Some("  ".into()), ..handoff() },
            TaskPatch { url: Some("not a link".into()), ..handoff() },
        ];
        for patch in patches {
            assert!(s.update_task_with_comment(b, patch, note("Completed: x")).is_err());
            assert_eq!(state(&s, b), before);
        }
        assert!(s.update_task_with_comment(999, handoff(), note("Completed: x")).is_err());
        assert_eq!(state(&s, b), before);
    }

    #[test]
    fn a_comment_that_cannot_be_saved_undoes_the_edit() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let [t, other] = ["t", "other"].map(|t| s.create_task(p.id, t, "").unwrap().id);
        let trigger = "CREATE TRIGGER stop BEFORE INSERT ON comments BEGIN SELECT RAISE(ABORT, 'closed'); END;";
        s.conn.execute_batch(trigger).unwrap();
        let before = state(&s, t);

        let patch = TaskPatch { waits_on: Some(other.to_string()), ..handoff() };
        let err = s.update_task_with_comment(t, patch, note("Completed: x")).unwrap_err();
        assert!(matches!(err, Error::Db(_)) && err.to_string().contains("closed"), "{err}");
        assert_eq!(state(&s, t), before, "status, escalation, tags and waits are undone with it");

        // The connection is still usable, and the same edit without a comment goes through.
        let patch = TaskPatch { waits_on: Some(other.to_string()), ..handoff() };
        let after = s.update_task(t, patch).unwrap();
        assert_eq!((after.status.as_str(), after.escalated, after.waiting_on), ("review", true, vec![other]));
    }

    #[test]
    fn an_escalation_lasts_until_the_task_moves_and_leaves_it_to_agents_after() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Ship it", "").unwrap().id;
        let escalated = || s.get_task(t).unwrap().escalated;

        s.update_task_with_comment(t, handoff(), note("Next step: decide")).unwrap();
        assert!(escalated());
        // Edits that leave it in review keep it, and so does a new place in the same column.
        let rename =
            TaskPatch { title: Some("Ship it now".into()), status: Some("review".into()), ..Default::default() };
        s.update_task(t, rename).unwrap();
        s.move_task(t, "review", None).unwrap();
        s.update_tasks(&[t], Some("review"), "looked", "").unwrap();
        assert!(escalated());

        // Dragged back to todo on the board, it is an agent's task again.
        s.move_task(t, "todo", None).unwrap();
        assert!(!escalated());
        assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(t));
    }

    #[test]
    fn every_way_a_task_moves_ends_its_escalation() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Ship it", "").unwrap().id;
        let escalated = || s.get_task(t).unwrap().escalated;
        let to = |status: &str| TaskPatch { status: Some(status.into()), ..Default::default() };
        let escalate = || s.update_task(t, TaskPatch { escalated: Some(true), ..Default::default() }).unwrap();

        escalate();
        s.update_task(t, to("doing")).unwrap();
        assert!(!escalated(), "update_task");
        escalate();
        s.move_tasks(&[t], "review", None).unwrap();
        assert!(!escalated(), "a group dragged on the board");
        escalate();
        s.update_tasks(&[t], Some("todo"), "", "").unwrap();
        assert!(!escalated(), "a group moved from the selection bar");
        escalate();
        s.next_task(None).unwrap();
        assert!(!escalated(), "next_task");

        // Escalated again by the same edit that moves it, or cleared where it is.
        escalate();
        s.update_task(t, TaskPatch { escalated: Some(true), ..to("review") }).unwrap();
        assert!(escalated());
        s.update_task(t, TaskPatch { escalated: Some(false), ..Default::default() }).unwrap();
        assert!(!escalated());
    }

    #[test]
    fn an_escalation_is_one_event_with_the_rest_of_its_edit() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Ship it", "").unwrap().id;
        let start = s.last_event().unwrap();
        let escalate = |more: TaskPatch| s.update_task(t, TaskPatch { escalated: Some(true), ..more }).unwrap();

        escalate(TaskPatch::default());
        let changes = s.changes().unwrap();
        escalate(TaskPatch::default());
        assert_eq!(s.changes().unwrap(), changes, "already escalated: nothing to write");
        s.update_task(t, TaskPatch { escalated: Some(false), ..Default::default() }).unwrap();
        escalate(TaskPatch { title: Some("renamed".into()), ..Default::default() });
        escalate(TaskPatch { status: Some("review".into()), ..Default::default() });
        s.move_task(t, "todo", None).unwrap();

        let kinds: Vec<String> = kinds(&s, start).into_iter().map(|e| e.0).collect();
        assert_eq!(kinds, ["task.updated", "task.updated", "task.updated", "task.moved", "task.moved"]);
    }

    #[test]
    fn deleting_what_a_task_waits_on_frees_it() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let blocker = s.create_task(p.id, "blocker", "").unwrap();
        s.move_task(blocker.id, "doing", None).unwrap();
        let new = TaskPatch { waits_on: Some(blocker.id.to_string()), ..Default::default() };
        let task = s.create_task_in(p.id, "task", new).unwrap();
        assert_eq!(task.waiting_on, [blocker.id]);
        assert_eq!(s.task_links(blocker.id, true).unwrap()[0].id, task.id);
        assert_eq!(s.task_links(task.id, false).unwrap()[0].id, blocker.id);
        s.delete_task(blocker.id).unwrap();
        assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(task.id));
    }

    #[test]
    fn editing_the_same_list_changes_nothing() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let blocker = s.create_task(p.id, "blocker", "").unwrap();
        let task = s.create_task(p.id, "task", "").unwrap();
        s.update_task(task.id, waits(&blocker.id.to_string())).unwrap();
        let before = s.changes().unwrap();
        s.update_task(task.id, waits(&format!("#{}", blocker.id))).unwrap();
        assert_eq!(s.changes().unwrap(), before);
    }

    #[test]
    fn filters_by_waiting_and_leaves_it_out_of_json_when_empty() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let blocker = s.create_task(p.id, "blocker", "").unwrap();
        let task = s.create_task(p.id, "task", "").unwrap();
        s.update_task(task.id, waits(&blocker.id.to_string())).unwrap();
        assert_eq!(titles(&s.search("is:waiting", None).unwrap()), ["task"]);
        assert_eq!(s.search("is:waiting", None).unwrap()[0].waiting_on, [blocker.id]);
        assert_eq!(s.list_tasks(None, None).unwrap()[1].waiting_on, [blocker.id]);
        assert!(s.list_tasks(None, None).unwrap()[0].waiting_on.is_empty());
        assert_eq!(titles(&s.search("-is:waiting", None).unwrap()), ["blocker"]);
        let json = serde_json::to_value(s.get_task(blocker.id).unwrap()).unwrap();
        assert!(json.get("waiting_on").is_none(), "{json}");
        let json = serde_json::to_value(s.get_task(task.id).unwrap()).unwrap();
        assert_eq!(json["waiting_on"], serde_json::json!([blocker.id]));

        s.set_property("waiting", false).unwrap();
        assert_eq!(s.search_for_agent("is:waiting").unwrap().len(), 0, "a hidden property finds nothing");
    }

    #[test]
    fn changes_many_tasks_at_once_or_not_at_all() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let task = |title, tags: &str| {
            let tags = Some(tags.to_string());
            s.create_task_in(p.id, title, TaskPatch { tags, ..Default::default() }).unwrap().id
        };
        let (a, b, c) = (task("a", "bug, ui"), task("b", "ui"), task("c", "keep"));

        s.update_tasks(&[a, b], Some("doing"), "New, bug", "ui").unwrap();
        let tags = |id| s.get_task(id).unwrap().tags;
        assert_eq!(
            (tags(a), tags(b), tags(c)),
            (vec!["bug".into(), "new".into()], vec!["new".into(), "bug".into()], vec!["keep".into()])
        );
        assert_eq!(titles(&s.list_tasks(None, Some("doing")).unwrap()), ["a", "b"], "they keep their order");

        let before = s.changes().unwrap();
        assert!(s.update_tasks(&[c, 999], Some("done"), "x", "").is_err());
        assert!(s.update_tasks(&[c], Some("nope"), "", "").is_err());
        assert_eq!(
            (s.get_task(c).unwrap().status.as_str(), tags(c), s.changes().unwrap()),
            ("todo", vec!["keep".into()], before)
        );

        let before = s.get_task(a).unwrap();
        s.update_tasks(&[a], Some("doing"), "bug", "absent").unwrap();
        assert_eq!(s.get_task(a).unwrap().position, before.position, "nothing to change moves nothing");

        s.delete_tasks(&[a, 999, b]).unwrap();
        assert_eq!(titles(&s.list_tasks(None, None).unwrap()), ["c"]);
    }

    #[test]
    fn projects_keep_the_order_they_are_moved_to() {
        let (_dir, s) = store();
        for slug in ["a", "b", "c", "d"] {
            s.create_project(slug, "", None).unwrap();
        }
        let order = || s.list_projects().unwrap().into_iter().map(|p| p.slug).collect::<Vec<_>>().join("");
        let move_to = |slug, before| s.move_project(slug, before).unwrap();
        assert_eq!(order(), "abcd", "never moved: by slug");

        move_to("c", Some("a"));
        assert_eq!(order(), "cabd", "first");
        let positioned: i64 = s.conn.query_row("SELECT count(position) FROM projects", [], |r| r.get(0)).unwrap();
        assert_eq!(positioned, 1, "only the moved project needed a position");

        move_to("d", Some("b"));
        assert_eq!(order(), "cadb", "among projects with no position");
        move_to("c", None);
        assert_eq!(order(), "adbc", "last");
        move_to("b", Some("d"));
        assert_eq!(order(), "abdc", "between two");
        move_to("b", Some("b"));
        assert_eq!(order(), "abdc", "onto itself");

        s.create_project("0new", "", None).unwrap();
        assert_eq!(order(), "abdc0new", "a new project goes last");
        move_to("0new", Some("b"));
        assert_eq!(order(), "a0newbdc");

        for _ in 0..80 {
            // Out of float room between two neighbours: numbers them again.
            move_to("c", Some("b"));
            move_to("d", Some("b"));
        }
        assert_eq!(order(), "a0newcdb");
        assert!(s.move_project("a", Some("nope")).is_err());
        assert!(s.move_project("nope", None).is_err());
    }

    #[test]
    fn keeps_only_the_newest_done_tasks() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        s.create_task(p.id, "open", "").unwrap();
        for title in ["d1", "d2", "d3", "d4"] {
            let t = s.create_task(p.id, title, "").unwrap();
            s.move_task(t.id, "done", None).unwrap();
        }
        let (tasks, hidden) = s.list_tasks_keeping_done(None, None, Some(2)).unwrap();
        assert_eq!((titles(&tasks), hidden), (vec!["open", "d3", "d4"], 2));
        let (tasks, hidden) = s.list_tasks_keeping_done(Some(p.id), Some("done"), Some(0)).unwrap();
        assert_eq!((tasks.len(), hidden), (0, 4));
        assert_eq!(s.list_tasks_keeping_done(None, Some("todo"), Some(0)).unwrap().1, 0);
        let (all, hidden) = s.list_tasks_keeping_done(None, None, None).unwrap();
        assert_eq!((titles(&all), hidden), (vec!["open", "d1", "d2", "d3", "d4"], 0));
    }

    #[test]
    fn opens_a_board_from_a_newer_kanzo_when_it_can() {
        let (_dir, s) = store();
        let set = |version: usize, compatible: usize| {
            s.conn
                .execute_batch(&format!(
                    "UPDATE meta SET value = '{version}' WHERE key = 'schema_version';
                     UPDATE meta SET value = '{compatible}' WHERE key = 'compatible';"
                ))
                .unwrap();
        };
        let newer = MIGRATIONS.len() + 1;
        set(newer, MIGRATIONS.len());
        s.migrate().unwrap();
        s.create_project("api", "", None).unwrap();
        let v: String =
            s.conn.query_row("SELECT value FROM meta WHERE key = 'schema_version'", [], |r| r.get(0)).unwrap();
        assert_eq!(v, newer.to_string());
        set(newer, newer);
        assert!(s.migrate().unwrap_err().to_string().contains("kanzo update"));
    }

    #[test]
    fn projects() {
        let (_dir, s) = store();
        let p = s.create_project("API", "API server", Some("https://github.com/Me/Api.git")).unwrap();
        assert_eq!((p.slug.as_str(), p.repos.as_slice()), ("api", ["me/api".to_string()].as_slice()));
        assert_eq!(s.find_project("me/api").unwrap().id, p.id);
        assert_eq!(s.project_by_repo("git@github.com:me/api.git").unwrap().unwrap().id, p.id);
        assert!(s.create_project("api", "", None).unwrap_err().to_string().contains("already exists"));
        assert!(s.create_project("web", "", Some("me/api")).unwrap_err().to_string().contains("already linked"));
        assert!(s.create_project("bad slug", "", None).is_err());
        let web = s.create_project("web", "", None).unwrap();
        assert_eq!((web.name.as_str(), web.color.as_deref()), ("web", None));
        assert_eq!(s.set_project_color("web", "teal").unwrap().color.as_deref(), Some("teal"));
        assert!(s.set_project_color("web", "#ff0000").is_err());
        let renamed = s.rename_project("web", "  Web   site ").unwrap();
        assert_eq!((renamed.slug.as_str(), renamed.name.as_str()), ("web", "Web site"));
        assert!(s.rename_project("web", "  ").is_err());
        assert!(s.find_project("nope").unwrap_err().to_string().contains("api, web"));
    }

    #[test]
    fn many_repos_per_project() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", Some("me/api")).unwrap();
        s.create_project("web", "", None).unwrap();
        assert_eq!(s.link_repo("api", "https://github.com/Me/API-docs.git").unwrap().repos, ["me/api", "me/api-docs"]);
        assert_eq!(s.find_project("me/api-docs").unwrap().id, api.id);
        assert_eq!(s.link_repo("api", "me/api").unwrap().repos.len(), 2, "linking twice changes nothing");
        assert!(s.link_repo("web", "me/api-docs").unwrap_err().to_string().contains("already linked to project api"));
        assert!(s.link_repo("api", "not a repo").is_err());
        assert_eq!(s.unlink_repo("api", "me/api").unwrap().repos, ["me/api-docs"]);
        assert!(s.project_by_repo("me/api").unwrap().is_none());
        assert!(s.unlink_repo("api", "me/api").is_err());
        s.delete_project("api").unwrap();
        assert_eq!(s.link_repo("web", "me/api-docs").unwrap().repos, ["me/api-docs"]);
    }

    #[test]
    fn search() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let web = s.create_project("web", "", None).unwrap();
        let login = s.create_task(api.id, "Fix login", "Users loop on /login").unwrap();
        let old = s.create_task(web.id, "Login page copy", "").unwrap();
        s.update_task(old.id, TaskPatch { status: Some("done".into()), ..Default::default() }).unwrap();
        let other = s.create_task(web.id, "Pricing 100%", "").unwrap();
        s.update_task(other.id, TaskPatch { tags: Some("ui".into()), ..Default::default() }).unwrap();
        let titles = |q: &str| s.search(q, Some(10)).unwrap().into_iter().map(|t| t.title).collect::<Vec<_>>();
        assert_eq!(titles("LOGIN"), ["Fix login", "Login page copy"], "any project, open first, done too");
        assert_eq!(titles("login api"), ["Fix login"], "every word must match, the project too");
        assert_eq!(titles(&format!("web#{}", other.id)), ["Pricing 100%"], "by key");
        assert_eq!(titles("ui"), ["Pricing 100%"], "by tag");
        s.add_comment(old.id, "you", "Needs the new logo", &[]).unwrap();
        assert_eq!(titles("logo login"), ["Login page copy"], "by comment, with the task's own words");
        assert_eq!(titles("100%"), ["Pricing 100%"], "% is a plain character");
        assert!(titles("nothing-like-this").is_empty());
        assert_eq!(s.search("", Some(10)).unwrap().len(), 3, "no words: the latest changes");
        assert_eq!(s.search("login", Some(1)).unwrap()[0].id, login.id);
    }

    #[test]
    fn filter_by_any_property() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let web = s.create_project("web", "", None).unwrap();
        let patch = |tags: &str, status: &str| TaskPatch {
            tags: Some(tags.into()),
            status: Some(status.into()),
            description: Some("Users loop on /login".into()),
            ..Default::default()
        };
        let login = s.create_task_in(api.id, "Fix login", patch("Bug, needs review", "doing")).unwrap();
        let debug = s.create_task_in(api.id, "Debug tools", patch("debugger", "todo")).unwrap();
        let human = s.create_task(web.id, "Call the Bank", "").unwrap();
        s.update_task(
            human.id,
            TaskPatch { human: Some(true), url: Some("https://x.dev/1".into()), ..Default::default() },
        )
        .unwrap();
        s.add_comment(debug.id, "you", "Needs the new logo", &[]).unwrap();
        s.add_comment(debug.id, "you", "Soon", &[]).unwrap();
        s.conn.execute("INSERT INTO images (task_id, file) VALUES (?1, 'a.png')", [human.id]).unwrap();
        s.conn
            .execute("UPDATE tasks SET created_at = '2026-01-15T10:00:00Z', updated_at = '2026-03-01T10:00:00Z'", [])
            .unwrap();
        s.conn.execute("UPDATE tasks SET created_at = '2026-02-01T10:00:00Z' WHERE id = ?1", [login.id]).unwrap();

        let ids = |q: &str| {
            let mut ids: Vec<i64> = s.search(q, None).unwrap().into_iter().map(|t| t.id).collect();
            ids.sort_unstable();
            ids
        };
        let (l, d, h) = (login.id, debug.id, human.id);
        for (q, want) in [
            ("tag:bug", vec![l]),
            ("TAG:BUG", vec![l]),
            ("tag:debug", vec![]),
            ("tag:\"needs review\"", vec![l]),
            ("-tag:bug", vec![d, h]),
            ("status:doing", vec![l]),
            ("status:DOING", vec![l]),
            ("project:api", vec![l, d]),
            ("-project:api", vec![h]),
            ("title:login", vec![l]),
            ("title:loop", vec![]),
            ("description:loop", vec![l, d]),
            ("url:x.dev", vec![h]),
            ("comment:logo", vec![d]),
            (&format!("id:{l}"), vec![l]),
            (&format!("id:>{l}"), vec![d, h]),
            (&format!("id:{l}..{d}"), vec![l, d]),
            ("comments:2", vec![d]),
            ("comments:>=1", vec![d]),
            ("comments:<1", vec![l, h]),
            ("images:1", vec![h]),
            ("created:2026-02-01", vec![l]),
            ("created:<2026-02-01", vec![d, h]),
            ("created:>=2026-02-01", vec![l]),
            ("created:2026-01-01..2026-01-31", vec![d, h]),
            ("updated:2026-03-01", vec![l, d, h]),
            ("is:human", vec![h]),
            ("-is:human", vec![l, d]),
            ("has:url", vec![h]),
            ("no:url", vec![l, d]),
            ("-has:url", vec![l, d]),
            ("-no:url", vec![h]),
            ("has:tags", vec![l, d]),
            ("has:description", vec![l, d]),
            ("has:comments", vec![d]),
            ("no:images", vec![l, d]),
            ("tag:bug status:doing", vec![l]),
            ("tag:bug status:todo", vec![]),
            ("project:api fix", vec![l]),
            ("project:api -status:doing", vec![d]),
            // Being typed: filters nothing yet.
            ("tag:", vec![l, d, h]),
            ("-status:", vec![l, d, h]),
            ("has:", vec![l, d, h]),
            // Not a complete qualifier: a word.
            ("created:soon", vec![]),
            ("comments:many", vec![]),
            ("is:nothing", vec![]),
            ("has:nothing", vec![]),
            ("http://x.dev", vec![]),
            ("-login", vec![]),
            // Quotes make a phrase, or text that only looks like a qualifier.
            ("\"loop on\"", vec![l, d]),
            ("\"tag:bug\"", vec![]),
        ] {
            assert_eq!(ids(q), want, "{q}");
        }
        s.update_task(l, TaskPatch { description: Some("status:doing is the text".into()), ..Default::default() })
            .unwrap();
        assert_eq!(ids("\"status:doing\""), [l]);
    }

    #[test]
    fn is_escalated_finds_what_agents_handed_to_the_user() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let plain = s.create_task(api.id, "Plain", "").unwrap().id;
        let handed = s.create_task(api.id, "Handed over", "").unwrap().id;
        let escalate = TaskPatch { status: Some("review".into()), escalated: Some(true), ..Default::default() };
        s.update_task(handed, escalate).unwrap();
        let ids = |q: &str| s.search(q, None).unwrap().iter().map(|t| t.id).collect::<Vec<_>>();
        assert_eq!((ids("is:escalated"), ids("-is:escalated")), (vec![handed], vec![plain]));
        s.move_task(handed, "todo", None).unwrap();
        assert!(ids("is:escalated").is_empty(), "a move ends it");
    }

    #[test]
    fn priority_filters_take_a_level_or_a_range() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let task = |title: &str, priority: Option<&str>| {
            let patch = TaskPatch { priority: priority.map(String::from), ..Default::default() };
            s.create_task_in(api.id, title, patch).unwrap().id
        };
        let (a, b, c, d) = (task("a", Some("P0")), task("b", Some("P1")), task("c", Some("P3")), task("d", None));
        let ids = |q: &str| {
            let mut ids: Vec<i64> = s.search(q, None).unwrap().iter().map(|t| t.id).collect();
            ids.sort();
            ids
        };
        for (q, want) in [
            ("priority:P0", vec![a]),
            ("priority:p1", vec![b]),
            ("priority:3", vec![c]),
            ("priority:<=P1", vec![a, b]),
            ("priority:>P0", vec![b, c]),
            ("priority:P1..P3", vec![b, c]),
            ("-priority:P0", vec![b, c, d]),
            ("-priority:<P3", vec![c, d]),
            ("has:priority", vec![a, b, c]),
            ("no:priority", vec![d]),
            ("priority:", vec![a, b, c, d]),
            ("priority:P4", vec![]),
            ("priority:high", vec![]),
        ] {
            assert_eq!(ids(q), want, "{q}");
        }

        s.set_property("priority", false).unwrap();
        assert!(s.search_for_agent("priority:P0").unwrap().is_empty(), "agents can't filter through it hidden");
        assert_eq!(ids("priority:P0"), [a], "the board still can");
    }

    #[test]
    fn filter_values_cannot_change_the_sql() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        s.create_task(api.id, "Keep me", "").unwrap();
        for q in [
            "tag:x'OR'1'='1",
            "created:2026-01-01'OR'1'='1",
            "created:'OR'1'='1'--",
            "id:1)OR(1=1",
            "comments:1;DROP",
            "created:2026-01-0'",
            "title:'",
            "status:'--",
            "priority:1'OR'1",
        ] {
            assert!(s.search(q, None).unwrap().is_empty(), "{q}");
        }
        assert_eq!(s.search("", None).unwrap().len(), 1);
    }

    #[test]
    fn next_task_takes_the_top_match_and_never_a_human_one() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let tagged = |title: &str, human: bool| {
            let patch = TaskPatch { tags: Some("billing".into()), human: Some(human), ..Default::default() };
            s.create_task_in(api.id, title, patch).unwrap();
        };
        s.create_task(api.id, "Not in the epic", "").unwrap();
        tagged("For the user", true);
        tagged("First in the epic", false);
        tagged("Second in the epic", false);

        let next = |q: &str| s.next_task_matching(Some(api.id), q).unwrap().map(|t| t.title);
        assert_eq!(next("is:human"), None);
        assert_eq!(next("tag:nope"), None);
        assert_eq!(next("tag:billing").as_deref(), Some("First in the epic"));
        assert_eq!(next("TAG:billing second").as_deref(), Some("Second in the epic"));
        assert_eq!(next("tag:billing"), None, "the human one stays");
        assert_eq!(next("  ").as_deref(), Some("Not in the epic"));
    }

    #[test]
    fn agents_cannot_filter_through_hidden_properties() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let patch = TaskPatch { tags: Some("secret".into()), ..Default::default() };
        let t = s.create_task_in(api.id, "Plain title", patch).unwrap();
        s.add_comment(t.id, "you", "whisper", &[]).unwrap();
        let found = |q: &str| s.search_for_agent(q).unwrap().len();
        assert_eq!((found("tag:secret"), found("secret"), found("comment:whisper"), found("whisper")), (1, 1, 1, 1));

        s.set_property("tags", false).unwrap();
        s.set_property("comments", false).unwrap();
        assert_eq!((found("tag:secret"), found("secret"), found("comment:whisper"), found("whisper")), (0, 0, 0, 0));
        assert_eq!(found("has:tags"), 0);
        assert_eq!(s.next_task_matching(None, "tag:secret").unwrap().map(|t| t.id), None);
        assert_eq!(found("plain"), 1, "what stays visible still matches");
        assert_eq!(s.search("tag:secret", None).unwrap().len(), 1, "the board still sees them");
    }

    #[test]
    fn search_ignores_case_beyond_ascii() {
        let (_dir, s) = store();
        let web = s.create_project("web", "", None).unwrap();
        s.create_task(web.id, "Über café", "").unwrap();
        for q in ["über", "ÜBER", "Über", "café", "CAFÉ", "web#1"] {
            assert_eq!(s.search(q, None).unwrap().len(), 1, "{q}");
        }
    }

    #[test]
    fn images() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Bug", "").unwrap();
        let shot = "0123456789abcdef.png".to_string();
        let on_task = s.add_image(t.id, &shot).unwrap();
        assert!(s.add_image(t.id, "../../etc/passwd").is_err());
        assert!(s.add_image(t.id + 1, &shot).is_err());
        let c = s.add_comment(t.id, "me", "", &["fedcba9876543210.jpg".into(), shot.clone()]).unwrap();
        assert!(s.add_comment(t.id, "me", "x", &["evil.svg".into()]).is_err());
        let all: Vec<_> = s.list_images(t.id).unwrap().into_iter().map(|i| (i.comment_id, i.file)).collect();
        assert_eq!(
            all,
            [(None, shot.clone()), (Some(c.id), "fedcba9876543210.jpg".into()), (Some(c.id), shot.clone())]
        );
        assert_eq!(s.image_files(ImagesOf::Task(t.id)).unwrap(), [shot.clone(), "fedcba9876543210.jpg".into()]);
        assert_eq!(s.image_files(ImagesOf::Project(p.id)).unwrap().len(), 2);
        s.delete_image(on_task.id).unwrap();
        assert!(s.unused_images(vec![shot.clone()]).unwrap().is_empty());
        let files = s.image_files(ImagesOf::Comment(c.id)).unwrap();
        s.delete_comment(c.id).unwrap();
        assert!(s.list_images(t.id).unwrap().is_empty());
        assert_eq!(s.unused_images(files).unwrap(), ["fedcba9876543210.jpg".to_string(), shot.clone()]);
        assert!(valid_image_file("6fec521a01297ab5.webp"));
        assert!(!valid_image_file("6FEC521A01297AB5.png") && !valid_image_file("6fec521a01297ab5.svg"));
    }

    #[test]
    fn migration_moves_repos_to_their_own_table() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("kanzo.db");
        {
            let c = Connection::open(&path).unwrap();
            c.execute_batch("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)").unwrap();
            for sql in &MIGRATIONS[..3] {
                c.execute_batch(sql).unwrap();
            }
            c.execute_batch(
                "INSERT INTO meta VALUES ('schema_version', '3');
                 INSERT INTO projects (slug, name, repo) VALUES ('api', 'api', 'me/api'), ('web', 'web', NULL);",
            )
            .unwrap();
        }
        let s = Store::open(&path, None).unwrap();
        s.migrate().unwrap();
        assert_eq!(s.find_project("api").unwrap().repos, ["me/api"]);
        assert!(s.find_project("web").unwrap().repos.is_empty());
        assert_eq!(s.find_project("me/api").unwrap().slug, "api");
    }

    #[test]
    fn task_lifecycle() {
        let (_dir, s) = store();
        let p = s.create_project("api", "API", None).unwrap();
        let t = s.create_task(p.id, "  Fix   login ", "Steps:\n1. log in\n").unwrap();
        assert_eq!((t.title.as_str(), t.status.as_str(), t.key()), ("Fix login", "todo", format!("api#{}", t.id)));
        assert_eq!(s.find_task(&t.key()).unwrap().id, t.id);
        assert!(s.find_task(&format!("web#{}", t.id)).is_err());

        let t = s
            .update_task(
                t.id,
                TaskPatch { status: Some("review".into()), title: Some("Fix login bug".into()), ..Default::default() },
            )
            .unwrap();
        assert_eq!((t.title.as_str(), t.status.as_str()), ("Fix login bug", "review"));
        assert!(s.update_task(t.id, TaskPatch { status: Some("nope".into()), ..Default::default() }).is_err());
        assert!(s.update_task(t.id, TaskPatch { title: Some("  ".into()), ..Default::default() }).is_err());
        let web = s.create_project("web", "", None).unwrap();
        let moved = s.update_task(t.id, TaskPatch { project_id: Some(web.id), ..Default::default() }).unwrap();
        assert_eq!((moved.key(), moved.status.as_str()), (format!("web#{}", t.id), "review"));
        let t = s.update_task(t.id, TaskPatch { project_id: Some(p.id), ..Default::default() }).unwrap();

        s.add_comment(t.id, "claude-code", "Done, see PR", &[]).unwrap();
        s.add_comment(t.id, "", "thanks", &[]).unwrap();
        let comments = s.list_comments(t.id).unwrap();
        assert_eq!(comments.iter().map(|c| c.author.as_str()).collect::<Vec<_>>(), ["claude-code", "me"]);
        assert!(s.add_comment(t.id, "me", " ", &[]).is_err());
        assert_eq!(s.get_task(t.id).unwrap().comments, 2);
        let tagged =
            s.update_task(t.id, TaskPatch { tags: Some(" Bug, UI,bug ,, needs  review".into()), ..Default::default() });
        assert_eq!(tagged.unwrap().tags, ["bug", "ui", "needs review"]);
        assert!(
            s.update_task(t.id, TaskPatch { tags: Some(" , ".into()), ..Default::default() }).unwrap().tags.is_empty()
        );
        let gone = s.add_comment(t.id, "me", "typo", &[]).unwrap();
        assert_eq!(s.delete_comment(gone.id).unwrap().body, "typo");
        assert!(s.delete_comment(gone.id).is_err());
        assert_eq!(s.get_task(t.id).unwrap().comments, 2);
        assert_eq!(s.find_project("api").unwrap().open, 1);

        s.delete_task(t.id).unwrap();
        assert!(s.get_task(t.id).is_err());
        let orphans: i64 = s.conn.query_row("SELECT count(*) FROM comments", [], |r| r.get(0)).unwrap();
        assert_eq!(orphans, 0);
        // Ids are never reused, so api#12 always means the same task.
        let t2 = s.create_task(p.id, "Another", "").unwrap();
        assert!(t2.id > t.id);
    }

    #[test]
    fn delete_project_removes_its_tasks_and_comments() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", Some("me/api")).unwrap();
        let web = s.create_project("web", "", None).unwrap();
        let t = s.create_task(api.id, "a", "").unwrap();
        s.add_comment(t.id, "me", "hi", &[]).unwrap();
        let kept = s.create_task(web.id, "b", "").unwrap();
        s.add_comment(kept.id, "me", "hello", &[]).unwrap();

        assert_eq!(s.delete_project("api").unwrap().id, api.id);
        assert!(s.find_project("api").is_err());
        assert!(s.get_task(t.id).is_err());
        let count = |table: &str| -> i64 {
            s.conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0)).unwrap()
        };
        assert_eq!((count("projects"), count("tasks"), count("comments")), (1, 1, 1));
        assert!(s.delete_project("api").is_err());
        s.create_project("api", "", Some("me/api")).unwrap();
    }

    #[test]
    fn ordering_and_moves() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let a = s.create_task(p.id, "a", "").unwrap();
        let b = s.create_task(p.id, "b", "").unwrap();
        let c = s.create_task(p.id, "c", "").unwrap();
        assert_eq!(titles(&s.list_tasks(Some(p.id), None).unwrap()), ["a", "b", "c"]);

        s.move_task(c.id, "todo", Some(a.id)).unwrap();
        assert_eq!(titles(&s.list_tasks(None, Some("todo")).unwrap()), ["c", "a", "b"]);
        s.move_task(c.id, "todo", None).unwrap();
        assert_eq!(titles(&s.list_tasks(None, Some("todo")).unwrap()), ["a", "b", "c"]);
        s.move_task(a.id, "doing", None).unwrap();
        s.move_task(b.id, "doing", Some(a.id)).unwrap();
        assert_eq!(titles(&s.list_tasks(None, None).unwrap()), ["c", "b", "a"]);

        // Many inserts at the same spot run out of float room and trigger a renumber.
        let mut moving = [b.id, c.id];
        for _ in 0..80 {
            s.move_task(moving[0], "doing", Some(a.id)).unwrap();
            moving.swap(0, 1);
        }
        assert_eq!(titles(&s.list_tasks(None, Some("doing")).unwrap()).last(), Some(&"a"));
        assert!(s.move_task(a.id, "nope", None).is_err());
    }

    #[test]
    fn a_task_keeps_its_priority_until_it_is_cleared() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let set = |id: i64, priority: &str| {
            s.update_task(id, TaskPatch { priority: Some(priority.into()), ..Default::default() })
        };
        let urgent = TaskPatch { priority: Some(" P1 ".into()), ..Default::default() };
        let t = s.create_task_in(p.id, "Fix login", urgent).unwrap();
        assert_eq!(t.priority, Some(1));
        let later = s.create_task(p.id, "Later", "").unwrap();
        assert_eq!(later.priority, None);
        let changes = s.changes().unwrap();
        set(later.id, " ").unwrap();
        assert_eq!(s.changes().unwrap(), changes, "clearing none writes nothing");

        assert_eq!(set(t.id, "p3").unwrap().priority, Some(3));
        assert_eq!(set(t.id, "0").unwrap().priority, Some(0));
        let renamed = s.update_task(t.id, TaskPatch { title: Some("Fix the login".into()), ..Default::default() });
        assert_eq!(renamed.unwrap().priority, Some(0), "an edit without it keeps it");
        assert_eq!(set(t.id, "").unwrap().priority, None);
        assert_eq!(set(t.id, "P2").unwrap().priority, Some(2));

        let before = (s.changes().unwrap(), s.get_task(t.id).unwrap().updated_at);
        for wrong in ["P4", "-1", "high", "P", "p1x"] {
            let err = set(t.id, wrong).unwrap_err();
            assert!(err.to_string().contains("P0 (highest)"), "{wrong}: {err}");
        }
        set(t.id, "P2").unwrap();
        assert_eq!((s.changes().unwrap(), s.get_task(t.id).unwrap().updated_at), before, "nothing to write");
        let bad = TaskPatch { priority: Some("urgent".into()), ..Default::default() };
        assert!(s.create_task_in(p.id, "Nope", bad).is_err());
    }

    #[test]
    fn a_new_priority_is_one_task_updated_event_and_none_is_left_out_of_the_json() {
        let (_dir, s) = store();
        let p = s.create_project("api", "", None).unwrap();
        let t = s.create_task(p.id, "Fix login", "").unwrap();
        let json = serde_json::to_value(&t).unwrap();
        assert!(json.get("priority").is_none(), "{json}");

        let start = s.last_event().unwrap();
        let t = s.update_task(t.id, TaskPatch { priority: Some("P0".into()), ..Default::default() }).unwrap();
        assert_eq!(serde_json::to_value(&t).unwrap()["priority"], 0);
        s.update_task(t.id, TaskPatch { priority: Some("".into()), ..Default::default() }).unwrap();
        let moved = TaskPatch { priority: Some("P1".into()), status: Some("doing".into()), ..Default::default() };
        s.update_task(t.id, moved).unwrap();
        let kinds: Vec<String> = kinds(&s, start).into_iter().map(|e| e.0).collect();
        assert_eq!(kinds, ["task.updated", "task.updated", "task.moved"]);
    }

    #[test]
    fn next_task_takes_higher_priorities_first_and_none_as_p2() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let task = |title: &str, priority: &str| {
            let patch = TaskPatch { priority: Some(priority.into()), ..Default::default() };
            s.create_task_in(api.id, title, patch).unwrap();
        };
        // In the column's order, top first.
        task("low", "P3");
        task("plain", "");
        task("normal", "P2");
        task("urgent", "P0");
        task("soon", "P1");
        task("urgent too", "P0");
        let human = TaskPatch { priority: Some("P0".into()), human: Some(true), ..Default::default() };
        s.create_task_in(api.id, "for the user", human).unwrap();
        let mut taken = Vec::new();
        while let Some(t) = s.next_task(None).unwrap() {
            taken.push(t.title);
        }
        assert_eq!(taken, ["urgent", "urgent too", "soon", "plain", "normal", "low"]);
    }

    #[test]
    fn next_task_keeps_to_the_column_while_priority_is_hidden() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        s.create_task(api.id, "top", "").unwrap();
        let urgent = TaskPatch { priority: Some("P0".into()), ..Default::default() };
        s.create_task_in(api.id, "urgent", urgent).unwrap();
        s.set_property("priority", false).unwrap();
        assert_eq!(s.next_task(None).unwrap().unwrap().title, "top");
        s.set_property("priority", true).unwrap();
        assert_eq!(s.next_task(None).unwrap().unwrap().title, "urgent");
    }

    #[test]
    fn next_task_takes_top_todo() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let web = s.create_project("web", "", None).unwrap();
        s.create_task(web.id, "web first", "").unwrap();
        let changes = s.changes().unwrap();
        let patch = TaskPatch { human: Some(true), tags: Some("Bug, bug".into()), ..Default::default() };
        let human = s.create_task_in(api.id, "Call the bank", patch).unwrap();
        assert!(human.human && human.tags == ["bug"] && s.changes().unwrap() == changes + 1, "all in one write");
        s.create_task(api.id, "api first", "").unwrap();
        s.create_task(api.id, "api second", "").unwrap();

        let t = s.next_task(Some(api.id)).unwrap().unwrap();
        assert_eq!((t.title.as_str(), t.status.as_str()), ("api first", "doing"));
        assert_eq!(s.next_task(None).unwrap().unwrap().title, "web first");
        assert_eq!(s.next_task(Some(api.id)).unwrap().unwrap().title, "api second");
        assert!(s.next_task(Some(api.id)).unwrap().is_none());
        assert_eq!(s.get_task(human.id).unwrap().status, "todo");
        assert!(!s.update_task(human.id, TaskPatch { human: Some(false), ..Default::default() }).unwrap().human);
    }

    #[test]
    fn backlog_is_a_column_agents_skip() {
        let (dir, s) = store();
        assert_eq!(s.statuses(), STATUSES);
        s.set_backlog(true).unwrap();
        let s = Store::open(&dir.path().join("kanzo.db"), None).unwrap();
        assert_eq!(s.statuses(), ["backlog", "todo", "doing", "review", "done"]);
        let api = s.create_project("api", "", None).unwrap();
        let status = |s: &str| TaskPatch { status: Some(s.into()), ..Default::default() };
        let backlog = s.create_task_in(api.id, "later", status("backlog")).unwrap();
        assert_eq!(backlog.status, "backlog");
        assert!(s.create_task_in(api.id, "x", status("nope")).is_err());
        assert_eq!(s.create_task(api.id, "now", "").unwrap().status, "todo");

        let t = s.next_task(None).unwrap().unwrap();
        assert_eq!((t.title.as_str(), t.status.as_str()), ("now", "doing"));
        assert!(s.next_task(None).unwrap().is_none());
        assert_eq!(s.get_task(backlog.id).unwrap().status, "backlog");

        assert!(s.set_backlog(false).is_err());
        s.delete_task(backlog.id).unwrap();
        s.set_backlog(false).unwrap();
    }

    #[test]
    fn hidden_properties_keep_their_data() {
        let (_dir, s) = store();
        assert!(s.hidden_properties().unwrap().is_empty());
        let api = s.create_project("api", "", None).unwrap();
        let t = s.create_task(api.id, "x", "Why").unwrap();
        let before = s.changes().unwrap();

        s.set_property("description", false).unwrap();
        s.set_property("tags", false).unwrap();
        s.set_property("tags", false).unwrap();
        assert_eq!(s.hidden_properties().unwrap(), ["description", "tags"]);
        assert!(s.changes().unwrap() > before, "other open boards redraw");
        assert_eq!(s.get_task(t.id).unwrap().description, "Why");

        s.set_property("description", true).unwrap();
        assert_eq!(s.hidden_properties().unwrap(), ["tags"]);
        for always in ["title", "status", "nope"] {
            assert!(s.set_property(always, false).is_err(), "{always}");
        }
    }

    #[test]
    fn change_counter_moves_on_every_write() {
        let (_dir, s) = store();
        let c0 = s.changes().unwrap();
        let p = s.create_project("api", "", None).unwrap();
        let c1 = s.changes().unwrap();
        let t = s.create_task(p.id, "x", "").unwrap();
        let c2 = s.changes().unwrap();
        s.add_comment(t.id, "me", "hi", &[]).unwrap();
        let c3 = s.changes().unwrap();
        assert!(c0 < c1 && c1 < c2 && c2 < c3);
    }

    #[test]
    fn a_task_links_to_one_url_on_any_site() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", None).unwrap();
        let t = s.create_task(api.id, "Fix login", "").unwrap();
        assert_eq!(t.url, "");
        let set = |url: &str| s.update_task(t.id, TaskPatch { url: Some(url.into()), ..Default::default() });
        for url in [
            "https://github.com/Me/Api/pull/12",
            "https://gitlab.example.com/a/b/-/merge_requests/3?x=1#y",
            "http://intranet",
        ] {
            assert_eq!(set(&format!("  {url} ")).unwrap().url, url);
        }
        for bad in [
            "#12",
            "owner/repo#12",
            "github.com/a/b",
            "javascript:alert(1)",
            "javascript://x",
            "https://",
            "https://a b",
        ] {
            assert!(set(bad).unwrap_err().to_string().contains("should start with"), "{bad}");
        }
        assert_eq!(s.get_task(t.id).unwrap().url, "http://intranet", "a bad URL changes nothing");
        assert_eq!(
            s.update_task(t.id, TaskPatch { title: Some("Fix".into()), ..Default::default() }).unwrap().url,
            "http://intranet"
        );
        assert_eq!(set("").unwrap().url, "");
    }

    #[test]
    fn task_keys() {
        assert_eq!(parse_task_key("api#12").unwrap(), (Some("api".into()), 12));
        assert_eq!(parse_task_key("#12").unwrap(), (None, 12));
        assert_eq!(parse_task_key(" 12 ").unwrap(), (None, 12));
        assert!(parse_task_key("api#x").is_err());
    }

    #[test]
    fn repos() {
        for url in [
            "owner/repo",
            "Owner/Repo",
            "https://github.com/owner/repo",
            "https://github.com/owner/repo.git",
            "git@github.com:owner/repo.git",
            "ssh://git@github.com/owner/repo.git",
            "git@github-work:owner/repo.git",
            "https://github.com/owner/repo/",
            "https://github.com/owner/repo/tree/main",
            "https://github.com/owner/repo/pull/3",
            "https://gitea.example.com/owner/repo.git",
            "git@gitea.example.com:owner/repo.git",
            "ssh://git@gitea.example.com:2222/owner/repo.git",
        ] {
            assert_eq!(repo_from_url(url).as_deref(), Some("owner/repo"), "{url}");
        }
        for url in [
            "acme/backend/api",
            "https://gitlab.com/acme/backend/api",
            "https://gitlab.com/acme/backend/api.git",
            "git@gitlab.com:acme/backend/api.git",
            "ssh://git@gitlab.com/acme/backend/api.git",
            "https://gitlab.com/acme/backend/api/-/merge_requests/3",
        ] {
            assert_eq!(repo_from_url(url).as_deref(), Some("acme/backend/api"), "{url}");
        }
        assert_eq!(repo_from_url("repo"), None);
        assert_eq!(repo_from_url("own er/repo"), None);
    }

    #[test]
    fn hosts() {
        for (url, host) in [
            ("https://gitlab.com/acme/backend/api", Some("gitlab.com")),
            ("git@gitlab.com:acme/api.git", Some("gitlab.com")),
            ("ssh://git@git.example.com:2222/acme/api.git", Some("git.example.com")),
            ("https://me:token@GitLab.example.com/acme/api.git", Some("gitlab.example.com")),
            ("https://github.com/owner/repo/pull/3", Some("github.com")),
            ("git@github-work:owner/repo.git", None),
            ("owner/repo", None),
            ("acme/backend/api", None),
        ] {
            assert_eq!(host_from_url(url).as_deref(), host, "{url}");
        }
    }

    #[test]
    fn repo_links_go_to_their_host() {
        let (_dir, s) = store();
        s.create_project("api", "", Some("git@gitlab.example.com:acme/backend/api.git")).unwrap();
        s.link_repo("api", "me/api-docs").unwrap();
        let p = s.link_repo("api", "https://gitlab.com/acme/web").unwrap();
        assert_eq!(p.repos, ["acme/backend/api", "me/api-docs", "acme/web"]);
        assert_eq!(
            p.repo_urls,
            [
                "https://gitlab.example.com/acme/backend/api",
                "https://github.com/me/api-docs",
                "https://gitlab.com/acme/web"
            ]
        );
    }

    #[test]
    fn repos_nested_in_one_group_are_different_repos() {
        let (_dir, s) = store();
        let api = s.create_project("api", "", Some("https://gitlab.com/acme/backend/api.git")).unwrap();
        let web = s.create_project("web", "", Some("git@gitlab.com:acme/backend/web.git")).unwrap();
        assert_eq!(api.repos, ["acme/backend/api"]);
        assert_eq!(s.project_by_repo("acme/backend/web").unwrap().unwrap().id, web.id);
        assert!(s.create_project("api2", "", Some("acme/backend/api")).is_err(), "still one project per repo");
    }

    #[test]
    fn moves_several_tasks_in_one_write() {
        let (_tmp, s) = store();
        let p = s.create_project("api", "", None).unwrap().id;
        let task = |title: &str| s.create_task(p, title, "").unwrap().id;
        let (a, b, c, d, x, y) = (task("a"), task("b"), task("c"), task("d"), task("x"), task("y"));
        s.move_tasks(&[x, y], "doing", None).unwrap();
        let order =
            |status: &str| -> Vec<i64> { s.list_tasks(None, Some(status)).unwrap().iter().map(|t| t.id).collect() };

        s.move_tasks(&[c, a], "doing", Some(y)).unwrap();
        assert_eq!(order("doing"), [x, c, a, y]);
        assert_eq!(order("todo"), [b, d]);

        // To the end, within a column, and past an anchor that's moving too.
        s.move_tasks(&[x, c], "doing", None).unwrap();
        assert_eq!(order("doing"), [a, y, x, c]);
        s.move_tasks(&[a, y], "doing", Some(a)).unwrap();
        assert_eq!(order("doing"), [x, c, a, y]);

        // More moves than there is float room between two neighbours.
        let many: Vec<i64> = (0..80).map(|i| task(&format!("m{i}"))).collect();
        s.move_tasks(&many, "doing", Some(y)).unwrap();
        let doing = order("doing");
        assert_eq!(&doing[3..83], &many[..]);
        assert_eq!(doing.last(), Some(&y));

        // All or nothing.
        assert!(s.move_tasks(&[b, 99999], "doing", None).is_err());
        assert!(order("todo").contains(&b));
        assert!(s.move_tasks(&[b], "nope", None).is_err());
    }
}