lific 2.8.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString, rand_core::OsRng},
};
use rusqlite::{Connection, OptionalExtension, params};

use crate::db::models::*;
use crate::error::LificError;

pub(crate) const INVALID_SESSION_MESSAGE: &str = "invalid or expired session";

// ── Password hashing ─────────────────────────────────────────

/// Hash a password with argon2 using a random salt.
pub fn hash_password(password: &str) -> Result<String, LificError> {
    let salt = SaltString::generate(&mut OsRng);
    let argon2 = Argon2::default();
    let hash = argon2
        .hash_password(password.as_bytes(), &salt)
        .map_err(|e| LificError::Internal(format!("password hashing failed: {e}")))?;
    Ok(hash.to_string())
}

/// Verify a password against an argon2 hash.
pub fn verify_password(password: &str, hash: &str) -> Result<bool, LificError> {
    let parsed = PasswordHash::new(hash)
        .map_err(|e| LificError::Internal(format!("invalid password hash: {e}")))?;
    Ok(Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok())
}

// ── User CRUD ────────────────────────────────────────────────

/// The longest password Lific will hash. Anything above this is rejected
/// before Argon2 sees it, so an oversized body cannot buy an attacker an
/// unbounded amount of CPU.
pub const MAX_PASSWORD_LEN: usize = 1024;

/// Validate a new account's fields without hashing its password.
///
/// LIF-412: signup runs Argon2 off the database writer, so the cheap checks
/// that can reject a request have to be callable on their own, before the
/// expensive part. [`create_user`] still runs them first, so any caller that
/// does not care about the split behaves exactly as before.
pub fn validate_new_user(input: &CreateUser) -> Result<(), LificError> {
    let username = input.username.trim();
    let email = input.email.trim().to_lowercase();

    if username.is_empty() {
        return Err(LificError::BadRequest("username cannot be empty".into()));
    }
    if email.is_empty() || !email.contains('@') {
        return Err(LificError::BadRequest("invalid email address".into()));
    }
    if input.password.len() < 8 {
        return Err(LificError::BadRequest(
            "password must be at least 8 characters".into(),
        ));
    }
    if input.password.len() > MAX_PASSWORD_LEN {
        return Err(LificError::BadRequest(
            "password must be 1024 characters or fewer".into(),
        ));
    }
    Ok(())
}

pub fn create_user(conn: &Connection, input: &CreateUser) -> Result<User, LificError> {
    validate_new_user(input)?;
    let password_hash = hash_password(&input.password)?;
    insert_user_with_hash(conn, input, &password_hash)
}

/// Insert an already-validated account whose password has already been hashed.
///
/// LIF-412: the write half of [`create_user`], so a caller can hash on the
/// blocking pool and take the exclusive writer only for the insert itself.
/// `input.password` is ignored here; `password_hash` is what gets stored.
pub fn insert_user_with_hash(
    conn: &Connection,
    input: &CreateUser,
    password_hash: &str,
) -> Result<User, LificError> {
    let username = input.username.trim();
    let email = input.email.trim().to_lowercase();
    let display_name = input
        .display_name
        .as_deref()
        .unwrap_or(username)
        .to_string();

    conn.execute(
        "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
        params![
            username,
            email,
            password_hash,
            display_name,
            input.is_admin,
            input.is_bot,
        ],
    )
    .map_err(|e| match e {
        rusqlite::Error::SqliteFailure(err, _)
            if err.code == rusqlite::ErrorCode::ConstraintViolation =>
        {
            LificError::BadRequest("an account with this username or email already exists".into())
        }
        other => other.into(),
    })?;

    let id = conn.last_insert_rowid();
    get_user_by_id(conn, id)
}

pub fn get_user_by_id(conn: &Connection, id: i64) -> Result<User, LificError> {
    conn.query_row(
        "SELECT id, username, email, password_hash, display_name, is_admin, is_bot, created_at, updated_at, is_active
         FROM users WHERE id = ?1",
        params![id],
        row_to_user,
    )
    .map_err(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => LificError::NotFound(format!("user {id} not found")),
        other => other.into(),
    })
}

pub fn get_user_by_username(conn: &Connection, username: &str) -> Result<User, LificError> {
    conn.query_row(
        "SELECT id, username, email, password_hash, display_name, is_admin, is_bot, created_at, updated_at, is_active
         FROM users WHERE username = ?1 COLLATE NOCASE",
        params![username],
        row_to_user,
    )
    .map_err(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => {
            LificError::NotFound(format!("user '{username}' not found"))
        }
        other => other.into(),
    })
}

pub fn get_user_by_email(conn: &Connection, email: &str) -> Result<User, LificError> {
    let email = email.trim().to_lowercase();
    conn.query_row(
        "SELECT id, username, email, password_hash, display_name, is_admin, is_bot, created_at, updated_at, is_active
         FROM users WHERE email = ?1 COLLATE NOCASE",
        params![email],
        row_to_user,
    )
    .map_err(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => {
            LificError::NotFound(format!("user with email '{email}' not found"))
        }
        other => other.into(),
    })
}

/// Pre-computed Argon2 hash of a dummy password, used to normalize timing
/// when the requested user doesn't exist. This ensures login attempts for
/// non-existent users take the same time as attempts with wrong passwords.
const DUMMY_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

/// Reject an oversized login password before Argon2 sees it, using the same
/// opaque message a wrong password gets. Split out of [`authenticate`] so the
/// HTTP login path (LIF-412) keeps the check while running the verify itself
/// off the database writer.
pub fn reject_oversized_password(password: &str) -> Result<(), LificError> {
    if password.len() > MAX_PASSWORD_LEN {
        return Err(LificError::BadRequest(
            "invalid username/email or password".into(),
        ));
    }
    Ok(())
}

/// One login attempt, with the database part already done and the Argon2 part
/// still to do.
///
/// LIF-412: verifying a password costs tens of milliseconds of CPU, and doing
/// it between a database lookup and a session insert used to mean holding a
/// connection for the whole attempt. Splitting the attempt in two lets the
/// caller take a read connection for [`password_challenge`], release it, run
/// the verify wherever it likes, and only then come back with the answer.
///
/// The dummy hash for an unknown user lives on this side of the split, so a
/// login for an account that does not exist still costs a full verify and
/// stays indistinguishable from a wrong password.
pub struct PasswordChallenge {
    user: Option<User>,
    hash: String,
}

impl PasswordChallenge {
    /// The Argon2 hash to verify against: the user's, or the dummy one when
    /// no such user exists.
    pub fn hash(&self) -> &str {
        &self.hash
    }

    /// Turn the verify's answer into the login's answer.
    pub fn finish(self, password_ok: bool) -> Result<User, LificError> {
        match self.user {
            // LIF-214: a deactivated account is told so rather than being
            // handed the generic wrong-password message. The check sits
            // *after* the Argon2 verify on purpose: answering before it would
            // turn the login form into an oracle for which usernames are
            // deactivated.
            Some(u) if password_ok && !u.is_active => Err(LificError::BadRequest(
                "this account has been deactivated. Ask an admin to restore it.".into(),
            )),
            Some(u) if password_ok => Ok(u),
            _ => Err(LificError::BadRequest(
                "invalid username/email or password".into(),
            )),
        }
    }
}

/// The generic failure a login reports. Kept in one place so the finalization
/// below cannot accidentally say something more specific than the verify does.
pub const INVALID_LOGIN_MESSAGE: &str = "invalid username/email or password";

/// Confirm, inside the transaction that is about to mint a session, that the
/// login which just succeeded is still true.
///
/// The Argon2 verify deliberately runs with no lock held, which takes tens of
/// milliseconds. In that window the account can be deactivated, its owner
/// deactivated, or its password changed by a lockdown, and the pre-transaction
/// verify has no way to know. Minting a session on that evidence hands out a
/// week-long credential for a password that no longer exists, which is exactly
/// what a password change is supposed to prevent.
///
/// So the user is re-read by id here and three things are required:
///
/// - the row still exists;
/// - the credential may authenticate at all ([`credential_is_live`], which
///   covers both a deactivated account and a bot whose owner was deactivated);
/// - the stored password hash is **byte-identical** to the one just verified.
///
/// The hash comparison is the load-bearing one: it is what makes "the password
/// was correct" mean "the password is correct". Argon2 is not re-run, so this
/// costs one indexed read.
pub fn finalize_login(
    conn: &Connection,
    user_id: i64,
    verified_hash: &str,
) -> Result<User, LificError> {
    let user = get_user_by_id(conn, user_id)
        .map_err(|_| LificError::BadRequest(INVALID_LOGIN_MESSAGE.into()))?;
    if !credential_is_live(conn, &user)? {
        return Err(LificError::BadRequest(
            "this account has been deactivated. Ask an admin to restore it.".into(),
        ));
    }
    if user.password_hash != verified_hash {
        // The password changed between the verify and here, which means the
        // one presented is the old one. Same message a wrong password gets.
        return Err(LificError::BadRequest(INVALID_LOGIN_MESSAGE.into()));
    }
    Ok(user)
}

/// The database half of a login: find the account by username or email and
/// pick the hash to verify against. Pure read, safe on a pooled read
/// connection.
pub fn password_challenge(conn: &Connection, identity: &str) -> PasswordChallenge {
    // Try username first, then email.
    // If the user doesn't exist, still run Argon2 against a dummy hash
    // to prevent timing side-channel enumeration of valid usernames.
    match get_user_by_username(conn, identity).or_else(|_| get_user_by_email(conn, identity)) {
        Ok(u) => {
            let hash = u.password_hash.clone();
            PasswordChallenge {
                user: Some(u),
                hash,
            }
        }
        Err(_) => PasswordChallenge {
            user: None,
            hash: DUMMY_HASH.to_string(),
        },
    }
}

/// Look up a user by username or email and verify their password, start to
/// finish on the caller's connection. Returns the user on success, or an
/// error on wrong credentials.
///
/// LIF-412: the login endpoint no longer calls this, because the Argon2
/// verify must not run while a database connection is held. It composes
/// [`password_challenge`] and [`PasswordChallenge::finish`] around a
/// `spawn_blocking` instead. This synchronous composition of the same two
/// halves is what the query-layer tests exercise, where serializing on one
/// connection costs nothing.
#[cfg(test)]
pub fn authenticate(conn: &Connection, identity: &str, password: &str) -> Result<User, LificError> {
    // Reject oversized passwords early to prevent Argon2 CPU DoS
    reject_oversized_password(password)?;
    let challenge = password_challenge(conn, identity);
    let password_ok = verify_password(password, challenge.hash()).unwrap_or(false);
    challenge.finish(password_ok)
}

/// LIF-190: update the authenticated user's profile fields. Each field is
/// optional so the caller can PATCH just one. Returns the refreshed user.
pub fn update_profile(
    conn: &Connection,
    user_id: i64,
    display_name: Option<&str>,
    email: Option<&str>,
) -> Result<User, LificError> {
    if let Some(dn) = display_name {
        let dn = dn.trim();
        if dn.is_empty() {
            return Err(LificError::BadRequest(
                "display name cannot be empty".into(),
            ));
        }
        if dn.chars().count() > 100 {
            return Err(LificError::BadRequest(
                "display name must be 100 characters or fewer".into(),
            ));
        }
        conn.execute(
            "UPDATE users SET display_name = ?1 WHERE id = ?2",
            params![dn, user_id],
        )?;
    }
    if let Some(em) = email {
        let em = em.trim().to_lowercase();
        if em.is_empty() || !em.contains('@') {
            return Err(LificError::BadRequest("invalid email address".into()));
        }
        conn.execute(
            "UPDATE users SET email = ?1 WHERE id = ?2",
            params![em, user_id],
        )
        .map_err(|e| match e {
            rusqlite::Error::SqliteFailure(err, _)
                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
            {
                LificError::BadRequest("that email is already in use".into())
            }
            other => other.into(),
        })?;
    }
    get_user_by_id(conn, user_id)
}

/// LIF-190: replace the user's password. Caller is responsible for verifying
/// the current password first. Enforces the same length bounds as signup.
pub fn update_password(
    conn: &Connection,
    user_id: i64,
    new_password: &str,
) -> Result<(), LificError> {
    let hash = prepare_new_password(new_password)?;
    update_password_hash(conn, user_id, &hash)
}

/// Check a proposed password against policy and hash it. Touches no
/// connection, so a caller holding no lock can run this on the blocking pool.
///
/// The policy lives here rather than at each call site so the CLI, the API and
/// the tests cannot drift apart on what a valid password is.
pub fn prepare_new_password(new_password: &str) -> Result<String, LificError> {
    if new_password.len() < 8 {
        return Err(LificError::BadRequest(
            "password must be at least 8 characters".into(),
        ));
    }
    if new_password.len() > 1024 {
        return Err(LificError::BadRequest(
            "password must be 1024 characters or fewer".into(),
        ));
    }
    hash_password(new_password)
}

/// Store a hash that has already been prepared by [`prepare_new_password`].
///
/// Split out so the API path can do the Argon2 work with no lock held and then
/// take the writer only for the write. Hashing under the exclusive writer
/// stalled every other write in the process for the duration, which is the
/// same problem LIF-412 fixed for login and signup.
pub fn update_password_hash(
    conn: &Connection,
    user_id: i64,
    prepared_hash: &str,
) -> Result<(), LificError> {
    conn.execute(
        "UPDATE users SET password_hash = ?1 WHERE id = ?2",
        params![prepared_hash, user_id],
    )?;
    Ok(())
}

pub fn list_users(conn: &Connection) -> Result<Vec<User>, LificError> {
    let mut stmt = conn.prepare_cached(
        "SELECT id, username, email, password_hash, display_name, is_admin, is_bot, created_at, updated_at, is_active
         FROM users ORDER BY created_at",
    )?;
    let rows = stmt.query_map([], row_to_user)?;
    rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
}

/// True if at least one human (non-bot) account exists.
///
/// Backs the public `GET /api/instance` endpoint so the auth screen can tell a
/// brand-new instance ("be the first account") from an established one ("join
/// this instance") without leaking any user data. Bot identities are excluded
/// because a connected tool is not a person who has signed up.
pub fn has_human_users(conn: &Connection) -> Result<bool, LificError> {
    let exists: bool = conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM users WHERE is_bot = 0)",
        [],
        |row| row.get(0),
    )?;
    Ok(exists)
}

fn row_to_user(row: &rusqlite::Row) -> Result<User, rusqlite::Error> {
    Ok(User {
        id: row.get(0)?,
        username: row.get(1)?,
        email: row.get(2)?,
        password_hash: row.get(3)?,
        display_name: row.get(4)?,
        is_admin: row.get(5)?,
        is_bot: row.get(6)?,
        created_at: row.get(7)?,
        updated_at: row.get(8)?,
        is_active: row.get(9)?,
    })
}

/// Return the first admin user (by creation time), if any.
/// Used as a fallback author for MCP stdio sessions where no HTTP auth is present.
pub fn first_admin(conn: &Connection) -> Result<Option<AuthUser>, LificError> {
    match conn.query_row(
        // LIF-214: a deactivated admin is not an identity anything may fall
        // back to, so the passwordless/stdio resolver skips them.
        "SELECT id, username, display_name, is_admin FROM users WHERE is_admin = 1 AND is_active = 1 ORDER BY created_at LIMIT 1",
        [],
        |row| {
            Ok(AuthUser {
                id: row.get(0)?,
                username: row.get(1)?,
                display_name: row.get(2)?,
                is_admin: row.get(3)?,
            })
        },
    ) {
        Ok(user) => Ok(Some(user)),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(e) => Err(e.into()),
    }
}

// ── Passwordless admin (LIFIC-9) ────────────────────────────

/// Derive a usable, unique username from a display name. Keeps [a-z0-9-],
/// collapses runs of non-alphanumerics to a single `-`, and falls back to
/// `admin` if nothing survives; appends `-N` when the raw slug is taken.
fn derive_username(conn: &Connection, display_name: &str) -> Result<String, LificError> {
    let slug: String = display_name
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-");
    let base = if slug.is_empty() {
        "admin".to_string()
    } else {
        slug
    };
    let mut candidate = base.clone();
    let mut n = 1;
    loop {
        match get_user_by_username(conn, &candidate) {
            Ok(_) => {
                candidate = format!("{base}-{n}");
                n += 1;
            }
            Err(LificError::NotFound(_)) => return Ok(candidate),
            Err(error) => return Err(error),
        }
    }
}

/// Create the first human admin on a fresh install — a passwordless operator.
///
/// "Passwordless" means it can never be signed into by password: the stored
/// hash is a random value with no known plaintext, and the email is a synthetic
/// placeholder that satisfies the NOT NULL UNIQUE schema. The operator reaches
/// this identity through the browser auto-login / passwordless fallback in
/// `resolve_caller`, never through a password prompt.
///
/// LIFIC-9: this is what makes `[auth] required = false` "passwordless mode"
/// instead of "half-broken anonymous" — there is always a real admin to resolve
/// to from the moment the instance exists.
pub fn create_passwordless_admin(
    conn: &Connection,
    display_name: &str,
) -> Result<User, LificError> {
    let display_name = display_name.trim();
    if display_name.is_empty() {
        return Err(LificError::BadRequest(
            "operator name cannot be empty".into(),
        ));
    }
    // Unusable hash: never arithmetically a login password, just fills the NOT
    // NULL column. Same guarantee as `create_bot_user`.
    let password_hash = unusable_password_hash()?;
    insert_first_admin(conn, display_name, password_hash)
}

/// Create the first human admin with a real password — the `Passwords` mode of
/// the `lific init` auth-mode menu (LIFIC-25).
///
/// Same username/email derivation as [`create_passwordless_admin`], but the
/// stored hash is a real argon2 hash of `password`, so the operator can sign in
/// on the web. This is the counterpart to passwordless mode: the operator
/// still reaches the instance without an admin prompt, but through the password
/// gate rather than browser auto-login.
pub fn create_first_admin_with_password(
    conn: &Connection,
    display_name: &str,
    password: &str,
) -> Result<User, LificError> {
    let display_name = display_name.trim();
    if display_name.is_empty() {
        return Err(LificError::BadRequest(
            "operator name cannot be empty".into(),
        ));
    }
    if password.is_empty() {
        return Err(LificError::BadRequest(
            "operator password cannot be empty".into(),
        ));
    }
    let password_hash = hash_password(password)?;
    insert_first_admin(conn, display_name, password_hash)
}

/// Shared insert for the first human admin (LIFIC-22/25). Derives the unique
/// username from `display_name`, fills the NOT NULL email with a synthetic
/// `{username}@local` placeholder, and stores the given `password_hash`. Both
/// passwordless mode (unusable hash) and password mode (real argon2 hash) land
/// here, so the derivation and constraint handling live in exactly one place.
fn insert_first_admin(
    conn: &Connection,
    display_name: &str,
    password_hash: String,
) -> Result<User, LificError> {
    let username = derive_username(conn, display_name)?;

    conn.execute(
        "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot)
         VALUES (?1, ?2, ?3, ?4, 1, 0)",
        params![
            username,
            format!("{username}@local"),
            password_hash,
            display_name,
        ],
    )
    .map_err(|e| match e {
        rusqlite::Error::SqliteFailure(err, _)
            if err.code == rusqlite::ErrorCode::ConstraintViolation =>
        {
            LificError::Internal("failed to create first admin (constraint)".into())
        }
        other => other.into(),
    })?;

    let id = conn.last_insert_rowid();
    get_user_by_id(conn, id)
}

// ── Sessions ─────────────────────────────────────────────────

/// Hash a session token with SHA-256 for storage.
fn hash_session_token(token: &str) -> String {
    crate::auth::sha256_hex(token.as_bytes())
}

/// Sweep expired session rows.
///
/// LIF-139: this used to run inside `validate_session`, which put a write on
/// the hot path of every session-authenticated request and forced the auth
/// middleware to take the exclusive writer mutex just to read. The sweep now
/// piggybacks on the session writes that already hold the writer — login
/// (`create_session`) and logout (`delete_session`) — so validation is a pure
/// read. Expiry itself is enforced by the `expires_at` predicate in
/// `validate_session`, never by this cleanup; the sweep only reclaims rows.
///
/// Best-effort: a failure here must never fail the login/logout it rides on.
fn purge_expired_sessions(conn: &Connection) {
    let _ = conn.execute(
        "DELETE FROM sessions WHERE datetime(expires_at) < datetime('now')",
        [],
    );
}

/// Create a new session for a user. Returns the session with the plaintext token
/// (shown once to the client). The SHA-256 hash is stored in the database.
/// Sessions expire after `duration_hours` (default 24 * 7 = 1 week).
pub fn create_session(
    conn: &Connection,
    user_id: i64,
    duration_hours: Option<i64>,
) -> Result<Session, LificError> {
    // LIF-139: login already holds the writer — sweep expired rows here
    // instead of on every validation.
    purge_expired_sessions(conn);

    let hours = duration_hours.unwrap_or(24 * 7); // 1 week default
    let token = generate_session_token();
    let token_hash = hash_session_token(&token);

    conn.execute(
        "INSERT INTO sessions (token, user_id, expires_at)
         VALUES (?1, ?2, datetime('now', ?3))",
        params![token_hash, user_id, format!("+{hours} hours")],
    )?;

    // Return the plaintext token to the caller (shown to the client once)
    Ok(Session {
        token,
        user_id,
        expires_at: conn.query_row(
            "SELECT expires_at FROM sessions WHERE token = ?1",
            params![token_hash],
            |row| row.get(0),
        )?,
        created_at: conn.query_row(
            "SELECT created_at FROM sessions WHERE token = ?1",
            params![token_hash],
            |row| row.get(0),
        )?,
    })
}

/// Whether a credential naming `user` may authenticate right now.
///
/// Two ways it may not:
///
/// - The account itself was deactivated (LIF-214). `set_active` tears down the
///   credentials it can see, and this catches anything that outlives that
///   write (a race, or a token minted while the flag was flipping).
/// - It is a *bot* whose owner was deactivated. A bot is a separate `users`
///   row with its own API keys and OAuth tokens, but no permissions of its
///   own: [`crate::authz::effective_user`] resolves every owned bot to its
///   owner before any role check runs. So an owner who has lost access would
///   otherwise keep exercising it through a tool connection minted earlier.
///   Enforcing on the read path rather than revoking the bots' credentials is
///   deliberate. It cannot race a connect that is in flight, and reactivating
///   the owner restores every bot without re-minting anything.
///
/// An ownerless bot (`owner_id IS NULL`, or a dangling owner row) inherits
/// nothing, so it is evaluated as itself — the same fallback `effective_user`
/// makes.
pub fn credential_is_live(conn: &Connection, user: &User) -> Result<bool, LificError> {
    if !user.is_active {
        return Ok(false);
    }
    if !user.is_bot {
        return Ok(true);
    }
    let owner_is_active: Option<bool> = conn
        .query_row(
            "SELECT owner.is_active FROM users bot
             JOIN users owner ON owner.id = bot.owner_id
             WHERE bot.id = ?1 AND bot.is_bot = 1",
            params![user.id],
            |row| row.get(0),
        )
        .optional()?;
    Ok(owner_is_active.unwrap_or(true))
}

/// Validate a session token. Returns the associated user if the session
/// exists and has not expired. The incoming plaintext token is hashed with
/// SHA-256 before lookup.
///
/// LIF-139: read-only. Expiry is enforced by the `datetime(expires_at) >
/// datetime('now')`
/// predicate below, so an expired row is rejected whether or not it has been
/// swept yet. The sweep moved to `create_session`/`delete_session`
/// (see [`purge_expired_sessions`]), which lets the auth middleware validate on
/// a pooled read connection rather than serializing on the single writer.
pub fn validate_session(conn: &Connection, token: &str) -> Result<User, LificError> {
    let token_hash = hash_session_token(token);

    let user_id: i64 = conn
        .query_row(
            "SELECT user_id FROM sessions WHERE token = ?1
             AND datetime(expires_at) > datetime('now')",
            params![token_hash],
            |row| row.get(0),
        )
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                LificError::BadRequest(INVALID_SESSION_MESSAGE.into())
            }
            other => other.into(),
        })?;

    let user = get_user_by_id(conn, user_id)?;
    // LIF-214: deactivation revokes access, so a session row that outlives it
    // (a race with the sweep, or a token minted before the flag flipped) must
    // not authenticate. Same error the middleware already maps to 401. A bot
    // whose owner is deactivated is rejected on the same terms — see
    // [`credential_is_live`].
    if !credential_is_live(conn, &user)? {
        return Err(LificError::BadRequest(INVALID_SESSION_MESSAGE.into()));
    }
    Ok(user)
}

/// Whether a session was created within the recent-authentication window.
pub fn session_is_recent(conn: &Connection, token: &str) -> Result<bool, LificError> {
    let token_hash = hash_session_token(token);
    Ok(conn
        .query_row(
            "SELECT created_at >= datetime('now', '-15 minutes')
             FROM sessions WHERE token = ?1",
            params![token_hash],
            |row| row.get(0),
        )
        .optional()?
        .unwrap_or(false))
}

/// Delete a session (logout). Hashes the plaintext token before lookup.
pub fn delete_session(conn: &Connection, token: &str) -> Result<(), LificError> {
    let token_hash = hash_session_token(token);
    conn.execute("DELETE FROM sessions WHERE token = ?1", params![token_hash])?;
    // LIF-139: logout holds the writer too — reclaim expired rows here.
    purge_expired_sessions(conn);
    Ok(())
}

/// Delete all sessions for a user.
pub fn delete_all_sessions(conn: &Connection, user_id: i64) -> Result<(), LificError> {
    conn.execute("DELETE FROM sessions WHERE user_id = ?1", params![user_id])?;
    Ok(())
}

/// SQL fragment matching every identity an account lockdown covers: the human
/// named by `?1`, plus every connected-tool bot they own. A bot carries no
/// permissions of its own ([`credential_is_live`]), so a credential minted for
/// one is the owner's reach by another name and has to fall with the owner's.
///
/// Deliberately matches on `user_id`, which is what every credential table
/// binds. A key with `user_id IS NULL` is the *unbound operator* key: it names
/// nobody, belongs to whoever runs the server locally, and is out of scope.
const LOCKDOWN_SCOPE_SQL: &str = "(user_id = ?1 OR user_id IN (\
     SELECT id FROM users WHERE is_bot = 1 AND owner_id = ?1))";

/// The ids of every connected-tool bot `owner_id` owns.
///
/// Deactivation and lockdown both act on the owner plus these, so anything
/// that has to be told about it (a realtime socket, say) needs the same set.
pub fn owned_bot_ids(conn: &Connection, owner_id: i64) -> Result<Vec<i64>, LificError> {
    let mut stmt =
        conn.prepare("SELECT id FROM users WHERE is_bot = 1 AND owner_id = ?1 ORDER BY id")?;
    let ids = stmt
        .query_map(params![owner_id], |row| row.get(0))?
        .collect::<Result<Vec<i64>, _>>()?;
    Ok(ids)
}

/// Lock an account down: sever every credential that could still act as the
/// user, or as one of their connected tools, right now.
///
/// This is the one primitive behind all three recovery front doors (API
/// password change, API sign-out-everywhere, and `lific user set-password`),
/// so "I've been compromised" means the same thing whichever one the user
/// reaches for. Blast radius, for the human **and every bot they own**:
///
/// - every session row is deleted;
/// - every active API key is revoked;
/// - every active OAuth access token is revoked;
/// - every unexchanged OAuth authorization code is burned (marked used, so a
///   racing exchange sees the single-use transition already spent rather than
///   a missing row it could mistake for a lookup failure);
/// - every *approved* OAuth device code is flipped to `denied`, which is the
///   terminal state its exchange path already refuses.
///
/// Deliberately NOT in scope: unbound operator API keys (they name no user),
/// bot identities themselves (the tool row survives so the UI can show it as
/// disconnected and offer a reconnect), and OAuth public-client registrations
/// (a client is not a credential). Pending, still-unbound device codes are
/// handled by the approval path revalidating the approver's session inside the
/// same transaction that binds them, not here: at lockdown time such a row
/// names nobody to scope it to.
///
/// Every revoked API key and OAuth token gets its own audit row, labelled with
/// the key name or client id. No token material is written anywhere.
///
/// Runs inside a SAVEPOINT and opens no independent write of its own, so a
/// caller may wrap it in a larger transaction and get one atomic recovery.
pub fn lock_down_account(conn: &Connection, user_id: i64) -> Result<(), LificError> {
    crate::db::queries::savepoint(conn, "lock_down_account", || {
        conn.execute(
            &format!("DELETE FROM sessions WHERE {LOCKDOWN_SCOPE_SQL}"),
            params![user_id],
        )?;

        let mut api_keys = conn.prepare(&format!(
            "SELECT id, name FROM api_keys WHERE revoked = 0 AND {LOCKDOWN_SCOPE_SQL}"
        ))?;
        let api_keys = api_keys
            .query_map(params![user_id], |row| Ok((row.get(0)?, row.get(1)?)))?
            .collect::<Result<Vec<(i64, String)>, _>>()?;
        conn.execute(
            &format!("UPDATE api_keys SET revoked = 1 WHERE revoked = 0 AND {LOCKDOWN_SCOPE_SQL}"),
            params![user_id],
        )?;
        for (id, name) in api_keys {
            conn.execute(
                "INSERT INTO audit_log
                    (actor_user_id, transport, entity_type, entity_id, entity_label,
                     action, field, old_value, new_value)
                 SELECT user_id, transport, 'api_key', ?1, ?2,
                        'revoke', 'revoked', '0', '1'
                 FROM _actor_state WHERE id = 1",
                params![id, name],
            )?;
        }

        let mut oauth_tokens = conn.prepare(&format!(
            "SELECT rowid, client_id FROM oauth_tokens WHERE revoked = 0 AND {LOCKDOWN_SCOPE_SQL}"
        ))?;
        let oauth_tokens = oauth_tokens
            .query_map(params![user_id], |row| Ok((row.get(0)?, row.get(1)?)))?
            .collect::<Result<Vec<(i64, String)>, _>>()?;
        conn.execute(
            &format!(
                "UPDATE oauth_tokens SET revoked = 1 WHERE revoked = 0 AND {LOCKDOWN_SCOPE_SQL}"
            ),
            params![user_id],
        )?;
        for (id, client_id) in oauth_tokens {
            conn.execute(
                "INSERT INTO audit_log
                    (actor_user_id, transport, entity_type, entity_id, entity_label,
                     action, field, old_value, new_value)
                 SELECT user_id, transport, 'oauth_token', ?1, ?2,
                        'revoke', 'revoked', '0', '1'
                 FROM _actor_state WHERE id = 1",
                params![id, client_id],
            )?;
        }

        // An authorization code is a bearer credential in flight. One issued
        // before the compromise was noticed would otherwise still exchange for
        // a fresh 30-day access token after every stored credential died.
        conn.execute(
            &format!("UPDATE oauth_codes SET used = 1 WHERE used = 0 AND {LOCKDOWN_SCOPE_SQL}"),
            params![user_id],
        )?;

        // Same reasoning for a device grant the user already approved: the
        // device is still polling and would collect a token on its next poll.
        conn.execute(
            &format!(
                "UPDATE oauth_device_codes SET status = 'denied'
                 WHERE status = 'approved' AND {LOCKDOWN_SCOPE_SQL}"
            ),
            params![user_id],
        )?;

        Ok(())
    })
}

/// Generate a session token with the lific_sess_ prefix.
fn generate_session_token() -> String {
    let bytes: [u8; 32] = rand::random();
    let hex = crate::auth::hex_encode(&bytes);
    format!("lific_sess_{hex}")
}

// ── API key ownership ────────────────────────────────────────

/// Rebind an existing API key to a user.
///
/// LIF-391: this is no longer part of key creation. `auth::create_api_key`
/// takes the owner and writes the binding in the same insert, so nothing
/// creates a key unbound and patches it afterwards. The one remaining caller
/// is `lific key assign`, which rebinds a key that already exists.
pub fn assign_key_to_user(
    conn: &Connection,
    key_name: &str,
    user_id: i64,
) -> Result<(), LificError> {
    let changed = conn.execute(
        "UPDATE api_keys SET user_id = ?1 WHERE name = ?2 AND revoked = 0",
        params![user_id, key_name],
    )?;
    if changed == 0 {
        return Err(LificError::NotFound(format!(
            "no active key named '{key_name}'"
        )));
    }
    Ok(())
}

// ── Bots (connected tools) ───────────────────────────────────

/// Create a bot user owned by the given human user.
/// Returns the bot user. API key creation is handled separately by the caller
/// using `auth::create_api_key`, which binds the new key to the bot.
/// Generate an unusable password hash: a random value with no known plaintext.
///
/// Used for identities that must never be signed into by password (passwordless
/// human admins, and bots) to satisfy the NOT NULL `password_hash` column while
/// guaranteeing `authenticate` can never succeed against it.
fn unusable_password_hash() -> Result<String, LificError> {
    let random_pw: [u8; 32] = rand::random();
    let random_pw_hex = crate::auth::hex_encode(&random_pw);
    hash_password(&random_pw_hex)
}

/// Whether a failure is SQLite rejecting a write because it broke a constraint
/// (UNIQUE, CHECK, foreign key). LIF-367 leans on this to tell "another
/// connect got here first" apart from a genuine database failure.
fn is_constraint_violation(err: &LificError) -> bool {
    matches!(
        err,
        LificError::Database(rusqlite::Error::SqliteFailure(e, _))
            if e.code == rusqlite::ErrorCode::ConstraintViolation
    )
}

/// Create a bot user owned by `owner_id`, with its `tool_id` set in the same
/// statement.
///
/// LIF-367: `idx_users_owner_tool` makes `(owner_id, tool_id)` unique for
/// bots, so the pair has to land atomically. Minting with `tool_id` NULL and
/// patching it in a follow-up UPDATE leaves a window in which a concurrent
/// connect sees no bot for the pair and mints a second one. Pass `None` only
/// for identities that genuinely have no tool behind them.
///
/// Every constraint the row can break — the unique username, the unique
/// (owner, tool) pair — comes back as [`LificError::BadRequest`], and that is
/// the *only* thing that produces that variant here. [`ensure_bot`] relies on
/// that to tell "somebody else already connected this tool" from a real
/// failure.
pub fn create_bot_user(
    conn: &Connection,
    owner_id: i64,
    bot_username: &str,
    display_name: &str,
    tool_id: Option<&str>,
) -> Result<crate::db::models::User, LificError> {
    let password_hash = unusable_password_hash()?;

    conn.execute(
        "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot, owner_id, tool_id)
         VALUES (?1, ?2, ?3, ?4, 0, 1, ?5, ?6)",
        params![
            bot_username,
            format!("{bot_username}@bot.local"),
            password_hash,
            display_name,
            owner_id,
            tool_id,
        ],
    )
    .map_err(|e| match e {
        rusqlite::Error::SqliteFailure(err, _)
            if err.code == rusqlite::ErrorCode::ConstraintViolation =>
        {
            LificError::BadRequest(format!(
                "this tool is already connected (bot '{bot_username}' exists)"
            ))
        }
        other => other.into(),
    })?;

    let bot_user_id = conn.last_insert_rowid();
    get_user_by_id(conn, bot_user_id)
}

// ── Instance-admin roster management (LIF-214) ───────────────
//
// One code path, two front doors. `lific user promote/demote` (src/cli/user.rs)
// keeps the raw, unguarded write, because the local shell is the recovery tool
// and must be able to put an instance back into any state it can also get it
// out of. The REST surface (`src/api/auth.rs`, admin-gated) goes through the
// `_guarded` wrappers, which refuse to strand an instance with no admin and
// refuse to touch a bot identity at all. Both end up in the same UPDATE.

/// Write the admin flag on one user by id. Deliberately guard-free: the two
/// callers below decide what is allowed before reaching here.
fn write_admin_flag(conn: &Connection, user_id: i64, is_admin: bool) -> Result<(), LificError> {
    conn.execute(
        "UPDATE users SET is_admin = ?1, updated_at = datetime('now') WHERE id = ?2",
        params![is_admin, user_id],
    )?;
    Ok(())
}

/// Set or unset admin status on a user, by username. The CLI path: no last-
/// admin guard, since `lific user promote` can always undo a `demote` from
/// the same shell, and an operator locked out of their own instance needs
/// exactly this escape hatch.
pub fn set_admin(conn: &Connection, username: &str, is_admin: bool) -> Result<(), LificError> {
    let user = get_user_by_username(conn, username)?;
    write_admin_flag(conn, user.id, is_admin)
}

/// How many admins can actually sign in right now. Bots are excluded (they
/// are never instance admins) and so are deactivated accounts, since an admin
/// who cannot authenticate is not an admin anyone can reach.
pub fn count_active_admins(conn: &Connection) -> Result<i64, LificError> {
    conn.query_row(
        "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND is_active = 1 AND is_bot = 0",
        [],
        |row| row.get(0),
    )
    .map_err(Into::into)
}

/// Resolve the target of a roster action, refusing bot identities.
///
/// A connected tool is not a member of the instance in the sense this roster
/// means: it has no password, is owned by a human, and is switched on and off
/// through Connected Tools (`disconnect_bot` / `delete_bot`). Promoting one to
/// instance admin would hand an agent's API key the run of the instance, so
/// every entry point here stops at the same door.
fn manageable_target(conn: &Connection, user_id: i64) -> Result<User, LificError> {
    let user = get_user_by_id(conn, user_id)?;
    if user.is_bot {
        return Err(LificError::BadRequest(
            "bot identities are managed from Connected Tools, not the member roster".into(),
        ));
    }
    Ok(user)
}

/// Promote or demote a user on the instance-admin axis. Returns the refreshed
/// row.
///
/// Refuses to demote the last admin who can still sign in (409 `Conflict`),
/// mirroring the last-lead guard on project membership. Demoting an already
/// deactivated admin is fine: they were not part of that count to begin with.
pub fn set_admin_guarded(
    conn: &Connection,
    user_id: i64,
    is_admin: bool,
) -> Result<User, LificError> {
    let target = manageable_target(conn, user_id)?;

    if target.is_admin && target.is_active && !is_admin && count_active_admins(conn)? <= 1 {
        return Err(LificError::Conflict(
            "cannot demote the last instance admin. Promote someone else first.".into(),
        ));
    }

    write_admin_flag(conn, target.id, is_admin)?;
    get_user_by_id(conn, target.id)
}

/// Deactivate or restore an account. Returns the refreshed row.
///
/// Refuses to deactivate the last admin who can still sign in (409
/// `Conflict`), for the same reason [`set_admin_guarded`] refuses to demote
/// them.
///
/// Deactivation ends access, it does not erase anything: the row and every
/// issue, comment and audit entry attributed to it stay exactly where they
/// are. To make "ends access" true rather than decorative, every credential
/// the account holds is torn down in the same write: sessions deleted, API
/// keys and OAuth tokens revoked. Restoring the account does not bring the
/// credentials back; the user signs in again and mints fresh ones.
///
/// The account's **owned bots** are handled differently on purpose. Their
/// sessions are deleted too, so an already-established realtime connection
/// drops promptly instead of lingering until its next reconnect. Their API
/// keys and OAuth tokens are left alone: [`credential_is_live`] rejects them
/// on the read path for as long as the owner is deactivated, which is
/// race-free, and reactivating the owner then restores every connected tool
/// without the user having to re-mint anything.
///
/// The guard, the flag write and every teardown run in one transaction. A
/// failure part-way through used to be able to leave a deactivated account
/// holding live credentials; now it leaves nothing at all.
pub fn set_active(conn: &Connection, user_id: i64, is_active: bool) -> Result<User, LificError> {
    // A SAVEPOINT, not `unchecked_transaction`: callers now wrap this in their
    // own transaction (the reactivate route revalidates the admin's session in
    // the same one), and `BEGIN` inside an open transaction is an error.
    // Savepoints nest, and behave as a plain transaction when there is no
    // outer one.
    crate::db::queries::savepoint(conn, "set_active", || {
        let target = manageable_target(conn, user_id)?;

        if !is_active && target.is_admin && target.is_active && count_active_admins(conn)? <= 1 {
            return Err(LificError::Conflict(
                "cannot deactivate the last instance admin. Promote someone else first.".into(),
            ));
        }

        conn.execute(
            "UPDATE users SET is_active = ?1, updated_at = datetime('now') WHERE id = ?2",
            params![is_active, target.id],
        )?;

        if !is_active {
            delete_all_sessions(conn, target.id)?;
            conn.execute(
                "UPDATE api_keys SET revoked = 1 WHERE user_id = ?1 AND revoked = 0",
                params![target.id],
            )?;
            conn.execute(
                "UPDATE oauth_tokens SET revoked = 1 WHERE user_id = ?1 AND revoked = 0",
                params![target.id],
            )?;
            // Owned bots: sessions only. Their keys and tokens stay intact and
            // simply stop authenticating (see the doc comment above).
            conn.execute(
                "DELETE FROM sessions WHERE user_id IN
                 (SELECT id FROM users WHERE owner_id = ?1 AND is_bot = 1)",
                params![target.id],
            )?;
        }

        get_user_by_id(conn, target.id)
    })
}

/// Find a bot by its stable (owner, tool) pairing (LIFIC-17).
///
/// This is the key that survives an owner rename, where the derived
/// `{tool}-{owner.username}` username does not.
pub fn find_bot_by_owner_and_tool(
    conn: &Connection,
    owner_id: i64,
    tool_id: &str,
) -> Result<Option<crate::db::models::User>, LificError> {
    match conn.query_row(
        "SELECT id, username, email, password_hash, display_name, is_admin, is_bot, created_at, updated_at, is_active
         FROM users WHERE owner_id = ?1 AND tool_id = ?2 AND is_bot = 1 LIMIT 1",
        params![owner_id, tool_id],
        row_to_user,
    ) {
        Ok(user) => Ok(Some(user)),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(e) => Err(e.into()),
    }
}

/// Find a legacy bot (tool_id NULL, minted before LIFIC-17) by its owner and
/// its tool *prefix*.
///
/// Legacy bots were keyed by the `{tool}-{owner.username}` username, which
/// embeds the owner's name at mint time. After a rename that prefix is stale,
/// so the lookup must not depend on the current owner username — it matches on
/// the stable `owner_id` and the tool prefix alone, which a rename never
/// touches. `GLOB '{tool_id}-*'` ties the match to the exact tool prefix (tool
/// slugs are `[a-z0-9-]`, so no `*`/`?` need escaping).
pub fn find_bot_legacy_by_tool_prefix(
    conn: &Connection,
    owner_id: i64,
    tool_id: &str,
) -> Result<Option<crate::db::models::User>, LificError> {
    match conn.query_row(
        "SELECT id, username, email, password_hash, display_name, is_admin, is_bot, created_at, updated_at, is_active
         FROM users WHERE owner_id = ?1 AND is_bot = 1 AND tool_id IS NULL
              AND username GLOB ?2 LIMIT 1",
        params![owner_id, format!("{tool_id}-*")],
        row_to_user,
    ) {
        Ok(user) => Ok(Some(user)),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(e) => Err(e.into()),
    }
}

/// Check if a bot has any active (non-revoked) API keys.
/// Whether a bot has standing access — an active (non-revoked) API key, or a
/// non-revoked OAuth token. Mirrors the Connected Tools "connected" state
/// (LIFIC-13): access is granted until explicitly revoked/disconnected,
/// independent of OAuth token expiry (the agent self-heals via re-auth).
/// Used to refuse re-connecting a tool that's already connected via either door.
pub fn bot_is_connected(conn: &Connection, bot_id: i64) -> Result<bool, LificError> {
    conn.query_row(
        "SELECT
                EXISTS(SELECT 1 FROM api_keys WHERE user_id = ?1 AND revoked = 0)
                OR EXISTS(SELECT 1 FROM oauth_tokens WHERE user_id = ?1 AND revoked = 0)",
        params![bot_id],
        |row| row.get(0),
    )
    .map_err(Into::into)
}

/// Ensure a per-tool bot exists for `owner_id`, reusing an existing one rather
/// than minting a duplicate. The bot username is `{tool_id}-{owner.username}`
/// — the same convention `lific connect` and the web UI's Connected Tools use,
/// so a bot minted at OAuth approval is indistinguishable from one connected
/// another way. Returns the bot user.
///
/// LIFIC-13: the single find-or-create decision all three doors (OAuth
/// approval, `lific connect`, web create_bot) share.
///
/// LIFIC-17: dedupe keys on the stable `(owner_id, tool_id)` pair, not the
/// derived username, so renaming the owner never orphans the agent. Legacy
/// bots minted before the `tool_id` column existed (tool_id NULL) are found
/// by their owner and tool prefix and backfilled in place — safe even when the
/// owner renamed in the meantime, since the prefix match skips the stale owner
/// name embedded in their username.
/// Re-resolve the bot for `(owner_id, tool_id)` after a write was rejected by
/// a constraint.
///
/// LIF-367: with `idx_users_owner_tool` in place, the loser of a concurrent
/// `ensure_bot` no longer silently mints a duplicate — its write fails. That
/// is the right outcome for the data and the wrong one for the caller, who
/// asked for "the bot for this tool" and should get the winner's row rather
/// than a 500. So look the pair up again: if somebody won the race, their bot
/// is the answer. If the lookup still misses, the constraint that fired was
/// something else (most likely the derived username colliding with an
/// unrelated account), and `rejection` — the error the write actually
/// produced — stands.
fn resolve_bot_conflict(
    conn: &Connection,
    owner_id: i64,
    tool_id: &str,
    rejection: LificError,
) -> Result<User, LificError> {
    match find_bot_by_owner_and_tool(conn, owner_id, tool_id)? {
        Some(winner) => Ok(winner),
        None => Err(rejection),
    }
}

pub fn ensure_bot(
    conn: &Connection,
    owner_id: i64,
    tool_id: &str,
    display_name: &str,
) -> Result<User, LificError> {
    // Structured dedupe first: stable across owner renames.
    if let Some(existing) = find_bot_by_owner_and_tool(conn, owner_id, tool_id)? {
        return Ok(existing);
    }
    // Legacy bot: pre-migration, tool_id NULL, keyed only by owner + tool.
    // Reuse and backfill it.
    if let Some(legacy) = find_bot_legacy_by_tool_prefix(conn, owner_id, tool_id)? {
        return match conn.execute(
            "UPDATE users SET tool_id = ?1 WHERE id = ?2",
            params![tool_id, legacy.id],
        ) {
            Ok(_) => Ok(legacy),
            // A concurrent connect claimed the pair between our lookup and
            // this backfill; the legacy row stays legacy and the winner wins.
            Err(e) => {
                let e: LificError = e.into();
                if is_constraint_violation(&e) {
                    resolve_bot_conflict(conn, owner_id, tool_id, e)
                } else {
                    Err(e)
                }
            }
        };
    }
    let owner_username = get_user_by_id(conn, owner_id)?.username;
    let bot_username = format!("{tool_id}-{owner_username}");
    match create_bot_user(conn, owner_id, &bot_username, display_name, Some(tool_id)) {
        Ok(bot) => Ok(bot),
        // The one thing that makes create_bot_user return BadRequest is SQLite
        // rejecting the row, which after LIF-367 usually means a concurrent
        // connect already minted this exact agent.
        Err(e @ LificError::BadRequest(_)) => resolve_bot_conflict(conn, owner_id, tool_id, e),
        Err(e) => Err(e),
    }
}

/// List all bots owned by a specific user.
pub fn list_bots(
    conn: &Connection,
    owner_id: i64,
) -> Result<Vec<crate::db::models::Bot>, LificError> {
    let mut stmt = conn.prepare_cached(
        "SELECT u.id, u.username, u.display_name, u.owner_id, u.created_at,
                EXISTS(
                    SELECT 1 FROM api_keys k WHERE k.user_id = u.id AND k.revoked = 0
                    UNION
                    SELECT 1 FROM oauth_tokens t WHERE t.user_id = u.id AND t.revoked = 0
                ) as connected
         FROM users u
         WHERE u.is_bot = 1 AND u.owner_id = ?1
         ORDER BY u.created_at DESC",
    )?;
    let rows = stmt.query_map(params![owner_id], |row| {
        Ok(crate::db::models::Bot {
            id: row.get(0)?,
            username: row.get(1)?,
            display_name: row.get(2)?,
            owner_id: row.get(3)?,
            created_at: row.get(4)?,
            connected: row.get(5)?,
        })
    })?;
    rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
}

/// Verify a bot both exists and is owned by `requester_id` (or the requester
/// is admin). Returns the bot's id on success. Shared by [`disconnect_bot`]
/// and [`delete_bot`], whose ownership rules are identical.
fn verify_bot_owner(
    conn: &Connection,
    bot_id: i64,
    requester_id: i64,
    is_admin: bool,
    action: &str,
) -> Result<(), LificError> {
    let owner_id: Option<i64> = conn
        .query_row(
            "SELECT owner_id FROM users WHERE id = ?1 AND is_bot = 1",
            params![bot_id],
            |row| row.get(0),
        )
        .map_err(|_| LificError::NotFound("bot not found".into()))?;

    if owner_id != Some(requester_id) && !is_admin {
        return Err(LificError::BadRequest(format!(
            "you can only {action} your own bots"
        )));
    }
    Ok(())
}

/// Disconnect a bot: revoke its credentials (API keys and OAuth tokens) so the
/// bot can no longer act. The bot's identity is kept — reconnecting later
/// reuses it. Only the owner or admin can do this.
pub fn disconnect_bot(
    conn: &Connection,
    bot_id: i64,
    requester_id: i64,
    is_admin: bool,
) -> Result<(), LificError> {
    verify_bot_owner(conn, bot_id, requester_id, is_admin, "disconnect")?;

    // Revoke all API keys for this bot
    conn.execute(
        "UPDATE api_keys SET revoked = 1 WHERE user_id = ?1 AND revoked = 0",
        params![bot_id],
    )?;
    // Revoke all OAuth tokens for this bot (LIFIC-13 follow-up): an
    // OAuth-connected agent has no API key, so without this "Disconnect"
    // would leave its access token live. Rows are kept — reconnectable bot.
    conn.execute(
        "UPDATE oauth_tokens SET revoked = 1 WHERE user_id = ?1 AND revoked = 0",
        params![bot_id],
    )?;
    // Kill in-flight OAuth handshakes too (PR #23 review): an approved but
    // not-yet-exchanged device code or auth code would otherwise mint a
    // fresh token for the bot the owner just disconnected.
    conn.execute(
        "UPDATE oauth_device_codes SET status = 'denied' \
         WHERE user_id = ?1 AND status IN ('pending', 'approved')",
        params![bot_id],
    )?;
    conn.execute(
        "UPDATE oauth_codes SET used = 1 WHERE user_id = ?1 AND used = 0",
        params![bot_id],
    )?;

    Ok(())
}

/// Permanently delete a bot user, its API keys, its OAuth tokens, and the
/// comments it made. The identity is gone, so any OAuth token rows are shred
/// rather than revoked. Only the owner or an admin can do this.
pub fn delete_bot(
    conn: &Connection,
    bot_id: i64,
    requester_id: i64,
    is_admin: bool,
) -> Result<(), LificError> {
    verify_bot_owner(conn, bot_id, requester_id, is_admin, "delete")?;

    // Delete API keys first (FK constraint)
    conn.execute("DELETE FROM api_keys WHERE user_id = ?1", params![bot_id])?;
    // Delete the bot's OAuth tokens (LIFIC-13 follow-up): leaves no dangling
    // rows pointing at a removed identity.
    conn.execute(
        "DELETE FROM oauth_tokens WHERE user_id = ?1",
        params![bot_id],
    )?;
    // And its in-flight OAuth handshakes (PR #23 review): a pending device or
    // auth code bound to a deleted identity must not stay exchangeable.
    conn.execute(
        "DELETE FROM oauth_device_codes WHERE user_id = ?1",
        params![bot_id],
    )?;
    conn.execute(
        "DELETE FROM oauth_codes WHERE user_id = ?1",
        params![bot_id],
    )?;

    // Delete any comments made by this bot (or reassign — deleting for now)
    conn.execute("DELETE FROM comments WHERE user_id = ?1", params![bot_id])?;

    // Delete the bot user
    let changed = conn.execute(
        "DELETE FROM users WHERE id = ?1 AND is_bot = 1",
        params![bot_id],
    )?;

    if changed == 0 {
        return Err(LificError::NotFound("bot not found".into()));
    }

    Ok(())
}

/// List API keys belonging to a specific user.
pub fn list_user_keys(
    conn: &Connection,
    user_id: i64,
) -> Result<Vec<crate::db::models::UserApiKey>, LificError> {
    let mut stmt = conn.prepare_cached(
        "SELECT id, name, created_at, expires_at, revoked
         FROM api_keys WHERE user_id = ?1
         ORDER BY created_at DESC",
    )?;
    let rows = stmt.query_map(params![user_id], |row| {
        Ok(crate::db::models::UserApiKey {
            id: row.get(0)?,
            name: row.get(1)?,
            created_at: row.get(2)?,
            expires_at: row.get(3)?,
            revoked: row.get(4)?,
        })
    })?;
    rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
}

/// Revoke an API key, but only if it belongs to the given user (or user is admin).
pub fn revoke_user_key(
    conn: &Connection,
    key_id: i64,
    user_id: i64,
    is_admin: bool,
) -> Result<(), LificError> {
    let changed = if is_admin {
        conn.execute(
            "UPDATE api_keys SET revoked = 1 WHERE id = ?1 AND revoked = 0",
            params![key_id],
        )?
    } else {
        conn.execute(
            "UPDATE api_keys SET revoked = 1 WHERE id = ?1 AND user_id = ?2 AND revoked = 0",
            params![key_id, user_id],
        )?
    };

    if changed == 0 {
        return Err(LificError::NotFound(
            "key not found or already revoked".into(),
        ));
    }
    Ok(())
}

// ── Tests ────────────────────────────────────────────────────

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

    fn test_db() -> db::DbPool {
        db::open_memory().expect("test db")
    }

    fn test_create_user(conn: &Connection) -> User {
        create_user(
            conn,
            &CreateUser {
                username: "blake".into(),
                email: "blake@example.com".into(),
                password: "securepassword123".into(),
                display_name: Some("Blake".into()),
                is_admin: true,
                is_bot: false,
            },
        )
        .expect("create user")
    }

    #[test]
    fn has_human_users_false_when_empty_then_true_after_signup() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        assert!(!has_human_users(&conn).unwrap(), "fresh db has no humans");

        test_create_user(&conn);
        assert!(
            has_human_users(&conn).unwrap(),
            "human signup flips it true"
        );
    }

    #[test]
    fn has_human_users_ignores_bot_only_instances() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        // A connected tool (bot) is not a person who signed up.
        create_user(
            &conn,
            &CreateUser {
                username: "agent".into(),
                email: "agent@example.com".into(),
                password: "securepassword123".into(),
                display_name: None,
                is_admin: false,
                is_bot: true,
            },
        )
        .unwrap();
        assert!(
            !has_human_users(&conn).unwrap(),
            "a bot-only instance still reads as having no human accounts"
        );
    }

    #[test]
    fn derive_username_propagates_database_errors() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        conn.execute("DROP TABLE users", []).unwrap();

        assert!(matches!(
            derive_username(&conn, "Blake"),
            Err(LificError::Database(_))
        ));
    }

    // ── ensure_bot (LIFIC-13) ────────────────────────────────

    #[test]
    fn ensure_bot_creates_a_new_bot_for_the_owner() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);

        let bot_id = ensure_bot(&conn, owner.id, "claude-code", "Claude Code")
            .unwrap()
            .id;
        let bot = get_user_by_id(&conn, bot_id).unwrap();
        assert!(bot.is_bot, "minted user is a bot");
        assert_eq!(bot.username, "claude-code-blake");
        assert_eq!(bot.display_name, "Claude Code");
        let listed = list_bots(&conn, owner.id).unwrap();
        assert_eq!(listed.len(), 1, "one bot owned by this user");
        assert_eq!(listed[0].owner_id, Some(owner.id));
    }

    #[test]
    fn ensure_bot_reuses_existing_bot_for_same_tool_and_owner() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);

        let first = ensure_bot(&conn, owner.id, "opencode", "OpenCode")
            .unwrap()
            .id;
        let second = ensure_bot(&conn, owner.id, "opencode", "OpenCode")
            .unwrap()
            .id;
        assert_eq!(first, second, "re-approval must reuse, not duplicate");
    }

    #[test]
    fn ensure_bot_distinguishes_owners() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner_a = test_create_user(&conn);
        let owner_b = create_user(
            &conn,
            &CreateUser {
                username: "ada".into(),
                email: "ada@example.com".into(),
                password: "securepassword123".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();

        let a = ensure_bot(&conn, owner_a.id, "opencode", "OpenCode")
            .unwrap()
            .id;
        let b = ensure_bot(&conn, owner_b.id, "opencode", "OpenCode")
            .unwrap()
            .id;
        assert_ne!(a, b, "each owner gets its own bot for the same tool");
    }

    // ── stable dedupe across owner rename (LIFIC-17) ──────────

    // The bot identity is keyed on (owner_id, tool_id), not the derived
    // `{tool}-{owner}` username string. Renaming the owner changes the string
    // but not the (owner_id, tool_id) pair, so a re-connect must reuse the
    // original bot rather than mint a duplicate.
    #[test]
    fn ensure_bot_reuses_existing_bot_after_owner_rename() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn); // username "blake"

        let first = ensure_bot(&conn, owner.id, "opencode", "OpenCode")
            .unwrap()
            .id;

        // Simulate the owner renaming their account: username changes, id stays.
        conn.execute(
            "UPDATE users SET username = ?1 WHERE id = ?2",
            params!["renamed-blake", owner.id],
        )
        .unwrap();

        let second = ensure_bot(&conn, owner.id, "opencode", "OpenCode")
            .unwrap()
            .id;
        assert_eq!(
            first, second,
            "renaming the owner must not orphan the agent"
        );
    }

    // Bots minted before the tool_id column existed (tool_id NULL) are still
    // found by their legacy `{tool}-{owner}` username and backfilled, so an
    // existing install does not duplicate agents on the first post-upgrade
    // reconnect.
    #[test]
    fn ensure_bot_backfills_legacy_bot_by_username() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn); // username "blake"
        // A pre-migration bot: username "opencode-blake", tool_id NULL.
        let legacy = create_bot_user(&conn, owner.id, "opencode-blake", "OpenCode", None).unwrap();

        let reused = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();
        assert_eq!(
            reused.id, legacy.id,
            "a legacy bot keyed by username must be reused, not duplicated"
        );
        let stored: Option<String> = conn
            .query_row(
                "SELECT tool_id FROM users WHERE id = ?1",
                params![legacy.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(
            stored.as_deref(),
            Some("opencode"),
            "legacy bot tool_id backfilled"
        );
    }

    // The legacy backfill holds even when the owner renamed *before* the
    // reconnect: the legacy username embeds the old owner name, so the match
    // keys on owner id + tool prefix, never the current owner username.
    #[test]
    fn ensure_bot_backfills_legacy_bot_even_after_owner_rename() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn); // username "blake"
        // A pre-migration bot whose username still has the old owner name.
        let legacy =
            create_bot_user(&conn, owner.id, "opencode-oldname", "OpenCode", None).unwrap();
        // The owner renames before ever reconnecting.
        conn.execute(
            "UPDATE users SET username = ?1 WHERE id = ?2",
            params!["new-name", owner.id],
        )
        .unwrap();

        let reused = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();
        assert_eq!(
            reused.id, legacy.id,
            "renaming before a legacy reconnect must still reuse, not duplicate"
        );
    }

    // ── (owner_id, tool_id) uniqueness in the schema (LIF-367) ───

    /// Insert a bot row straight into the table, bypassing every
    /// application-level dedupe, so the schema is the only thing that can
    /// object. Returns the raw rusqlite result.
    fn raw_insert_bot(
        conn: &Connection,
        username: &str,
        owner_id: i64,
        tool_id: Option<&str>,
    ) -> Result<usize, rusqlite::Error> {
        conn.execute(
            "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot, owner_id, tool_id)
             VALUES (?1, ?2, 'x', 'Agent', 0, 1, ?3, ?4)",
            params![username, format!("{username}@bot.local"), owner_id, tool_id],
        )
    }

    fn is_constraint_err(err: &rusqlite::Error) -> bool {
        matches!(
            err,
            rusqlite::Error::SqliteFailure(e, _)
                if e.code == rusqlite::ErrorCode::ConstraintViolation
        )
    }

    // The pairing used to be enforced by `ensure_bot` reading before it wrote,
    // which two concurrent connects can both win. The database now refuses the
    // second row outright.
    #[test]
    fn second_bot_for_the_same_owner_and_tool_is_rejected_by_the_schema() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();

        // A distinct username, so the users.username UNIQUE is not what fires:
        // only idx_users_owner_tool can reject this.
        let err = raw_insert_bot(&conn, "opencode-blake-2", owner.id, Some("opencode"))
            .expect_err("duplicate (owner_id, tool_id) bot must be rejected");
        assert!(
            is_constraint_err(&err),
            "expected a constraint violation, got {err:?}"
        );
        let bots: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM users WHERE is_bot = 1 AND owner_id = ?1",
                params![owner.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(bots, 1, "the rejected insert left no row behind");
    }

    // The index is partial on purpose. Humans and legacy bots awaiting lazy
    // backfill both carry tool_id NULL and must not collide with each other,
    // and one owner may connect any number of *different* tools.
    #[test]
    fn bot_uniqueness_ignores_null_tool_ids_and_distinct_tools() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);

        raw_insert_bot(&conn, "legacy-one", owner.id, None).unwrap();
        raw_insert_bot(&conn, "legacy-two", owner.id, None)
            .expect("two legacy bots with tool_id NULL are allowed");
        raw_insert_bot(&conn, "opencode-blake", owner.id, Some("opencode")).unwrap();
        raw_insert_bot(&conn, "claude-code-blake", owner.id, Some("claude-code"))
            .expect("a different tool for the same owner is allowed");
    }

    // Whatever order the connects land in, the owner ends up with exactly one
    // agent for the tool and every caller gets that same identity back.
    #[test]
    fn ensure_bot_is_idempotent_across_repeated_connects() {
        let pool = test_db();
        let owner_id = {
            let conn = pool.write().unwrap();
            test_create_user(&conn).id
        };

        let ids: [i64; 4] = std::thread::scope(|scope| {
            // Build every handle before joining so the connects actually overlap.
            let handles: [_; 4] = std::array::from_fn(|_| {
                let pool = pool.clone();
                scope.spawn(move || {
                    let conn = pool.write().unwrap();
                    ensure_bot(&conn, owner_id, "opencode", "OpenCode")
                        .expect("ensure_bot must not fail on a repeat connect")
                        .id
                })
            });
            handles.map(|handle| handle.join().unwrap())
        });

        assert!(
            ids.windows(2).all(|w| w[0] == w[1]),
            "every connect must resolve to the same agent, got {ids:?}"
        );
        let conn = pool.write().unwrap();
        let bots: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM users WHERE is_bot = 1 AND owner_id = ?1 AND tool_id = 'opencode'",
                params![owner_id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(bots, 1, "no duplicate agent for the pair");
    }

    // The recovery path itself: a mint rejected by the index means somebody
    // else already minted the pair, and the caller wants that winner, not an
    // error.
    #[test]
    fn a_rejected_mint_resolves_to_the_bot_that_won_the_race() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let winner = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();

        let resolved = resolve_bot_conflict(
            &conn,
            owner.id,
            "opencode",
            LificError::BadRequest("rejected".into()),
        )
        .unwrap();
        assert_eq!(resolved.id, winner.id, "the winner's bot is the answer");
    }

    // ...but a constraint that fired for some other reason must not be
    // reported as a successful connect. Here an unrelated account already
    // holds the username the bot would take, so there is no winner to return.
    #[test]
    fn a_rejected_mint_with_no_winner_stays_an_error() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn); // "blake"
        create_user(
            &conn,
            &CreateUser {
                username: "opencode-blake".into(),
                email: "squatter@example.com".into(),
                password: "securepassword123".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();

        let err = ensure_bot(&conn, owner.id, "opencode", "OpenCode")
            .expect_err("a username collision is still a failure");
        assert!(
            matches!(err, LificError::BadRequest(ref m) if m.contains("already connected")),
            "expected the connect-conflict message, got {err:?}"
        );
    }

    // ── migration 038: dedupe of rows minted before the index (LIF-367) ──

    // Rewinds the pool to the schema-037 shape, seeds the duplicate an
    // unguarded `ensure_bot` could produce along with rows referencing the
    // loser, then applies 038 verbatim and checks the survivor absorbed
    // everything.
    //
    // The runner (`migrate::run`) only ever applies migrations *newer* than
    // the highest recorded version, so it cannot be asked to replay one in
    // isolation; the migration SQL is applied directly instead, which is the
    // same statements in the same order.
    #[test]
    fn migration_038_keeps_the_oldest_bot_and_repoints_every_reference() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        conn.execute_batch("DROP INDEX idx_users_owner_tool;")
            .unwrap();

        let owner = test_create_user(&conn);
        raw_insert_bot(&conn, "opencode-blake", owner.id, Some("opencode")).unwrap();
        let survivor = conn.last_insert_rowid();
        raw_insert_bot(&conn, "opencode-oldname", owner.id, Some("opencode")).unwrap();
        let loser = conn.last_insert_rowid();
        assert!(loser > survivor, "the loser is the newer row");

        // A bot for a different tool, and a legacy NULL-tool bot: both must be
        // left exactly where they are.
        raw_insert_bot(&conn, "claude-code-blake", owner.id, Some("claude-code")).unwrap();
        let untouched = conn.last_insert_rowid();

        conn.execute_batch(
            "INSERT INTO projects (name, identifier) VALUES ('Lific', 'LIF');
             INSERT INTO issues (project_id, sequence, title) VALUES (1, 1, 'An issue');",
        )
        .unwrap();

        // Every user-referencing column in the schema, pointed at the loser.
        conn.execute(
            "INSERT INTO api_keys (name, key_hash, user_id) VALUES ('k', 'h', ?1)",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO sessions (token, user_id, expires_at) VALUES ('t', ?1, datetime('now', '+1 day'))",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO comments (issue_id, user_id, content) VALUES (1, ?1, 'hi')",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO comment_mentions (comment_id, user_id) VALUES (1, ?1)",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO attachments (sha256, filename, mime, size_bytes, uploader_id)
             VALUES (?1, 'f.png', 'image/png', 1, ?2)",
            params![crate::storage::AttachmentStore::hash_bytes(b"abc"), loser],
        )
        .unwrap();
        conn.execute("UPDATE projects SET lead_user_id = ?1", params![loser])
            .unwrap();
        conn.execute(
            "INSERT INTO oauth_clients (client_id, client_name, redirect_uris)
             VALUES ('c', 'Test', '[\"http://localhost\"]')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_tokens (access_token, client_id, expires_at, user_id)
             VALUES ('tok', 'c', datetime('now', '+1 hour'), ?1)",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_codes (code, client_id, redirect_uri, code_challenge, expires_at, user_id)
             VALUES ('code', 'c', 'http://localhost', 'ch', datetime('now', '+1 hour'), ?1)",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_device_codes (device_code_hash, user_code, expires_at, user_id)
             VALUES ('dh', 'ABCD-EFGH', datetime('now', '+1 hour'), ?1)",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO audit_log (actor_user_id, transport, entity_type, entity_id, action, field)
             VALUES (?1, 'mcp', 'issue', 1, 'create', 'seeded')",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO saved_views (project_id, user_id, name, config) VALUES (1, ?1, 'Mine', '{}')",
            params![loser],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO project_groups (user_id, name) VALUES (?1, 'Work')",
            params![loser],
        )
        .unwrap();
        // Both rows are members of the same project, at different roles, and
        // the *loser* holds the stronger one. Collapsing the pair must keep
        // the privilege, not whichever row happened to survive.
        conn.execute(
            "INSERT INTO project_members (project_id, user_id, role) VALUES (1, ?1, 'viewer')",
            params![survivor],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO project_members (project_id, user_id, role) VALUES (1, ?1, 'lead')",
            params![loser],
        )
        .unwrap();

        conn.execute_batch(include_str!(
            "../../../migrations/038_bot_identity_unique.sql"
        ))
        .unwrap();

        // The loser is gone, the survivor and the unrelated bot are not.
        let remaining: Vec<i64> = conn
            .prepare("SELECT id FROM users WHERE is_bot = 1 ORDER BY id")
            .unwrap()
            .query_map([], |r| r.get(0))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(remaining, vec![survivor, untouched]);

        let owns = |sql: &str| -> i64 { conn.query_row(sql, [], |r| r.get(0)).unwrap() };
        assert_eq!(owns("SELECT user_id FROM api_keys"), survivor);
        assert_eq!(owns("SELECT user_id FROM sessions"), survivor);
        assert_eq!(owns("SELECT user_id FROM comments"), survivor);
        assert_eq!(owns("SELECT user_id FROM comment_mentions"), survivor);
        assert_eq!(owns("SELECT uploader_id FROM attachments"), survivor);
        assert_eq!(owns("SELECT lead_user_id FROM projects"), survivor);
        assert_eq!(owns("SELECT user_id FROM oauth_tokens"), survivor);
        assert_eq!(owns("SELECT user_id FROM oauth_codes"), survivor);
        assert_eq!(owns("SELECT user_id FROM oauth_device_codes"), survivor);
        assert_eq!(
            owns("SELECT actor_user_id FROM audit_log WHERE field = 'seeded'"),
            survivor
        );
        assert_eq!(owns("SELECT user_id FROM saved_views"), survivor);
        assert_eq!(owns("SELECT user_id FROM project_groups"), survivor);
        assert_eq!(
            owns(&format!(
                "SELECT COUNT(*) FROM audit_log WHERE actor_user_id = {loser}"
            )),
            0,
            "nothing is still attributed to the deleted row"
        );

        // One membership left, carrying the stronger of the two roles.
        let members: Vec<(i64, String)> = conn
            .prepare("SELECT user_id, role FROM project_members")
            .unwrap()
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(members, vec![(survivor, "lead".to_string())]);

        // And the constraint is now in force.
        let err = raw_insert_bot(&conn, "opencode-third", owner.id, Some("opencode"))
            .expect_err("038 leaves the pair unique");
        assert!(is_constraint_err(&err), "got {err:?}");
    }

    // Where a row cannot simply be repointed because the survivor already
    // holds one for the same unique key, nothing may be silently thrown away:
    // roles merge upward, group items are reparented, and views that only
    // share a name are renamed rather than dropped. Three duplicate bots, so
    // the loser-versus-loser collisions are covered too.
    #[test]
    fn migration_038_merges_colliding_rows_instead_of_dropping_them() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        conn.execute_batch("DROP INDEX idx_users_owner_tool;")
            .unwrap();

        let owner = test_create_user(&conn);
        raw_insert_bot(&conn, "opencode-blake", owner.id, Some("opencode")).unwrap();
        let survivor = conn.last_insert_rowid();
        raw_insert_bot(&conn, "opencode-second", owner.id, Some("opencode")).unwrap();
        let loser_a = conn.last_insert_rowid();
        raw_insert_bot(&conn, "opencode-third", owner.id, Some("opencode")).unwrap();
        let loser_b = conn.last_insert_rowid();

        conn.execute_batch(
            "INSERT INTO projects (name, identifier) VALUES ('One', 'ONE'), ('Two', 'TWO');",
        )
        .unwrap();

        // Roles: the survivor is a viewer where a loser leads, and a loser
        // holds the only membership of the second project.
        for (project, user, role) in [
            (1, survivor, "viewer"),
            (1, loser_a, "lead"),
            (2, loser_b, "maintainer"),
        ] {
            conn.execute(
                "INSERT INTO project_members (project_id, user_id, role) VALUES (?1, ?2, ?3)",
                params![project, user, role],
            )
            .unwrap();
        }

        // Groups: 'Work' exists three times over, each holding items; 'Solo'
        // belongs to a loser alone.
        for (id, user, name) in [
            (100, survivor, "Work"),
            (200, loser_a, "Work"),
            (300, loser_a, "Solo"),
            (400, loser_b, "Work"),
        ] {
            conn.execute(
                "INSERT INTO project_groups (id, user_id, name) VALUES (?1, ?2, ?3)",
                params![id, user, name],
            )
            .unwrap();
        }
        conn.execute_batch(
            "INSERT INTO project_group_items (group_id, project_id)
             VALUES (100, 1), (200, 1), (200, 2), (300, 2), (400, 2);",
        )
        .unwrap();

        // Views: one name, three different configs, plus a loser-only view.
        for (id, user, name, config) in [
            (1, survivor, "Mine", "{\"a\":1}"),
            (2, loser_a, "Mine", "{\"b\":2}"),
            (3, loser_a, "Solo", "{}"),
            (4, loser_b, "Mine", "{\"c\":3}"),
        ] {
            conn.execute(
                "INSERT INTO saved_views (id, project_id, user_id, name, config)
                 VALUES (?1, 1, ?2, ?3, ?4)",
                params![id, user, name, config],
            )
            .unwrap();
        }

        conn.execute_batch(include_str!(
            "../../../migrations/038_bot_identity_unique.sql"
        ))
        .unwrap();

        // The strongest role wins per project; nothing is dropped.
        let members: Vec<(i64, i64, String)> = conn
            .prepare("SELECT project_id, user_id, role FROM project_members ORDER BY project_id")
            .unwrap()
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(
            members,
            vec![
                (1, survivor, "lead".to_string()),
                (2, survivor, "maintainer".to_string()),
            ]
        );

        // The three 'Work' groups collapse into the survivor's, and every
        // project that was in any of them is still in the one that remains.
        let groups: Vec<(i64, i64, String)> = conn
            .prepare("SELECT id, user_id, name FROM project_groups ORDER BY id")
            .unwrap()
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(
            groups,
            vec![
                (100, survivor, "Work".to_string()),
                (300, survivor, "Solo".to_string()),
            ]
        );
        let items: Vec<(i64, i64)> = conn
            .prepare("SELECT group_id, project_id FROM project_group_items ORDER BY group_id, project_id")
            .unwrap()
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(
            items,
            vec![(100, 1), (100, 2), (300, 2)],
            "the reparented item survived and the duplicate collapsed"
        );

        // Every view survives with its own config; the name clash is resolved
        // by suffixing the newer rows, not by deleting them.
        let views: Vec<(i64, i64, String, String)> = conn
            .prepare("SELECT id, user_id, name, config FROM saved_views ORDER BY id")
            .unwrap()
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(
            views,
            vec![
                (1, survivor, "Mine".to_string(), "{\"a\":1}".to_string()),
                (
                    2,
                    survivor,
                    "Mine (merged 2)".to_string(),
                    "{\"b\":2}".to_string()
                ),
                (3, survivor, "Solo".to_string(), "{}".to_string()),
                (
                    4,
                    survivor,
                    "Mine (merged 4)".to_string(),
                    "{\"c\":3}".to_string()
                ),
            ]
        );

        // Both losers are gone and no reference dangles.
        let bots: Vec<i64> = conn
            .prepare("SELECT id FROM users WHERE is_bot = 1")
            .unwrap()
            .query_map([], |r| r.get(0))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(bots, vec![survivor], "{loser_a} and {loser_b} merged away");
        let dangling: i64 = conn
            .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(dangling, 0, "no foreign key left pointing at a deleted row");
    }

    // ── disconnect/delete bot credential revocation (LIFIC-13 follow-up) ──

    /// Insert an active (non-revoked) `oauth_tokens` row bound to `user_id`.
    fn insert_oauth_token_for(conn: &Connection, user_id: i64) -> i64 {
        let token_hash = format!("testtoken-{user_id}-{}", user_id);
        let client_id = "test-client";
        conn.execute(
            "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES (?1, 'Test', '[\"http://localhost\"]')",
            params![client_id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id)
             VALUES (?1, ?2, datetime('now', '+1 hour'), 'mcp', ?3)",
            params![token_hash, client_id, user_id],
        )
        .unwrap();
        let id: i64 = conn
            .query_row(
                "SELECT rowid FROM oauth_tokens WHERE access_token = ?1",
                params![token_hash],
                |r| r.get(0),
            )
            .unwrap();
        id
    }

    #[test]
    fn disconnect_bot_revokes_bots_oauth_tokens_but_keeps_bot() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let bot = ensure_bot(&conn, owner.id, "claude-code", "Claude Code").unwrap();
        insert_oauth_token_for(&conn, bot.id);

        disconnect_bot(&conn, bot.id, owner.id, false).unwrap();

        // The bot and its OAuth tokens still exist (reconnectable), but tokens revoked.
        let revoked: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_tokens WHERE user_id = ?1 AND revoked = 1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(revoked, 1, "bot's OAuth token revoked");
        let still_there: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_tokens WHERE user_id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(still_there, 1, "token row kept — reconnectable bot");
        let bot_exists: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM users WHERE id = ?1 AND is_bot = 1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(bot_exists, 1, "bot identity kept after disconnect");
    }

    #[test]
    fn delete_bot_removes_its_oauth_token_rows() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let bot = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();
        insert_oauth_token_for(&conn, bot.id);

        delete_bot(&conn, bot.id, owner.id, false).unwrap();

        let tokens: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_tokens WHERE user_id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(tokens, 0, "delete shreds the bot's OAuth token rows");
        let bot_rows: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM users WHERE id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(bot_rows, 0, "bot identity removed");
    }

    /// Seed an in-flight OAuth handshake pair (approved device code + unused
    /// auth code) bound to `user_id`, for the disconnect/delete revocation
    /// tests (PR #23 review).
    fn insert_pending_handshakes_for(conn: &Connection, user_id: i64) {
        conn.execute(
            "INSERT INTO oauth_device_codes
                (device_code_hash, user_code, expires_at, status, user_id)
             VALUES ('devhash', 'BCDF-GHJK', datetime('now', '+1 hour'), 'approved', ?1)",
            params![user_id],
        )
        .unwrap();
        conn.execute(
            "INSERT OR IGNORE INTO oauth_clients (client_id, client_name, redirect_uris)
             VALUES ('c1', 'Test', '[]')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_codes
                (code, client_id, redirect_uri, code_challenge, expires_at, user_id)
             VALUES ('code1', 'c1', 'http://localhost/cb', 'ch', datetime('now', '+1 hour'), ?1)",
            params![user_id],
        )
        .unwrap();
    }

    #[test]
    fn disconnect_bot_kills_in_flight_oauth_handshakes() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let bot = ensure_bot(&conn, owner.id, "claude-code", "Claude Code").unwrap();
        insert_pending_handshakes_for(&conn, bot.id);

        disconnect_bot(&conn, bot.id, owner.id, false).unwrap();

        let device_status: String = conn
            .query_row(
                "SELECT status FROM oauth_device_codes WHERE user_id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(device_status, "denied", "approved device code denied");
        let code_used: i64 = conn
            .query_row(
                "SELECT used FROM oauth_codes WHERE user_id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(code_used, 1, "pending auth code burned");
    }

    #[test]
    fn delete_bot_removes_in_flight_oauth_handshakes() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let bot = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();
        insert_pending_handshakes_for(&conn, bot.id);

        delete_bot(&conn, bot.id, owner.id, false).unwrap();

        let device_rows: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_device_codes WHERE user_id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        let code_rows: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_codes WHERE user_id = ?1",
                params![bot.id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(
            (device_rows, code_rows),
            (0, 0),
            "no exchangeable handshakes survive bot deletion"
        );
    }

    // ── list_bots / connected semantics (LIFIC-13 OAuth bots) ──

    #[test]
    fn bot_with_oauth_token_lists_as_connected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let bot = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();
        // No API key — connected purely by an OAuth token (LIFIC-13 path).
        insert_oauth_token_for(&conn, bot.id);

        let listed = list_bots(&conn, owner.id).unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].id, bot.id);
        assert!(
            listed[0].connected,
            "an OAuth-connected bot must list as connected (no API key involved)"
        );
        assert!(bot_is_connected(&conn, bot.id).unwrap());
    }

    #[test]
    fn bot_with_only_revoked_credentials_lists_as_disconnected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let owner = test_create_user(&conn);
        let bot = ensure_bot(&conn, owner.id, "opencode", "OpenCode").unwrap();
        insert_oauth_token_for(&conn, bot.id);
        // Revoke the token — the bot is no longer connected.
        conn.execute(
            "UPDATE oauth_tokens SET revoked = 1 WHERE user_id = ?1",
            params![bot.id],
        )
        .unwrap();

        let listed = list_bots(&conn, owner.id).unwrap();
        assert!(
            !listed[0].connected,
            "a bot with only revoked credentials must list as disconnected"
        );
        assert!(!bot_is_connected(&conn, bot.id).unwrap());
    }

    #[test]
    fn bot_is_connected_propagates_database_errors() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        conn.execute("DROP TABLE oauth_tokens", []).unwrap();

        assert!(matches!(
            bot_is_connected(&conn, 1),
            Err(LificError::Database(_))
        ));
    }

    #[test]
    fn api_key_connected_bot_still_lists_as_connected() {
        let pool = test_db();
        let (owner, bot) = {
            let conn = pool.write().unwrap();
            let owner = test_create_user(&conn);
            let bot = ensure_bot(&conn, owner.id, "claude-code", "Claude Code").unwrap();
            (owner.id, bot.id)
        };
        // The classic `lific connect` path: an active API key, no OAuth token.
        let name = format!("claude-code-{}", {
            let conn = pool.read().unwrap();
            get_user_by_id(&conn, owner).unwrap().username
        });
        let manager = crate::auth::create_key_manager().unwrap();
        let _ = crate::auth::create_api_key(&pool, &manager, &name, Some(bot)).unwrap();

        let listed = {
            let conn = pool.read().unwrap();
            list_bots(&conn, owner).unwrap()
        };
        assert!(
            listed.iter().any(|b| b.id == bot && b.connected),
            "API-key-connected bot (legacy path) still lists as connected"
        );
    }

    // ── LIF-190: profile + password updates ─────────────────

    #[test]
    fn update_profile_changes_display_name_and_email() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let updated =
            update_profile(&conn, user.id, Some("Blake W"), Some("NEW@Example.com")).unwrap();
        assert_eq!(updated.display_name, "Blake W");
        assert_eq!(updated.email, "new@example.com"); // normalized lowercase
    }

    #[test]
    fn update_profile_partial_leaves_other_field() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let updated = update_profile(&conn, user.id, Some("Renamed"), None).unwrap();
        assert_eq!(updated.display_name, "Renamed");
        assert_eq!(updated.email, "blake@example.com"); // untouched
    }

    #[test]
    fn update_profile_rejects_blank_name_and_bad_email() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        assert!(update_profile(&conn, user.id, Some("   "), None).is_err());
        assert!(update_profile(&conn, user.id, None, Some("not-an-email")).is_err());
    }

    #[test]
    fn update_profile_rejects_duplicate_email() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let _a = test_create_user(&conn);
        let b = create_user(
            &conn,
            &CreateUser {
                username: "other".into(),
                email: "other@example.com".into(),
                password: "securepassword123".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();

        // Taking the first user's email must fail on the unique constraint.
        assert!(update_profile(&conn, b.id, None, Some("blake@example.com")).is_err());
    }

    #[test]
    fn update_password_rehashes_and_authenticates() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        update_password(&conn, user.id, "brand-new-password").unwrap();
        // Old password no longer works; new one does.
        assert!(authenticate(&conn, "blake", "securepassword123").is_err());
        assert!(authenticate(&conn, "blake", "brand-new-password").is_ok());
    }

    #[test]
    fn update_password_enforces_min_length() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);
        assert!(update_password(&conn, user.id, "short").is_err());
    }

    #[test]
    fn password_hash_roundtrip() {
        let hash = hash_password("my-secret-pass").unwrap();
        assert!(hash.starts_with("$argon2"));
        assert!(verify_password("my-secret-pass", &hash).unwrap());
        assert!(!verify_password("wrong-pass", &hash).unwrap());
    }

    #[test]
    fn create_and_get_user() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let user = test_create_user(&conn);
        assert_eq!(user.username, "blake");
        assert_eq!(user.email, "blake@example.com");
        assert_eq!(user.display_name, "Blake");
        assert!(user.is_admin);
        assert!(!user.is_bot);

        // password_hash should be argon2
        assert!(user.password_hash.starts_with("$argon2"));

        // Get by ID
        let fetched = get_user_by_id(&conn, user.id).unwrap();
        assert_eq!(fetched.username, "blake");

        // Get by username (case insensitive)
        let fetched = get_user_by_username(&conn, "Blake").unwrap();
        assert_eq!(fetched.id, user.id);

        // Get by email
        let fetched = get_user_by_email(&conn, "BLAKE@EXAMPLE.COM").unwrap();
        assert_eq!(fetched.id, user.id);
    }

    #[test]
    fn duplicate_username_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        test_create_user(&conn);

        let result = create_user(
            &conn,
            &CreateUser {
                username: "blake".into(),
                email: "other@example.com".into(),
                password: "anotherpassword1".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already exists"));
    }

    #[test]
    fn duplicate_email_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        test_create_user(&conn);

        let result = create_user(
            &conn,
            &CreateUser {
                username: "other".into(),
                email: "blake@example.com".into(),
                password: "anotherpassword1".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        );
        assert!(result.is_err());
    }

    #[test]
    fn short_password_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let result = create_user(
            &conn,
            &CreateUser {
                username: "test".into(),
                email: "test@example.com".into(),
                password: "short".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("8 characters"));
    }

    #[test]
    fn oversized_password_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let long_pw = "a".repeat(1025);
        let result = create_user(
            &conn,
            &CreateUser {
                username: "test".into(),
                email: "test@example.com".into(),
                password: long_pw,
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("1024"));
    }

    #[test]
    fn authenticate_correct_password() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        test_create_user(&conn);

        // By username
        let user = authenticate(&conn, "blake", "securepassword123").unwrap();
        assert_eq!(user.username, "blake");

        // By email
        let user = authenticate(&conn, "blake@example.com", "securepassword123").unwrap();
        assert_eq!(user.username, "blake");
    }

    #[test]
    fn authenticate_wrong_password_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        test_create_user(&conn);

        let result = authenticate(&conn, "blake", "wrongpassword123");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("invalid"));
    }

    #[test]
    fn authenticate_nonexistent_user_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let result = authenticate(&conn, "nobody", "password12345678");
        assert!(result.is_err());
    }

    // ── LIF-412: the halves the login endpoint runs apart ────

    /// An unknown identity still yields a challenge to verify, against the
    /// dummy hash, so a login for an account that does not exist costs the
    /// same Argon2 work as one for an account that does. This is the
    /// enumeration defence, and splitting `authenticate` in two must not
    /// leave it on the wrong side of the seam.
    #[test]
    fn password_challenge_hands_an_unknown_identity_the_dummy_hash() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        test_create_user(&conn);

        let known = password_challenge(&conn, "blake");
        assert_ne!(
            known.hash(),
            DUMMY_HASH,
            "a real user verifies their own hash"
        );
        assert!(verify_password("securepassword123", known.hash()).unwrap());

        let unknown = password_challenge(&conn, "nobody");
        assert_eq!(unknown.hash(), DUMMY_HASH);
        let err = unknown.finish(false).unwrap_err().to_string();
        assert!(
            err.contains("invalid username/email or password"),
            "an unknown identity gets the generic message: {err}"
        );
    }

    /// The split answers exactly what `authenticate` answers, deactivated
    /// accounts (LIF-214) included: same user on success, same messages on
    /// failure.
    #[test]
    fn the_split_matches_authenticate_including_deactivation() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let challenge = password_challenge(&conn, "blake");
        let ok = verify_password("securepassword123", challenge.hash()).unwrap();
        assert_eq!(challenge.finish(ok).unwrap().id, user.id);

        let challenge = password_challenge(&conn, "blake");
        let wrong = verify_password("wrongpassword123", challenge.hash()).unwrap();
        assert_eq!(
            challenge.finish(wrong).unwrap_err().to_string(),
            authenticate(&conn, "blake", "wrongpassword123")
                .unwrap_err()
                .to_string()
        );

        conn.execute(
            "UPDATE users SET is_active = 0 WHERE id = ?1",
            params![user.id],
        )
        .unwrap();
        let challenge = password_challenge(&conn, "blake");
        let ok = verify_password("securepassword123", challenge.hash()).unwrap();
        let err = challenge.finish(ok).unwrap_err().to_string();
        assert!(
            err.contains("deactivated"),
            "a deactivated account is still told so after the verify: {err}"
        );
    }

    /// Hashing outside the writer and inserting inside it must produce the
    /// same account `create_user` does, validation included.
    #[test]
    fn validate_then_insert_with_hash_matches_create_user() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let input = CreateUser {
            username: "  spaced  ".into(),
            email: "MixedCase@Example.com".into(),
            password: "securepassword123".into(),
            display_name: None,
            is_admin: false,
            is_bot: false,
        };
        validate_new_user(&input).expect("valid input");
        let hash = hash_password(&input.password).unwrap();
        let user = insert_user_with_hash(&conn, &input, &hash).unwrap();

        assert_eq!(user.username, "spaced", "username is trimmed");
        assert_eq!(user.email, "mixedcase@example.com", "email is lowercased");
        assert_eq!(user.display_name, "spaced");
        assert_eq!(
            authenticate(&conn, "spaced", "securepassword123")
                .unwrap()
                .id,
            user.id,
            "the externally-hashed password still logs in"
        );

        let short = CreateUser {
            password: "short".into(),
            ..input
        };
        assert!(
            validate_new_user(&short)
                .unwrap_err()
                .to_string()
                .contains("at least 8 characters"),
            "validation is the same as create_user's"
        );
    }

    #[test]
    fn list_users_returns_all() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        test_create_user(&conn);

        create_user(
            &conn,
            &CreateUser {
                username: "ada".into(),
                email: "ada@example.com".into(),
                password: "adaspassword123".into(),
                display_name: Some("Ada".into()),
                is_admin: false,
                is_bot: true,
            },
        )
        .unwrap();

        let users = list_users(&conn).unwrap();
        assert_eq!(users.len(), 2);
    }

    #[test]
    fn display_name_defaults_to_username() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let user = create_user(
            &conn,
            &CreateUser {
                username: "noname".into(),
                email: "noname@example.com".into(),
                password: "password12345678".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();

        assert_eq!(user.display_name, "noname");
    }

    // ── Session tests ────────────────────────────────────────

    #[test]
    fn session_create_and_validate() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let session = create_session(&conn, user.id, None).unwrap();
        assert!(session.token.starts_with("lific_sess_"));
        assert_eq!(session.user_id, user.id);

        // Validate returns the user
        let validated_user = validate_session(&conn, &session.token).unwrap();
        assert_eq!(validated_user.id, user.id);
        assert_eq!(validated_user.username, "blake");
    }

    #[test]
    fn session_invalid_token_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        let result = validate_session(&conn, "lific_sess_nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn session_expired_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        // Create a session that already expired (negative duration trick)
        let token = generate_session_token();
        conn.execute(
            "INSERT INTO sessions (token, user_id, expires_at)
             VALUES (?1, ?2, datetime('now', '-1 hour'))",
            params![token, user.id],
        )
        .unwrap();

        let result = validate_session(&conn, &token);
        assert!(result.is_err());
    }

    // ── LIF-139: validation is read-only, cleanup rides the writers ──

    /// Insert an already-expired session row directly and return its token.
    fn insert_expired_session(conn: &Connection, user_id: i64) -> String {
        let token = generate_session_token();
        conn.execute(
            "INSERT INTO sessions (token, user_id, expires_at)
             VALUES (?1, ?2, datetime('now', '-1 hour'))",
            params![hash_session_token(&token), user_id],
        )
        .unwrap();
        token
    }

    fn session_row_count(conn: &Connection) -> i64 {
        conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
            .unwrap()
    }

    // The expiry check lives in the SELECT, not in a cleanup DELETE. An
    // expired token must be refused even while its row is still on disk.
    #[test]
    fn expired_session_rejected_without_being_swept_first() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);
        let token = insert_expired_session(&conn, user.id);

        assert!(
            validate_session(&conn, &token).is_err(),
            "an expired session must be rejected on the predicate alone"
        );
        assert_eq!(
            session_row_count(&conn),
            1,
            "validation must not write — the expired row is still there"
        );
        // Still rejected on a second look, i.e. the first call didn't rely on
        // having deleted the row.
        assert!(validate_session(&conn, &token).is_err());
    }

    // Login already holds the writer, so it is where expired rows get reaped.
    #[test]
    fn creating_a_session_purges_expired_rows() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);
        insert_expired_session(&conn, user.id);
        assert_eq!(session_row_count(&conn), 1);

        let fresh = create_session(&conn, user.id, None).unwrap();

        assert_eq!(
            session_row_count(&conn),
            1,
            "login sweeps the expired row, leaving only the new session"
        );
        assert!(
            validate_session(&conn, &fresh.token).is_ok(),
            "the freshly minted session survives the sweep"
        );
    }

    // Logout is the other writer-holding touchpoint.
    #[test]
    fn deleting_a_session_purges_expired_rows() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);
        let live = create_session(&conn, user.id, None).unwrap();
        insert_expired_session(&conn, user.id);
        assert_eq!(session_row_count(&conn), 2);

        delete_session(&conn, &live.token).unwrap();

        assert_eq!(
            session_row_count(&conn),
            0,
            "logout removes its own session and sweeps expired ones"
        );
    }

    // The middleware now validates on a pooled read connection, which is
    // read-only at the SQLite level: a stray write would surface as an error
    // rather than a silent no-op.
    #[test]
    fn session_validates_over_a_read_connection() {
        let pool = test_db();
        let (user_id, token) = {
            let conn = pool.write().unwrap();
            let user = test_create_user(&conn);
            let session = create_session(&conn, user.id, None).unwrap();
            (user.id, session.token)
        };

        let conn = pool.read().unwrap();
        let validated = validate_session(&conn, &token).expect("read-only validation works");
        assert_eq!(validated.id, user_id);
        assert!(validate_session(&conn, "lific_sess_nope").is_err());
    }

    #[test]
    fn session_delete_logout() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let session = create_session(&conn, user.id, None).unwrap();
        assert!(validate_session(&conn, &session.token).is_ok());

        delete_session(&conn, &session.token).unwrap();
        assert!(validate_session(&conn, &session.token).is_err());
    }

    #[test]
    fn session_delete_all_for_user() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let s1 = create_session(&conn, user.id, None).unwrap();
        let s2 = create_session(&conn, user.id, None).unwrap();

        delete_all_sessions(&conn, user.id).unwrap();
        assert!(validate_session(&conn, &s1.token).is_err());
        assert!(validate_session(&conn, &s2.token).is_err());
    }

    #[test]
    fn recent_session_window_rejects_old_sessions() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);
        let session = create_session(&conn, user.id, None).unwrap();

        assert!(session_is_recent(&conn, &session.token).unwrap());
        conn.execute(
            "UPDATE sessions SET created_at = datetime('now', '-16 minutes')",
            [],
        )
        .unwrap();
        assert!(!session_is_recent(&conn, &session.token).unwrap());
    }

    /// Seed one account plus a bot it owns, an unrelated account, and one of
    /// every credential shape a lockdown has an opinion about. Returns
    /// `(user, bot, stranger)`.
    fn seed_lockdown_fixture(conn: &Connection) -> (User, User, User) {
        let user = test_create_user(conn);
        let bot = create_bot_user(conn, user.id, "bot", "Bot", Some("bot")).unwrap();
        let stranger = create_user(
            conn,
            &CreateUser {
                username: "stranger".into(),
                email: "stranger@test.com".into(),
                password: "strangerpassword".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();

        conn.execute(
            "INSERT INTO api_keys (name, key_hash, user_id) VALUES
             ('human-recovery-key', 'hash-human', ?1),
             ('bot-recovery-key', 'hash-bot', ?2),
             ('stranger-key', 'hash-stranger', ?3),
             ('operator-recovery-key', 'hash-operator', NULL)",
            params![user.id, bot.id, stranger.id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_clients (client_id, client_name, redirect_uris)
             VALUES ('recovery-client', 'Recovery', '[\"http://localhost\"]')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_tokens (access_token, client_id, expires_at, user_id) VALUES
             ('oauth-hash-human', 'recovery-client', '2099-01-01T00:00:00Z', ?1),
             ('oauth-hash-bot', 'recovery-client', '2099-01-01T00:00:00Z', ?2),
             ('oauth-hash-stranger', 'recovery-client', '2099-01-01T00:00:00Z', ?3)",
            params![user.id, bot.id, stranger.id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_codes
                (code, client_id, redirect_uri, code_challenge, expires_at, user_id) VALUES
             ('code-bot', 'recovery-client', 'http://localhost', 'c', '2099-01-01T00:00:00Z', ?1),
             ('code-stranger', 'recovery-client', 'http://localhost', 'c', '2099-01-01T00:00:00Z', ?2)",
            params![bot.id, stranger.id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_device_codes
                (device_code_hash, user_code, expires_at, status, user_id) VALUES
             ('dev-bot', 'BCDF-GHJK', '2099-01-01T00:00:00Z', 'approved', ?1),
             ('dev-stranger', 'BCDF-GHJL', '2099-01-01T00:00:00Z', 'approved', ?2),
             ('dev-pending', 'BCDF-GHJM', '2099-01-01T00:00:00Z', 'pending', NULL)",
            params![bot.id, stranger.id],
        )
        .unwrap();

        (user, bot, stranger)
    }

    /// Signup's two atomicity claims, on a real file with two independently
    /// opened pools, which is the separation two processes have.
    ///
    /// The first-admin decision is `SELECT COUNT(*) = 0 FROM users` followed by
    /// an insert. Those are two statements, so on a bare writer guard they were
    /// two implicit transactions and two racing signups could both read zero.
    /// Inside one `BEGIN IMMEDIATE` they cannot: SQLite admits one writer, so
    /// the second signup reads the first one's committed row.
    #[test]
    fn concurrent_signups_produce_exactly_one_first_admin() {
        let dir = tempfile::tempdir().expect("scratch dir");
        let path = dir.path().join("lific.db");
        let first = crate::db::open(&path).expect("first pool");
        let second = crate::db::open(&path).expect("second pool");

        // The shape `auth_signup` runs: policy read, first-admin decision,
        // insert and session, all in one immediate transaction.
        let signup = |pool: &crate::db::DbPool, username: &str| -> Result<User, LificError> {
            let hash = hash_password("testpassword1").unwrap();
            pool.transaction(|tx| {
                let settings = crate::db::queries::settings::get(tx)?;
                let mut input = CreateUser {
                    username: username.into(),
                    email: format!("{username}@test.local"),
                    password: "testpassword1".into(),
                    display_name: None,
                    is_admin: false,
                    is_bot: false,
                };
                input.is_admin =
                    tx.query_row("SELECT COUNT(*) = 0 FROM users", [], |r| r.get(0))?;
                let user = insert_user_with_hash(tx, &input, &hash)?;
                create_session(tx, user.id, Some(settings.session_lifetime_days * 24))?;
                Ok(user)
            })
        };

        let (a, b) = std::thread::scope(|scope| {
            let one = scope.spawn(|| signup(&first, "alice"));
            let two = scope.spawn(|| signup(&second, "bob"));
            (one.join().unwrap(), two.join().unwrap())
        });

        let a = a.expect("alice signs up");
        let b = b.expect("bob signs up");
        assert!(
            a.is_admin ^ b.is_admin,
            "exactly one of two racing signups may become the first admin"
        );

        let conn = first.read().unwrap();
        let admins: i64 = conn
            .query_row("SELECT COUNT(*) FROM users WHERE is_admin = 1", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(admins, 1);
        // And neither account exists without the session that signed it in.
        for user in [&a, &b] {
            let sessions: i64 = conn
                .query_row(
                    "SELECT COUNT(*) FROM sessions WHERE user_id = ?1",
                    params![user.id],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(sessions, 1, "no user is left without a session");
        }
    }

    /// The other half: a failure anywhere in the signup transaction leaves no
    /// account behind. On the old bare-writer path the insert had already
    /// committed by the time the session failed.
    #[test]
    fn a_signup_that_fails_after_the_insert_leaves_no_account() {
        let pool = test_db();
        let hash = hash_password("testpassword1").unwrap();
        let outcome: Result<(), LificError> = pool.transaction(|tx| {
            let input = CreateUser {
                username: "half-created".into(),
                email: "half@test.local".into(),
                password: "testpassword1".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            };
            insert_user_with_hash(tx, &input, &hash)?;
            Err(LificError::Internal("session mint failed".into()))
        });
        assert!(outcome.is_err());

        let conn = pool.read().unwrap();
        assert!(
            get_user_by_username(&conn, "half-created").is_err(),
            "a failed signup must not leave an account nobody can sign in to"
        );
    }

    /// Login's finalization: the hash verified off the writer must still be
    /// the stored one when the session is minted.
    #[test]
    fn a_login_finalizes_only_against_the_hash_it_verified() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);
        let verified = user.password_hash.clone();

        // Ordinary case: nothing changed in between.
        assert_eq!(
            finalize_login(&conn, user.id, &verified).unwrap().id,
            user.id
        );

        // A password change committed during the Argon2 verify. The password
        // just proven correct is now the old one.
        update_password(&conn, user.id, "a whole new password").unwrap();
        let err = finalize_login(&conn, user.id, &verified).expect_err("stale hash");
        assert!(
            matches!(&err, LificError::BadRequest(m) if m == INVALID_LOGIN_MESSAGE),
            "a superseded password must report as simply wrong: {err:?}"
        );

        // The liveness arm: a deactivated account cannot finalize either,
        // even with the right hash. (An admin exists alongside so the
        // last-admin guard permits switching this one off.)
        create_user(
            &conn,
            &CreateUser {
                username: "keeper".into(),
                email: "keeper@test.com".into(),
                password: "testpassword1".into(),
                display_name: None,
                is_admin: true,
                is_bot: false,
            },
        )
        .unwrap();
        let fresh = get_user_by_id(&conn, user.id).unwrap().password_hash;
        set_active(&conn, user.id, false).unwrap();
        assert!(finalize_login(&conn, user.id, &fresh).is_err());
    }

    #[test]
    fn lockdown_severs_every_credential_for_the_user_and_their_bots() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (user, bot, _stranger) = seed_lockdown_fixture(&conn);
        let human_session = create_session(&conn, user.id, None).unwrap();
        let bot_session = create_session(&conn, bot.id, None).unwrap();

        lock_down_account(&conn, user.id).unwrap();

        assert!(validate_session(&conn, &human_session.token).is_err());
        assert!(validate_session(&conn, &bot_session.token).is_err());

        let live = |sql: &str| -> i64 { conn.query_row(sql, [], |r| r.get(0)).unwrap() };
        assert_eq!(
            live("SELECT COUNT(*) FROM api_keys WHERE revoked = 0 AND name = 'human-recovery-key'"),
            0
        );
        assert_eq!(
            live("SELECT COUNT(*) FROM api_keys WHERE revoked = 0 AND name = 'bot-recovery-key'"),
            0
        );
        assert_eq!(
            live(
                "SELECT COUNT(*) FROM oauth_tokens WHERE revoked = 0 AND access_token IN ('oauth-hash-human', 'oauth-hash-bot')"
            ),
            0
        );
        assert_eq!(
            live("SELECT used FROM oauth_codes WHERE code = 'code-bot'"),
            1,
            "an unexchanged code bound to an owned bot is burned"
        );
        assert_eq!(
            live(
                "SELECT COUNT(*) FROM oauth_device_codes WHERE device_code_hash = 'dev-bot' AND status = 'denied'"
            ),
            1,
            "an approved device grant bound to an owned bot is denied"
        );

        // The bot identity itself survives, so the UI can show the tool as
        // disconnected and offer a reconnect rather than losing it.
        assert!(get_user_by_id(&conn, bot.id).is_ok());
    }

    #[test]
    fn lockdown_spares_other_accounts_and_the_unbound_operator_key() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (user, _bot, stranger) = seed_lockdown_fixture(&conn);
        let stranger_session = create_session(&conn, stranger.id, None).unwrap();

        lock_down_account(&conn, user.id).unwrap();

        assert!(validate_session(&conn, &stranger_session.token).is_ok());
        let live = |sql: &str| -> i64 { conn.query_row(sql, [], |r| r.get(0)).unwrap() };
        assert_eq!(
            live("SELECT revoked FROM api_keys WHERE name = 'operator-recovery-key'"),
            0,
            "an unbound operator key names nobody and is out of scope"
        );
        assert_eq!(
            live("SELECT revoked FROM api_keys WHERE name = 'stranger-key'"),
            0
        );
        assert_eq!(
            live("SELECT revoked FROM oauth_tokens WHERE access_token = 'oauth-hash-stranger'"),
            0
        );
        assert_eq!(
            live("SELECT used FROM oauth_codes WHERE code = 'code-stranger'"),
            0
        );
        assert_eq!(
            live(
                "SELECT COUNT(*) FROM oauth_device_codes WHERE device_code_hash = 'dev-stranger' AND status = 'approved'"
            ),
            1
        );
        assert_eq!(
            live(
                "SELECT COUNT(*) FROM oauth_device_codes WHERE device_code_hash = 'dev-pending' AND status = 'pending'"
            ),
            1,
            "an unbound pending grant names nobody to scope it to"
        );
    }

    #[test]
    fn lockdown_audits_each_revoked_credential_without_token_material() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (user, _bot, _stranger) = seed_lockdown_fixture(&conn);

        lock_down_account(&conn, user.id).unwrap();

        let mut stmt = conn
            .prepare(
                "SELECT entity_type, entity_label FROM audit_log
                 WHERE action = 'revoke' ORDER BY entity_type, entity_label",
            )
            .unwrap();
        let rows: Vec<(String, String)> = stmt
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
            .unwrap()
            .map(Result::unwrap)
            .collect();
        assert_eq!(
            rows,
            vec![
                ("api_key".to_string(), "bot-recovery-key".to_string()),
                ("api_key".to_string(), "human-recovery-key".to_string()),
                ("oauth_token".to_string(), "recovery-client".to_string()),
                ("oauth_token".to_string(), "recovery-client".to_string()),
            ]
        );
        // Labels are names and client ids. No hash or token value is copied
        // into the log.
        let leaked: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM audit_log
                 WHERE entity_label LIKE 'hash-%' OR entity_label LIKE 'oauth-hash-%'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(leaked, 0);
    }

    #[test]
    fn lockdown_rolls_back_whole_when_the_caller_transaction_fails() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (user, _bot, _stranger) = seed_lockdown_fixture(&conn);
        let session = create_session(&conn, user.id, None).unwrap();

        // A caller that wraps the primitive and then fails must leave nothing
        // half-severed: the lockdown opens no independent write of its own.
        let outcome: Result<(), LificError> =
            crate::db::queries::savepoint(&conn, "caller_transaction", || {
                lock_down_account(&conn, user.id)?;
                Err(LificError::BadRequest("caller changed its mind".into()))
            });
        assert!(outcome.is_err());

        assert!(validate_session(&conn, &session.token).is_ok());
        let live_keys: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM api_keys WHERE revoked = 0 AND user_id IS NOT NULL",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(live_keys, 3);
    }

    // ── API key ownership tests ──────────────────────────────

    #[test]
    fn assign_key_to_user_works() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        // Create an API key manually
        conn.execute(
            "INSERT INTO api_keys (name, key_hash) VALUES ('opencode', 'fakehash')",
            [],
        )
        .unwrap();

        let key_id: i64 = conn
            .query_row(
                "SELECT id FROM api_keys WHERE name = 'opencode'",
                [],
                |row| row.get(0),
            )
            .unwrap();

        let owner = |conn: &Connection| -> Option<i64> {
            conn.query_row(
                "SELECT user_id FROM api_keys WHERE id = ?1",
                params![key_id],
                |row| row.get(0),
            )
            .unwrap()
        };

        // Before assignment: no user
        assert!(owner(&conn).is_none());

        // Assign
        assign_key_to_user(&conn, "opencode", user.id).unwrap();

        // After assignment: the key points at the user
        assert_eq!(owner(&conn), Some(user.id));
    }

    #[test]
    fn assign_nonexistent_key_fails() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let user = test_create_user(&conn);

        let result = assign_key_to_user(&conn, "nope", user.id);
        assert!(result.is_err());
    }

    // ── create_passwordless_admin (LIFIC-9) ─────────────────

    #[test]
    fn operator_admin_is_not_a_connected_tool() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let admin = create_passwordless_admin(&conn, "Operator Blake").unwrap();

        assert!(admin.is_admin, "first admin is an admin");
        assert!(
            !admin.is_bot,
            "first admin is a person, not a connected tool"
        );
        assert_eq!(admin.display_name, "Operator Blake");
    }

    #[test]
    fn operator_admin_resolves_as_first_admin() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let admin = create_passwordless_admin(&conn, "Operator Blake").unwrap();

        let resolved = first_admin(&conn)
            .unwrap()
            .expect("resolves as first admin");
        assert_eq!(resolved.id, admin.id);
        assert_eq!(resolved.username, admin.username);
    }

    #[test]
    fn operator_username_comes_from_their_name() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let admin = create_passwordless_admin(&conn, "Blake Smith").unwrap();
        assert_eq!(admin.username, "blake-smith");
    }

    #[test]
    fn same_named_operators_get_distinct_usernames() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let first = create_passwordless_admin(&conn, "Blake").unwrap();
        let second = create_passwordless_admin(&conn, "blake!").unwrap();

        assert_ne!(
            first.username, second.username,
            "usernames must not collide"
        );
        assert!(!first.username.is_empty());
        assert!(!second.username.is_empty());
    }

    #[test]
    fn passwordless_admin_cannot_be_logged_into_by_password() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        create_passwordless_admin(&conn, "Blake").unwrap();
        // The random stored hash has no known plaintext, so password login
        // must always fail — there is no password, only passwordless identity.
        let result = authenticate(&conn, "blake", "anypassword123");
        assert!(
            result.is_err(),
            "passwordless admin must never authenticate by password"
        );
    }

    // ── create_first_admin_with_password (LIFIC-25) ──────────

    #[test]
    fn password_admin_is_admin_and_authenticates() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let admin = create_first_admin_with_password(&conn, "Blake Smith", "hunter22").unwrap();

        assert!(admin.is_admin, "first admin is an admin");
        assert_eq!(admin.username, "blake-smith");
        assert!(!admin.is_bot);
        let got = authenticate(&conn, "blake-smith", "hunter22").unwrap();
        assert_eq!(got.id, admin.id, "correct password logs in as the admin");
    }

    #[test]
    fn password_admin_rejects_wrong_password() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        create_first_admin_with_password(&conn, "Blake", "correcthorse1").unwrap();
        assert!(
            authenticate(&conn, "blake", "wrongpassword").is_err(),
            "wrong password must be rejected"
        );
    }

    #[test]
    fn password_admin_rejects_empty_password() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let err = create_first_admin_with_password(&conn, "Blake", "").unwrap_err();
        assert!(
            matches!(err, LificError::BadRequest(_)),
            "an empty password must be rejected, got {err:?}"
        );
    }

    // ── Deactivation: credential teardown and owned bots ─────
    //
    // LIF-214 gave `set_active` a teardown. These pin the two things review
    // found missing from it: the write has to be all-or-nothing, and the
    // account's owned bots have to stop working too.

    /// An admin (so the last-admin guard is never the thing under test), a
    /// human owner, and one bot the owner owns.
    fn deactivation_fixture(conn: &Connection) -> (User, User) {
        let mk = |username: &str, is_admin: bool| {
            create_user(
                conn,
                &CreateUser {
                    username: username.into(),
                    email: format!("{username}@example.com"),
                    password: "securepassword123".into(),
                    display_name: None,
                    is_admin,
                    is_bot: false,
                },
            )
            .unwrap()
        };
        mk("keeper-admin", true);
        let owner = mk("owner", false);
        let bot = ensure_bot(conn, owner.id, "opencode", "OpenCode").unwrap();
        (owner, bot)
    }

    fn seed_key(conn: &Connection, name: &str, user_id: i64) {
        conn.execute(
            "INSERT INTO api_keys (name, key_hash, user_id) VALUES (?1, ?2, ?3)",
            params![name, format!("hash-{name}"), user_id],
        )
        .unwrap();
    }

    fn seed_oauth_token(conn: &Connection, suffix: &str, user_id: i64) {
        conn.execute(
            "INSERT INTO oauth_clients (client_id, client_name, redirect_uris)
             VALUES (?1, 'Test', '[\"http://localhost\"]')",
            params![format!("client-{suffix}")],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id)
             VALUES (?1, ?2, '2999-01-01T00:00:00Z', 'mcp', ?3)",
            params![
                format!("hash-{suffix}"),
                format!("client-{suffix}"),
                user_id
            ],
        )
        .unwrap();
    }

    fn count(conn: &Connection, sql: &str, id: i64) -> i64 {
        conn.query_row(sql, params![id], |row| row.get(0)).unwrap()
    }

    fn live_sessions(conn: &Connection, user_id: i64) -> i64 {
        count(
            conn,
            "SELECT COUNT(*) FROM sessions WHERE user_id = ?1",
            user_id,
        )
    }

    fn live_keys(conn: &Connection, user_id: i64) -> i64 {
        count(
            conn,
            "SELECT COUNT(*) FROM api_keys WHERE user_id = ?1 AND revoked = 0",
            user_id,
        )
    }

    fn live_tokens(conn: &Connection, user_id: i64) -> i64 {
        count(
            conn,
            "SELECT COUNT(*) FROM oauth_tokens WHERE user_id = ?1 AND revoked = 0",
            user_id,
        )
    }

    /// The exact end state of a successful deactivation, in one assertion
    /// block: the target loses everything, the bot loses only its sessions.
    #[test]
    fn deactivation_tears_down_the_full_credential_set_in_one_write() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (owner, bot) = deactivation_fixture(&conn);

        create_session(&conn, owner.id, None).unwrap();
        create_session(&conn, bot.id, None).unwrap();
        seed_key(&conn, "owner-key", owner.id);
        seed_key(&conn, "bot-key", bot.id);
        seed_oauth_token(&conn, "owner", owner.id);
        seed_oauth_token(&conn, "bot", bot.id);

        let refreshed = set_active(&conn, owner.id, false).unwrap();
        assert!(!refreshed.is_active);

        assert_eq!(live_sessions(&conn, owner.id), 0, "own sessions deleted");
        assert_eq!(live_keys(&conn, owner.id), 0, "own API keys revoked");
        assert_eq!(live_tokens(&conn, owner.id), 0, "own OAuth tokens revoked");

        assert_eq!(
            live_sessions(&conn, bot.id),
            0,
            "the bot's sessions go too, so live realtime connections drop"
        );
        assert_eq!(
            live_keys(&conn, bot.id),
            1,
            "the bot's API key is left intact; the read path refuses it"
        );
        assert_eq!(
            live_tokens(&conn, bot.id),
            1,
            "same for its OAuth token, so reactivation needs no re-minting"
        );
    }

    /// A refused deactivation writes nothing at all. The guard runs inside the
    /// same transaction as the teardown, so a rejection cannot leave a
    /// half-revoked account behind.
    #[test]
    fn a_refused_deactivation_leaves_every_credential_alone() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let admin = create_user(
            &conn,
            &CreateUser {
                username: "solo-admin".into(),
                email: "solo-admin@example.com".into(),
                password: "securepassword123".into(),
                display_name: None,
                is_admin: true,
                is_bot: false,
            },
        )
        .unwrap();
        create_session(&conn, admin.id, None).unwrap();
        seed_key(&conn, "admin-key", admin.id);
        seed_oauth_token(&conn, "admin", admin.id);

        let err = set_active(&conn, admin.id, false).unwrap_err();
        assert!(
            matches!(err, LificError::Conflict(_)),
            "the last admin cannot be deactivated, got {err:?}"
        );

        assert!(get_user_by_id(&conn, admin.id).unwrap().is_active);
        assert_eq!(live_sessions(&conn, admin.id), 1);
        assert_eq!(live_keys(&conn, admin.id), 1);
        assert_eq!(live_tokens(&conn, admin.id), 1);
    }

    #[test]
    fn a_bots_session_dies_with_its_owner_and_returns_on_reactivation() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (owner, bot) = deactivation_fixture(&conn);

        // A session minted *after* deactivation still must not authenticate:
        // the check is on the read path, not on the teardown.
        set_active(&conn, owner.id, false).unwrap();
        let token = create_session(&conn, bot.id, None).unwrap().token;
        assert!(
            validate_session(&conn, &token).is_err(),
            "a bot session cannot authenticate while its owner is deactivated"
        );

        set_active(&conn, owner.id, true).unwrap();
        assert_eq!(
            validate_session(&conn, &token).unwrap().id,
            bot.id,
            "reactivating the owner brings the bot straight back"
        );
    }

    #[test]
    fn credential_is_live_tracks_the_owner_and_ignores_ownerless_bots() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let (owner, bot) = deactivation_fixture(&conn);

        assert!(credential_is_live(&conn, &owner).unwrap());
        assert!(credential_is_live(&conn, &bot).unwrap());

        set_active(&conn, owner.id, false).unwrap();
        let owner = get_user_by_id(&conn, owner.id).unwrap();
        assert!(!credential_is_live(&conn, &owner).unwrap());
        assert!(
            !credential_is_live(&conn, &bot).unwrap(),
            "the bot inherits its owner's loss of access"
        );

        // An ownerless bot has nothing to inherit and is evaluated as itself,
        // matching `authz::effective_user`'s dangling-owner fallback.
        let orphan = create_user(
            &conn,
            &CreateUser {
                username: "orphan".into(),
                email: "orphan@bot.local".into(),
                password: "securepassword123".into(),
                display_name: None,
                is_admin: false,
                is_bot: true,
            },
        )
        .unwrap();
        assert!(credential_is_live(&conn, &orphan).unwrap());
    }
}