mahbot 0.4.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
use super::*;
use crate::Role;
use crate::Tool;
use crate::Workspace;
use crate::role::DIAGNOSTICS_ROLE;
use crate::util::test::TicketBuilder;
use crate::util::test::assert_superseded_ticket;
use crate::util::test::expect_ticket;
use crate::util::test::init_test_stores;
use crate::util::test::make_ticket;
use crate::workspace::test_ws;
use crate::workspace::test_ws_named;
use strum::IntoEnumIterator;
use tempfile::TempDir;

/// Scenarios for testing invalid prerequisite/supersede inputs.
#[derive(Debug, Clone, Copy)]
enum InvalidInputScenario {
    /// Prerequisite/supersede references a nonexistent ticket.
    NonExistent,
    /// Prerequisite/supersede references a ticket in a different workspace.
    CrossWorkspace,
    /// Prerequisite/supersede references the ticket itself (self-reference).
    SelfReference,
}

/// Operation under test in the invalid-input matrix.
#[derive(Debug, Clone, Copy)]
enum InvalidInputOp {
    Create,
    Supersede,
}

/// Open a test store and create a default ticket.
/// Returns (store, temp_dir, ticket_id).
async fn setup() -> (BoardStore, TempDir, String) {
    let (store, tmp) = open_test_store().await;
    let id = make_ticket(
        &store,
        &test_ws_named("/ws", "ws"),
        "Test",
        TicketPhase::Backlog,
    )
    .await;
    (store, tmp, id)
}

#[tokio::test]
async fn test_get_ticket_phase() {
    let (store, _tmp) = open_test_store().await;

    // Non-existent ticket returns None.
    assert!(
        store
            .get_ticket_phase("nonexistent")
            .await
            .expect("query")
            .is_none()
    );

    let id = make_ticket(
        &store,
        &crate::workspace::test_ws_named("/workspace", "workspace"),
        "Status Test",
        TicketPhase::Planning,
    )
    .await;

    let phase = crate::util::test::expect_ticket_phase(&store, &id).await;
    assert_eq!(phase, TicketPhase::Planning);

    // After transition, reflects new phase.
    store
        .transition_to(&id, None, TicketPhase::ReadyForDevelopment, None)
        .await
        .expect("set");
    let phase = crate::util::test::expect_ticket_phase(&store, &id).await;
    assert_eq!(phase, TicketPhase::ReadyForDevelopment);
}

#[tokio::test]
async fn test_get_tickets_by_ids() {
    let (store, _tmp) = open_test_store().await;
    let ws = crate::workspace::test_ws_named("/ws", "test_ws");

    // sql_in_placeholders(0) produces invalid `WHERE id IN ()` —
    // the guard must short-circuit empty input before reaching SQL.
    let tickets = store
        .get_tickets_by_ids(&[], crate::board::LoadComments::No)
        .await
        .expect("empty ids");
    assert!(tickets.is_empty(), "empty ids should return empty vec");

    let id_a = make_ticket(&store, &ws, "Ticket A", TicketPhase::Done).await;
    let id_c = make_ticket(&store, &ws, "Ticket C", TicketPhase::Backlog).await;

    let ids = vec![id_a.clone(), id_c.clone()];
    let tickets = store
        .get_tickets_by_ids(&ids, crate::board::LoadComments::No)
        .await
        .expect("get by ids");
    assert_eq!(tickets.len(), 2, "should return exactly 2 tickets");

    for t in &tickets {
        match t.id.as_str() {
            id if id == id_a => assert_eq!(t.title, "Ticket A"),
            id if id == id_c => assert_eq!(t.title, "Ticket C"),
            other => panic!("unexpected ticket id: {other}"),
        }
    }
}

#[test]
fn test_ticket_phase_parse_and_roundtrip() {
    // Roundtrip: as_ref() -> parse() for every variant
    for v in TicketPhase::iter() {
        let parsed: TicketPhase = v.as_ref().parse().unwrap();
        assert_eq!(&parsed, &v, "roundtrip failed for {v}");
    }

    // Error case — verify error message includes helpful details.
    let err = "unknown_phase".parse::<TicketPhase>().unwrap_err();
    let msg = format!("{err}");

    assert!(
        msg.contains("Invalid phase"),
        "error should mention 'Invalid phase', got: {msg}"
    );
    assert!(
        msg.contains("unknown_phase"),
        "error should contain the invalid input value, got: {msg}"
    );
    assert!(
        TicketPhase::iter().any(|p| msg.contains(p.as_ref())),
        "error should list at least one valid phase, got: {msg}"
    );
}

#[test]
fn test_display_name_no_underscores() {
    // Every variant's display_name() must be underscore-free
    // and non-empty.
    for variant in TicketPhase::iter() {
        let name = variant.display_name();
        assert!(!name.is_empty(), "empty display_name for {variant}");
        assert!(
            !name.contains('_'),
            "display_name for {variant} still has underscore: {name}"
        );
    }
}

#[tokio::test]
async fn test_unconditional_transition_clears_assignment() {
    let (store, _tmp, id) = setup().await;

    // Claim the ticket (sets assigned_to to NULL by default)
    let claimed = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::InDevelopment,
            "ws",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim")
        .expect("ticket exists");

    // Set assigned_to explicitly (matching production dispatch_engineer behavior)
    store
        .set_assigned_to_no_cancel(&claimed.id, Some(Role::Engineer.as_str()))
        .await
        .expect("set_assigned_to");
    let ticket = store
        .get_ticket(&id)
        .await
        .expect("get")
        .expect("should exist");
    assert!(
        ticket.assigned_to.is_some(),
        "assigned_to should be set after set_assigned_to"
    );

    // Update phase — this should clear assigned_to
    store
        .transition_to(&id, None, TicketPhase::DiagnosticsDone, None)
        .await
        .expect("update");

    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert_eq!(ticket.phase, TicketPhase::DiagnosticsDone);
    assert!(
        ticket.assigned_to.is_none(),
        "assigned_to should be cleared after unconditional transition"
    );
}

#[tokio::test]
async fn test_guarded_transition() {
    let (store, _tmp, id) = setup().await;

    // Wrong expected phase — should fail, ticket unchanged.
    let result = store
        .transition_to(
            &id,
            Some(TicketPhase::Done),
            TicketPhase::InDevelopment,
            None,
        )
        .await;
    assert!(
        result.is_err(),
        "guarded transition with wrong phase should fail"
    );
    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert_eq!(ticket.phase, TicketPhase::Backlog);

    // Correct expected phase — should succeed.
    store
        .transition_to(
            &id,
            Some(TicketPhase::Backlog),
            TicketPhase::InDevelopment,
            None,
        )
        .await
        .expect("guarded transition with correct phase should succeed");
    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert_eq!(ticket.phase, TicketPhase::InDevelopment);
}

#[tokio::test]
async fn test_add_comment() {
    let (store, _tmp, id) = setup().await;

    store
        .add_comment(&id, Role::Engineer.as_str(), "done!")
        .await
        .expect("add comment");

    let comments = store.get_comments(&id).await.expect("get comments");
    assert_eq!(comments.len(), 1);
    assert_eq!(comments[0].role, Role::Engineer.as_str());
    assert_eq!(comments[0].content, "done!");
    assert!(!comments[0].created_at.is_empty());

    // Verify updated_at was bumped
    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert!(ticket.updated_at > ticket.created_at);
}

#[tokio::test]
async fn test_list_tickets() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    make_ticket(&store, &ws, "A", TicketPhase::Backlog).await;
    make_ticket(&store, &ws, "B", TicketPhase::Backlog).await;
    make_ticket(&store, &ws, "C", TicketPhase::Backlog).await;

    // All tickets for the workspace
    let tickets = store
        .list_all_tickets(Some("ws"), None)
        .await
        .expect("list");
    assert_eq!(tickets.len(), 3);

    // Filter by phase (none match since all are Backlog)
    let tickets = store
        .list_all_tickets(Some("ws"), Some(TicketPhase::Done))
        .await
        .expect("list");
    assert_eq!(tickets.len(), 0);
}

/// Verify that `reset_inflight_tickets` correctly transitions each in-flight
/// ticket phase back to its ready state, and that non-inflight phases (e.g.
/// Backlog) are left untouched.
///
/// Canonical reset test. The serial(reset_inflight) group is the contract for
/// the shared global board: ANY test creating a ticket in a reset-affected
/// phase (Analysis/InDevelopment/InDiagnostics/InSanitation/InReview/InQa) on
/// the shared board must join this group, or a concurrent reset will clobber
/// its fixture (phase-CAS failure indistinguishable from a real regression).
/// This test itself uses an isolated store, so its membership is defensive —
/// the attribute is load-bearing for the group, not for this test's own data.
#[tokio::test]
#[serial_test::serial(reset_inflight)]
async fn test_reset_inflight_tickets() {
    /// A single reset transition case.
    struct Case {
        name: &'static str,
        /// Unique suffix for workspace names (isolates cases).
        suffix: &'static str,
        /// The phase the ticket starts in.
        start: TicketPhase,
        /// The expected phase after reset.
        expected: TicketPhase,
        /// Expected pipeline_reservation after reset.
        reservation: bool,
    }

    let cases = [
        Case {
            name: "Backlog unaffected (not an inflight phase)",
            suffix: "a",
            start: TicketPhase::Backlog,
            expected: TicketPhase::Backlog,
            reservation: false,
        },
        Case {
            name: "Analysis → Backlog (no reservation)",
            suffix: "b",
            start: TicketPhase::Analysis,
            expected: TicketPhase::Backlog,
            reservation: false,
        },
        Case {
            name: "InDevelopment → ReadyForDevelopment (reservation=1)",
            suffix: "c",
            start: TicketPhase::InDevelopment,
            expected: TicketPhase::ReadyForDevelopment,
            reservation: true,
        },
        Case {
            name: "InDiagnostics → ReadyForDevelopment (reservation=1)",
            suffix: "d",
            start: TicketPhase::InDiagnostics,
            expected: TicketPhase::ReadyForDevelopment,
            reservation: true,
        },
        Case {
            name: "InSanitation → QaPassed (reservation=1)",
            suffix: "e",
            start: TicketPhase::InSanitation,
            expected: TicketPhase::QaPassed,
            reservation: true,
        },
        Case {
            name: "InQa → Reviewed (no reservation)",
            suffix: "f",
            start: TicketPhase::InQa,
            expected: TicketPhase::Reviewed,
            reservation: false,
        },
        Case {
            name: "InReview → DiagnosticsDone (no reservation)",
            suffix: "g",
            start: TicketPhase::InReview,
            expected: TicketPhase::DiagnosticsDone,
            reservation: false,
        },
    ];

    let (store, _tmp) = open_test_store().await;

    for case in &cases {
        let ws = test_ws_named(&format!("/{}", case.suffix), case.suffix);

        let id = make_ticket(&store, &ws, case.name, case.start).await;

        store.reset_inflight_tickets(&[]).await.expect("reset");

        let t = expect_ticket(&store, &id).await;
        assert_eq!(
            t.phase, case.expected,
            "Case '{}': unexpected phase after reset",
            case.name,
        );
        assert_eq!(
            t.pipeline_reservation, case.reservation,
            "Case '{}': unexpected pipeline_reservation after reset",
            case.name,
        );
        assert!(
            t.assigned_to.is_none(),
            "Case '{}': assigned_to should be NULL after reset",
            case.name,
        );
    }
}

#[tokio::test]
async fn test_claim_prefers_reserved_ticket() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // Create two ReadyForDevelopment tickets
    let fresh_id = make_ticket(&store, &ws, "Fresh", TicketPhase::ReadyForDevelopment).await;
    let reserved_id = make_ticket(&store, &ws, "Reserved", TicketPhase::ReadyForDevelopment).await;

    // Set reservation on the second ticket
    store
        .transition_to(
            &reserved_id,
            Some(TicketPhase::ReadyForDevelopment),
            TicketPhase::ReadyForDevelopment,
            Some(true),
        )
        .await
        .expect("set reservation");

    // When claiming with PipelineCheck::Enforce, the reserved ticket should be picked first
    let claimed = store
        .claim_ticket_in_workspace(
            TicketPhase::ReadyForDevelopment,
            TicketPhase::InDevelopment,
            "ws",
            PipelineCheck::Enforce,
            None,
        )
        .await
        .expect("claim")
        .expect("should claim a ticket");
    assert_eq!(
        claimed.id, reserved_id,
        "Reserved ticket should be claimed before fresh one"
    );
    assert!(
        !claimed.pipeline_reservation,
        "Claim should clear pipeline_reservation"
    );

    // Verify the cleared reservation is persisted in the DB
    // (the returned Ticket struct already reflects the DB state, but
    // a separate re-read explicitly tests persistence).
    let reserved_db = expect_ticket(&store, &reserved_id).await;
    assert!(
        !reserved_db.pipeline_reservation,
        "Reservation should be 0 in DB after claim"
    );

    // After the reserved ticket is claimed (now InDevelopment, pipeline-blocking),
    // the fresh ticket is still at ReadyForDevelopment but cannot be claimed
    // because the pipeline is blocked. Verify the fresh ticket remains untouched.
    let fresh = expect_ticket(&store, &fresh_id).await;
    assert_eq!(
        fresh.phase,
        TicketPhase::ReadyForDevelopment,
        "Fresh ticket should still be at ReadyForDevelopment"
    );
    assert!(
        !fresh.pipeline_reservation,
        "Fresh ticket should have no reservation"
    );
}

#[tokio::test]
async fn test_terminal_transition_clears_reservation() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // Reserve a ticket the way a bounce-back does.
    let id = make_ticket(&store, &ws, "Bounced", TicketPhase::Backlog).await;
    store
        .transition_to(
            &id,
            Some(TicketPhase::Backlog),
            TicketPhase::ReadyForDevelopment,
            Some(true),
        )
        .await
        .expect("reserve");
    assert!(
        expect_ticket(&store, &id).await.pipeline_reservation,
        "bounce-back should set reservation"
    );

    // Terminal transition (done) clears the flag even with reservation = None.
    store
        .transition_to(&id, None, TicketPhase::Done, None)
        .await
        .expect("done");
    let t = expect_ticket(&store, &id).await;
    assert_eq!(t.phase, TicketPhase::Done);
    assert!(
        !t.pipeline_reservation,
        "terminal transition must clear pipeline_reservation"
    );

    // Non-terminal control: a planning transition preserves the flag.
    let ctl = make_ticket(&store, &ws, "Control", TicketPhase::Backlog).await;
    store
        .transition_to(
            &ctl,
            Some(TicketPhase::Backlog),
            TicketPhase::ReadyForDevelopment,
            Some(true),
        )
        .await
        .expect("reserve control");
    store
        .transition_to(&ctl, None, TicketPhase::Planning, None)
        .await
        .expect("planning");
    let ctl = expect_ticket(&store, &ctl).await;
    assert_eq!(ctl.phase, TicketPhase::Planning);
    assert!(
        ctl.pipeline_reservation,
        "non-terminal transition must preserve pipeline_reservation"
    );
}

#[tokio::test]
async fn test_supersede_clears_reservation() {
    init_test_stores().await;
    let store = crate::board::BOARD.get().unwrap();
    let ws = test_ws_named("/ws", "ws");
    let old_id = make_ticket(store, &ws, "Test", TicketPhase::Backlog).await;
    store
        .transition_to(
            &old_id,
            Some(TicketPhase::Backlog),
            TicketPhase::ReadyForDevelopment,
            Some(true),
        )
        .await
        .expect("reserve");

    TicketBuilder::new(store, &ws)
        .title("New title")
        .desc("New desc")
        .supersede(&old_id)
        .await
        .expect("supersede");

    let old = expect_ticket(store, &old_id).await;
    assert_superseded_ticket(&old);
    assert!(
        !old.pipeline_reservation,
        "supersede cancellation must clear pipeline_reservation"
    );
}

#[tokio::test]
async fn test_clear_terminal_reservations_sweep() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // Stale pre-fix rows: terminal-phase tickets carrying a reservation,
    // including the archived shape (is_archived = 1, like the live stale row).
    let done_id = make_ticket(&store, &ws, "Done", TicketPhase::Done).await;
    let cancelled_id = make_ticket(&store, &ws, "Cancelled", TicketPhase::Cancelled).await;
    let failed_id = make_ticket(&store, &ws, "Failed", TicketPhase::Failed).await;
    let archived_id = make_ticket(&store, &ws, "Archived", TicketPhase::Done).await;
    store.set_archived(&archived_id).await.expect("archive");
    for id in [&done_id, &cancelled_id, &failed_id, &archived_id] {
        store
            .conn
            .execute(
                "UPDATE tickets SET pipeline_reservation = 1 WHERE id = ?1",
                crate::turso::params![id.clone()],
            )
            .await
            .expect("stale reservation");
    }
    let archived_before = expect_ticket(&store, &archived_id).await;

    // Reserved non-terminal ticket must survive the sweep.
    let reserved_id = make_ticket(&store, &ws, "Reserved", TicketPhase::ReadyForDevelopment).await;
    store
        .transition_to(
            &reserved_id,
            Some(TicketPhase::ReadyForDevelopment),
            TicketPhase::ReadyForDevelopment,
            Some(true),
        )
        .await
        .expect("reserve");

    assert_eq!(
        store.clear_terminal_reservations().await.expect("sweep"),
        4,
        "sweep should clear all four stale terminal rows"
    );

    for id in [&done_id, &cancelled_id, &failed_id, &archived_id] {
        assert!(
            !expect_ticket(&store, id).await.pipeline_reservation,
            "sweep must clear reservation on {id}"
        );
    }
    let archived_after = expect_ticket(&store, &archived_id).await;
    assert_eq!(
        archived_after.updated_at, archived_before.updated_at,
        "sweep must not bump updated_at"
    );
    assert!(
        expect_ticket(&store, &reserved_id)
            .await
            .pipeline_reservation,
        "sweep must not touch non-terminal reserved tickets"
    );
}

#[tokio::test]
async fn test_has_pipeline_blocker_reserved() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // A fresh ReadyForDevelopment ticket should NOT be a blocker
    let id = make_ticket(&store, &ws, "Fresh", TicketPhase::ReadyForDevelopment).await;
    assert!(
        !store
            .has_pipeline_blocker_for_workspace("ws")
            .await
            .expect("check"),
        "Fresh ReadyForDevelopment ticket should not be a pipeline blocker"
    );

    // After setting reservation, it should be a blocker
    store
        .transition_to(
            &id,
            Some(TicketPhase::ReadyForDevelopment),
            TicketPhase::ReadyForDevelopment,
            Some(true),
        )
        .await
        .expect("set reservation");
    assert!(
        store
            .has_pipeline_blocker_for_workspace("ws")
            .await
            .expect("check"),
        "Reserved ReadyForDevelopment ticket should be a pipeline blocker"
    );

    // After removing reservation, it should not be a blocker
    store
        .transition_to(
            &id,
            Some(TicketPhase::ReadyForDevelopment),
            TicketPhase::ReadyForDevelopment,
            Some(false),
        )
        .await
        .expect("clear reservation");
    assert!(
        !store
            .has_pipeline_blocker_for_workspace("ws")
            .await
            .expect("check"),
        "Non-reserved ReadyForDevelopment ticket should not be a pipeline blocker again"
    );
}

/// Assert that [`BoardStore::has_active_tickets_excluding`] returns the
/// expected value. Supports both static and formatted messages.
async fn assert_active_excluding(
    store: &BoardStore,
    ws_name: &str,
    exclude_id: &str,
    expected: bool,
    msg: impl std::fmt::Display,
) {
    assert_eq!(
        store
            .has_active_tickets_excluding(ws_name, exclude_id)
            .await
            .expect("check"),
        expected,
        "{msg}"
    );
}

/// Create 5 tickets in non-active phases under workspace "ws_non" (/ws_non),
/// returning their IDs.
///
/// Non-active phases covered: Done, Cancelled, Failed, Planning, Backlog.
/// Note: Analysis is also filtered out by the SQL query but is intentionally
/// omitted here — it has its own dedicated test coverage elsewhere.
async fn create_non_active_tickets(store: &BoardStore) -> Vec<String> {
    let ws = test_ws_named("/ws_non", "ws_non");
    vec![
        make_ticket(store, &ws, "Done", TicketPhase::Done).await,
        make_ticket(store, &ws, "Cancelled", TicketPhase::Cancelled).await,
        make_ticket(store, &ws, "Failed", TicketPhase::Failed).await,
        make_ticket(store, &ws, "Planning", TicketPhase::Planning).await,
        make_ticket(store, &ws, "Backlog", TicketPhase::Backlog).await,
    ]
}

/// Verify that [`BoardStore::has_active_tickets_excluding`] correctly identifies
/// active tickets (PIPELINE_BLOCKING_PHASES + ReadyForDevelopment) per workspace,
/// excluding a specified ticket ID.
///
/// Active tickets include all ReadyForDevelopment tickets regardless of
/// `pipeline_reservation`, unlike [`has_pipeline_blocker_for_workspace`] which
/// requires `pipeline_reservation = 1`. This is intentional — unstarted backlog
/// tickets are considered active to suppress Done notifications until the pipeline
/// is fully drained.
#[tokio::test]
async fn test_has_active_tickets_excluding() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // Create one ticket per active phase: all PIPELINE_BLOCKING_PHASES + ReadyForDevelopment
    let rfd_id = make_ticket(&store, &ws, "RFD", TicketPhase::ReadyForDevelopment).await;
    let in_dev_id = make_ticket(&store, &ws, "InDev", TicketPhase::InDevelopment).await;
    let done_id = make_ticket(&store, &ws, "Done", TicketPhase::Done).await;
    let cancelled_id = make_ticket(&store, &ws, "Cancelled", TicketPhase::Cancelled).await;

    // All non-excluded active tickets are found
    assert_active_excluding(
        &store,
        "ws",
        &done_id,
        true,
        "Should find active tickets (RFD + InDev) when excluding Done",
    )
    .await;

    // Excluding an active ticket still finds another active ticket
    assert_active_excluding(
        &store,
        "ws",
        &rfd_id,
        true,
        "Should find InDev as active when excluding RFD",
    )
    .await;
    assert_active_excluding(
        &store,
        "ws",
        &in_dev_id,
        true,
        "Should find RFD as active when excluding InDev",
    )
    .await;

    // Non-active (Done, Cancelled) exclusion should still find active tickets
    for exclude in [&done_id, &cancelled_id] {
        assert_active_excluding(
            &store,
            "ws",
            exclude,
            true,
            "Non-active exclusion should still find active tickets",
        )
        .await;
    }

    // ReadyForDevelopment without reservation counts as active
    // (rfd_id already has no reservation — it was created with default)
    assert_active_excluding(
        &store,
        "ws",
        "nonexistent",
        true,
        "Should find active tickets for nonexistent exclude ID",
    )
    .await;

    // Different workspace — no tickets
    assert_active_excluding(
        &store,
        "other_ws",
        &rfd_id,
        false,
        "Should not find active tickets in unrelated workspace",
    )
    .await;

    // Workspace with only non-active tickets — Done, Cancelled, Failed, Planning, Backlog
    let non_active_ids = create_non_active_tickets(&store).await;
    for exclude in &non_active_ids {
        assert_active_excluding(
                &store,
                "ws_non",
                exclude,
                false,
                format!("Workspace with only non-active tickets should have no active tickets (excluded {exclude})"),
            )
            .await;
    }
    // Excluding a nonexistent ID in a non-active-only workspace also returns false
    assert_active_excluding(
        &store,
        "ws_non",
        "nonexistent",
        false,
        "No active tickets for nonexistent exclude ID in non-active-only workspace",
    )
    .await;
}

/// Verify that every non-transitory pipeline-blocking phase has a reset transition.
///
/// [`PIPELINE_BLOCKING_PHASES`] defines 9 phases; 5 of them (InDevelopment,
/// InDiagnostics, InSanitation, InReview, InQa) have entries in
/// [`RESET_TRANSITIONS`]. The remaining 4 phases
/// ([`TRANSITORY_HANDOFF_PHASES`]) are transitory handoff states that the
/// poller picks up within seconds — no agent is mid-execution in those states,
/// so they don't need reset entries.
///
/// This test does NOT assert the reverse direction (reset → pipeline blocker),
/// because [`RESET_TRANSITIONS`] also includes `Analysis → Backlog`, and `Analysis`
/// is intentionally not a pipeline blocker (it's a pre-flight phase).
///
/// It also mechanically verifies that [`TRANSITORY_HANDOFF_PHASES`] is a subset of
/// [`PIPELINE_BLOCKING_PHASES`], ensuring the two sets stay in sync.
#[test]
fn test_pipeline_blockers_coverage() {
    // Verify that every transitory handoff phase is a pipeline blocker.
    for phase in TRANSITORY_HANDOFF_PHASES {
        assert!(
            PIPELINE_BLOCKING_PHASES.contains(phase),
            "\
TRANSITORY_HANDOFF_PHASES contains `{phase}` which is not in \
PIPELINE_BLOCKING_PHASES. Every transitory handoff phase must also \
be a pipeline blocker.\
                ",
        );
    }

    // Collect all `from` phases from BoardStore::RESET_TRANSITIONS for easy lookup.
    let reset_from: Vec<TicketPhase> = BoardStore::RESET_TRANSITIONS
        .iter()
        .map(|t| t.from)
        .collect();

    for phase in PIPELINE_BLOCKING_PHASES {
        let has_reset = reset_from.contains(phase);
        assert!(
            has_reset || phase.is_transitory_handoff(),
            "\
PIPELINE_BLOCKING_PHASES contains `{phase}` which has no corresponding \
entry in RESET_TRANSITIONS and is not a transitory handoff phase \
(see `TicketPhase::is_transitory_handoff`). Either add a reset transition to \
RESET_TRANSITIONS, or mark the phase as transitory handoff in that method \
with a comment explaining why no agent is mid-execution in that state.\
                ",
        );
    }
}

#[tokio::test]
async fn test_claim_ticket_in_workspace() {
    let (store, _tmp) = open_test_store().await;

    // Create tickets in two different workspaces
    let ws_a = test_ws_named("/ws_a", "workspace_a");
    let ws_b = test_ws_named("/ws_b", "workspace_b");

    let id_a = make_ticket(&store, &ws_a, "Ticket A", TicketPhase::Backlog).await;

    let id_b = make_ticket(&store, &ws_b, "Ticket B", TicketPhase::Backlog).await;

    // Claim ticket from workspace A — should succeed
    let claimed_a = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::InDevelopment,
            "workspace_a",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim in ws_a")
        .expect("should claim ticket from ws_a");
    assert_eq!(claimed_a.id, id_a);
    assert_eq!(claimed_a.workspace_name, "workspace_a");
    assert_eq!(claimed_a.phase, TicketPhase::InDevelopment);
    assert!(claimed_a.assigned_to.is_none());

    // Claim from workspace A again — should return None (no more backlog tickets)
    assert!(
        store
            .claim_ticket_in_workspace(
                TicketPhase::Backlog,
                TicketPhase::InDevelopment,
                "workspace_a",
                PipelineCheck::Skip,
                None,
            )
            .await
            .expect("second claim in ws_a")
            .is_none(),
        "no more tickets to claim in ws_a"
    );

    // Claim ticket from workspace B — should still succeed (different workspace)
    let claimed_b = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::InDevelopment,
            "workspace_b",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim in ws_b")
        .expect("should claim ticket from ws_b");
    assert_eq!(claimed_b.id, id_b);
    assert_eq!(claimed_b.workspace_name, "workspace_b");
}

#[tokio::test]
async fn test_claim_ticket_in_workspace_respects_claim_grace() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // Fresh ticket (created just now) must not be claimed within the grace window.
    let fresh = make_ticket(&store, &ws, "Fresh", TicketPhase::Backlog).await;
    assert!(
        store
            .claim_ticket_in_workspace(
                TicketPhase::Backlog,
                TicketPhase::Analysis,
                "ws",
                PipelineCheck::Skip,
                Some(chrono::Duration::seconds(60)),
            )
            .await
            .expect("claim")
            .is_none(),
        "fresh ticket must stay in backlog within the claim grace window"
    );

    // Once the ticket is older than the grace window it is claimable again.
    let old_created = (Utc::now() - chrono::Duration::seconds(120)).to_rfc3339();
    store
        .conn
        .execute(
            "UPDATE tickets SET created_at = ?1 WHERE id = ?2",
            crate::turso::params![old_created, fresh.clone()],
        )
        .await
        .expect("backdate");
    let claimed = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            "ws",
            PipelineCheck::Skip,
            Some(chrono::Duration::seconds(60)),
        )
        .await
        .expect("claim")
        .expect("old ticket should be claimable");
    assert_eq!(claimed.id, fresh);

    // No grace window: fresh tickets are claimed immediately.
    let fresh2 = make_ticket(&store, &ws, "Fresh2", TicketPhase::Backlog).await;
    let claimed = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            "ws",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim")
        .expect("fresh ticket claimable without grace window");
    assert_eq!(claimed.id, fresh2);
}

/// Table-driven tests for [`PipelineCheck::Enforce`] — claims with pipeline occupancy
/// checking enabled.
#[tokio::test]
async fn test_claim_ticket_in_workspace_if_pipeline_free() {
    /// The pipeline scenario for a single test case.
    enum Scenario {
        /// Blocker in the same workspace — claim should be blocked.
        SameWorkspace(TicketPhase),
        /// Blocker in a different workspace — claim should succeed.
        DifferentWorkspace(TicketPhase),
        /// No blocker — claim should succeed.
        NoBlocker,
    }

    struct Case {
        name: &'static str,
        /// Unique suffix for workspace names (isolates cases).
        suffix: &'static str,
        scenario: Scenario,
    }

    let cases = [
        Case {
            name: "blocked by same-workspace pipeline ticket",
            suffix: "blocked",
            scenario: Scenario::SameWorkspace(TicketPhase::InReview),
        },
        Case {
            name: "not blocked by cross-workspace pipeline ticket",
            suffix: "cross",
            scenario: Scenario::DifferentWorkspace(TicketPhase::InDevelopment),
        },
        Case {
            name: "no blocker succeeds",
            suffix: "none",
            scenario: Scenario::NoBlocker,
        },
    ];

    let (store, _tmp) = open_test_store().await;

    for case in &cases {
        let suffix = case.suffix;

        // Derive workspace names from the scenario.
        let (claim_ws_name, blocker_ws_name) = match &case.scenario {
            Scenario::DifferentWorkspace(_) => (
                format!("ws_{suffix}_claimable"),
                format!("ws_{suffix}_blocker"),
            ),
            // SameWorkspace and NoBlocker both use a single workspace name.
            Scenario::SameWorkspace(_) | Scenario::NoBlocker => {
                let name = format!("ws_{suffix}");
                (name.clone(), name)
            }
        };

        let expected_claim = !matches!(case.scenario, Scenario::SameWorkspace(_));

        let blocker_ws = test_ws_named(&format!("/{blocker_ws_name}"), &blocker_ws_name);
        let claimable_ws = test_ws_named(&format!("/{claim_ws_name}"), &claim_ws_name);

        // Create a pipeline blocker (if any)
        if let Scenario::SameWorkspace(phase) | Scenario::DifferentWorkspace(phase) = &case.scenario
        {
            // When blocker and claimable share a workspace, place the
            // blocker in the claimable's workspace (they are the same).
            let blocker_target = match &case.scenario {
                Scenario::DifferentWorkspace(_) => &blocker_ws,
                Scenario::SameWorkspace(_) => &claimable_ws,
                // Not reachable: NoBlocker is guarded by the enclosing if-let.
                Scenario::NoBlocker => unreachable!(),
            };
            make_ticket(&store, blocker_target, "Blocker", *phase).await;
        }

        // Create a claimable ticket
        let id = make_ticket(
            &store,
            &claimable_ws,
            "Claimable",
            TicketPhase::ReadyForDevelopment,
        )
        .await;

        // Claim with PipelineCheck::Enforce
        let claimed = store
            .claim_ticket_in_workspace(
                TicketPhase::ReadyForDevelopment,
                TicketPhase::InDevelopment,
                &claim_ws_name,
                PipelineCheck::Enforce,
                None,
            )
            .await
            .expect("claim should not error");

        if expected_claim {
            let claimed = claimed.expect("should claim ticket");
            assert_eq!(claimed.id, id, "Case '{}': wrong ticket id", case.name);
            assert_eq!(
                claimed.phase,
                TicketPhase::InDevelopment,
                "Case '{}': wrong phase after claim",
                case.name
            );
        } else {
            assert!(
                claimed.is_none(),
                "Case '{}': claim should be blocked",
                case.name
            );
        }
    }
}

// ── Prerequisites ────────────────────────────────────────────

#[tokio::test]
async fn test_create_ticket_with_prerequisites() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    // Create prerequisite tickets first
    let p1 = make_ticket(&store, &ws, "P1", TicketPhase::Backlog).await;
    let p2 = make_ticket(&store, &ws, "P2", TicketPhase::Backlog).await;

    // Create a ticket depending on both
    let deps = vec![p1.clone(), p2.clone()];
    let id = TicketBuilder::new(&store, &ws)
        .title("Dependent")
        .desc("needs both")
        .prereqs(&deps)
        .create()
        .await
        .expect("create dependent");

    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert_eq!(ticket.prerequisites.len(), 2);
    assert!(ticket.prerequisites.contains(&p1));
    assert!(ticket.prerequisites.contains(&p2));
}

/// Matrix of invalid prerequisite/supersede inputs for `create_ticket` and
/// `supersede_and_create`.
#[tokio::test]
async fn test_invalid_inputs() {
    let cases = [
        (InvalidInputOp::Create, InvalidInputScenario::NonExistent),
        (InvalidInputOp::Create, InvalidInputScenario::CrossWorkspace),
        (InvalidInputOp::Create, InvalidInputScenario::SelfReference),
        (InvalidInputOp::Supersede, InvalidInputScenario::NonExistent),
        (
            InvalidInputOp::Supersede,
            InvalidInputScenario::CrossWorkspace,
        ),
        (
            InvalidInputOp::Supersede,
            InvalidInputScenario::SelfReference,
        ),
    ];

    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");
    let ws_b = test_ws_named("/ws_b", "ws_b");
    // Isolated workspace for create/SelfReference: with exactly one seed
    // ticket, the hardcoded `{ws_sr}-1` predicts the next ID (board.rs
    // allocates IDs inside the tx before the self-reference check). No
    // other cell may write to ws_sr or the prediction silently breaks.
    let ws_sr = test_ws_named("/ws_sr", "ws_sr");

    for (op, scenario) in cases {
        // SelfReference keeps per-op arms — the error substrings differ
        // ('cannot depend on itself' vs 'supersede and depend'); the
        // NonExistent/CrossWorkspace substrings are identical across ops.
        let expected_error = match (op, scenario) {
            (_, InvalidInputScenario::NonExistent) => "not found",
            (_, InvalidInputScenario::CrossWorkspace) => "Cross-workspace",
            (InvalidInputOp::Create, InvalidInputScenario::SelfReference) => {
                "cannot depend on itself"
            }
            (InvalidInputOp::Supersede, InvalidInputScenario::SelfReference) => {
                "supersede and depend"
            }
        };

        // Seed a ticket for scenarios that reference an existing one.
        // NonExistent: none — reference a nonexistent id directly.
        // CrossWorkspace: seed in `ws`, referenced from `ws_b`.
        // SelfReference: supersede reuses the original in `ws`; create seeds
        //   the isolated `ws_sr` (counter invariant above).
        let seed: Option<String> = match scenario {
            InvalidInputScenario::NonExistent => None,
            InvalidInputScenario::CrossWorkspace => {
                Some(make_ticket(&store, &ws, "Existing", TicketPhase::Backlog).await)
            }
            InvalidInputScenario::SelfReference => {
                let seed_ws = match op {
                    InvalidInputOp::Create => &ws_sr,
                    InvalidInputOp::Supersede => &ws,
                };
                Some(make_ticket(&store, seed_ws, "Original", TicketPhase::Backlog).await)
            }
        };

        let target_ws = match (op, scenario) {
            (InvalidInputOp::Create, InvalidInputScenario::SelfReference) => &ws_sr,
            (_, InvalidInputScenario::CrossWorkspace) => &ws_b,
            (_, InvalidInputScenario::NonExistent)
            | (InvalidInputOp::Supersede, InvalidInputScenario::SelfReference) => &ws,
        };

        let prereqs: Vec<String> = match (op, scenario) {
            (InvalidInputOp::Create, InvalidInputScenario::NonExistent) => {
                vec!["nonexistent-1".to_string()]
            }
            (InvalidInputOp::Create, InvalidInputScenario::SelfReference) => {
                // Exactly one seed above → next id in ws_sr is `{ws_sr}-1`.
                vec![format!("{}-1", ws_sr.name)]
            }
            (
                InvalidInputOp::Supersede,
                InvalidInputScenario::NonExistent | InvalidInputScenario::CrossWorkspace,
            ) => vec![],
            (InvalidInputOp::Create, InvalidInputScenario::CrossWorkspace)
            | (InvalidInputOp::Supersede, InvalidInputScenario::SelfReference) => {
                vec![seed.clone().expect("seed")]
            }
        };

        let err = match op {
            InvalidInputOp::Create => TicketBuilder::new(&store, target_ws)
                .title("New")
                .prereqs(&prereqs)
                .create()
                .await
                .unwrap_err(),
            InvalidInputOp::Supersede => {
                // NonExistent supersedes a nonexistent target; the rest reuse
                // the seeded ticket.
                let supersede_id = seed.as_deref().unwrap_or("nonexistent");
                TicketBuilder::new(&store, target_ws)
                    .title("New")
                    .prereqs(&prereqs)
                    .supersede(supersede_id)
                    .await
                    .unwrap_err()
            }
        };
        assert!(
            err.to_string().contains(expected_error),
            "Case '{op:?}/{scenario:?}': expected error containing \
             '{expected_error}', got: {err}"
        );
    }
}

/// Create a 2-ticket dependency chain: A (no prereqs) → B (depends on A).
async fn create_chain_ab(store: &BoardStore, ws: Workspace) -> (String, String) {
    let a = make_ticket(store, &ws, "A", TicketPhase::Backlog).await;
    let b = TicketBuilder::new(store, &ws)
        .title("B")
        .desc("depends on A")
        .prereqs(std::slice::from_ref(&a))
        .create()
        .await
        .expect("create b");
    (a, b)
}

#[tokio::test]
async fn test_circular_dependency_rejected() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    let (a, b) = create_chain_ab(&store, ws.clone()).await;

    // Verify that A→B chain works: creating a ticket with both A and B
    // as prerequisites is NOT a cycle (it's just redundant, since A is
    // already transitively required through B). This should succeed.
    let _c = TicketBuilder::new(&store, &ws)
        .title("C")
        .desc("depends on both")
        .prereqs(&[a.clone(), b.clone()])
        .create()
        .await
        .expect("create c — A and B as prereqs is not a cycle");
}

#[tokio::test]
async fn test_transitive_prerequisites_block() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    let (a, b) = create_chain_ab(&store, ws.clone()).await;

    // C depends on B
    let c = TicketBuilder::new(&store, &ws)
        .title("C")
        .desc("top")
        .prereqs(std::slice::from_ref(&b))
        .create()
        .await
        .expect("create c");

    // C should be blocked even though B is done — A is still blocking
    // First claim: A is the only unblocked one
    let claimed = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            "ws",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim")
        .expect("should claim A");
    assert_eq!(claimed.id, a);

    // B should still be blocked — A is in Analysis, not Done yet
    let second = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            "ws",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim");
    assert!(
        second.is_none(),
        "B should be blocked because A is in Analysis, not Done"
    );

    // Move A to done
    store
        .transition_to(&a, None, TicketPhase::Done, None)
        .await
        .expect("done a");

    // Now B should be claimable
    let claimed2 = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            "ws",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim")
        .expect("should claim B");
    assert_eq!(claimed2.id, b);

    // Move B to done
    store
        .transition_to(&b, None, TicketPhase::Done, None)
        .await
        .expect("done b");

    // Now C should be claimable
    let claimed3 = store
        .claim_ticket_in_workspace(
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            "ws",
            PipelineCheck::Skip,
            None,
        )
        .await
        .expect("claim")
        .expect("should claim C");
    assert_eq!(claimed3.id, c);
}

async fn assert_archive_empty_db(store: &BoardStore) {
    let count = store
        .archive_stale_cancelled(1)
        .await
        .expect("archive_stale_cancelled");
    assert_eq!(count, 0, "Empty DB stale archive should return 0");
    let count = store
        .archive_all_done_and_cancelled(None)
        .await
        .expect("archive_all_done_and_cancelled");
    assert_eq!(count, 0, "Empty DB all archive should return 0");
}

#[tokio::test]
async fn test_archive_stale_cancelled() {
    let (store, _tmp) = open_test_store().await;
    assert_archive_empty_db(&store).await;

    let ws = test_ws_named("/ws", "ws");

    // Ticket 1: cancelled, old (2h) → should be archived
    let two_hours_ago = (Utc::now() - chrono::Duration::hours(2)).to_rfc3339();
    let old_cancelled_id = make_ticket(&store, &ws, "old-cancelled", TicketPhase::Cancelled).await;
    store
        .conn
        .execute(
            "UPDATE tickets SET updated_at = ?1 WHERE id = ?2",
            crate::turso::params![two_hours_ago.clone(), old_cancelled_id.clone()],
        )
        .await
        .expect("backdate");

    // Ticket 2: cancelled, fresh → should NOT be archived
    let fresh_cancelled_id =
        make_ticket(&store, &ws, "fresh-cancelled", TicketPhase::Cancelled).await;
    // No backdating — updated_at is now.

    // Ticket 3: not cancelled (Backlog), old → should NOT be archived
    let old_backlog_id = make_ticket(&store, &ws, "old-backlog", TicketPhase::Backlog).await;
    store
        .conn
        .execute(
            "UPDATE tickets SET updated_at = ?1 WHERE id = ?2",
            crate::turso::params![two_hours_ago.clone(), old_backlog_id.clone()],
        )
        .await
        .expect("backdate");

    // Act
    let count = store
        .archive_stale_cancelled(1)
        .await
        .expect("archive_stale_cancelled");
    assert_eq!(count, 1, "should archive only the old cancelled ticket");

    // Assert
    let old_cancelled = crate::util::test::expect_ticket(&store, &old_cancelled_id).await;
    assert!(
        old_cancelled.is_archived,
        "old cancelled ticket should be archived"
    );
    assert_eq!(old_cancelled.phase, TicketPhase::Cancelled);

    let fresh_cancelled = crate::util::test::expect_ticket(&store, &fresh_cancelled_id).await;
    assert!(
        !fresh_cancelled.is_archived,
        "fresh cancelled ticket should NOT be archived"
    );
    assert_eq!(fresh_cancelled.phase, TicketPhase::Cancelled);

    let old_backlog = crate::util::test::expect_ticket(&store, &old_backlog_id).await;
    assert!(
        !old_backlog.is_archived,
        "old non-cancelled ticket should NOT be archived"
    );
    assert_eq!(old_backlog.phase, TicketPhase::Backlog);
}

#[tokio::test]
async fn test_archive_all_done_and_cancelled() {
    let (store, _tmp) = open_test_store().await;
    assert_archive_empty_db(&store).await;

    let ws = test_ws_named("/ws", "ws");

    // Create three tickets: one Done, one Cancelled, one Backlog.
    let done_id = make_ticket(&store, &ws, "done", TicketPhase::Done).await;
    let cancelled_id = make_ticket(&store, &ws, "cancelled", TicketPhase::Cancelled).await;
    let backlog_id = make_ticket(&store, &ws, "backlog", TicketPhase::Backlog).await;

    // Before archiving, count_by_phase includes active tickets.
    let count_done_before = store
        .count_by_phase(TicketPhase::Done, None)
        .await
        .expect("count Done before");
    assert_eq!(
        count_done_before, 1,
        "Should count Done ticket before archive"
    );
    let count_cancelled_before = store
        .count_by_phase(TicketPhase::Cancelled, None)
        .await
        .expect("count Cancelled before");
    assert_eq!(
        count_cancelled_before, 1,
        "Should count Cancelled ticket before archive"
    );
    let count_backlog_before = store
        .count_by_phase(TicketPhase::Backlog, None)
        .await
        .expect("count Backlog before");
    assert_eq!(
        count_backlog_before, 1,
        "Should count Backlog ticket before archive"
    );

    // Act
    let count = store
        .archive_all_done_and_cancelled(None)
        .await
        .expect("archive");
    assert_eq!(count, 2, "should archive Done and Cancelled tickets");

    // Assert per-ticket state
    let done_ticket = crate::util::test::expect_ticket(&store, &done_id).await;
    assert!(done_ticket.is_archived, "Done ticket should be archived");
    assert_eq!(done_ticket.phase, TicketPhase::Done);

    let cancelled_ticket = crate::util::test::expect_ticket(&store, &cancelled_id).await;
    assert!(
        cancelled_ticket.is_archived,
        "Cancelled ticket should be archived"
    );
    assert_eq!(cancelled_ticket.phase, TicketPhase::Cancelled);

    let backlog_ticket = crate::util::test::expect_ticket(&store, &backlog_id).await;
    assert!(
        !backlog_ticket.is_archived,
        "Backlog ticket should NOT be archived"
    );
    assert_eq!(backlog_ticket.phase, TicketPhase::Backlog);

    // After archiving, count_by_phase excludes archived tickets.
    let count_done_after = store
        .count_by_phase(TicketPhase::Done, None)
        .await
        .expect("count Done after");
    assert_eq!(
        count_done_after, 0,
        "Should not count archived Done tickets"
    );
    let count_cancelled_after = store
        .count_by_phase(TicketPhase::Cancelled, None)
        .await
        .expect("count Cancelled after");
    assert_eq!(
        count_cancelled_after, 0,
        "Should not count archived Cancelled tickets"
    );
    let count_backlog_after = store
        .count_by_phase(TicketPhase::Backlog, None)
        .await
        .expect("count Backlog after");
    assert_eq!(
        count_backlog_after, 1,
        "Should still count non-archived Backlog tickets"
    );
}

#[tokio::test]
async fn test_archive_all_done_and_cancelled_workspace_filter() {
    let (store, _tmp) = open_test_store().await;

    // Create a done ticket in ws1 and another in ws2.
    let id1 = make_ticket(
        &store,
        &test_ws_named("/ws1", "ws1"),
        "Test",
        TicketPhase::Done,
    )
    .await;
    let id2 = make_ticket(
        &store,
        &test_ws_named("/ws2", "ws2"),
        "Test",
        TicketPhase::Done,
    )
    .await;

    // Archive only ws1.
    let count = store
        .archive_all_done_and_cancelled(Some("ws1"))
        .await
        .expect("archive_all_done_and_cancelled");
    assert_eq!(count, 1, "Should archive only ws1 ticket");

    let ticket1 = crate::util::test::expect_ticket(&store, &id1).await;
    assert!(ticket1.is_archived, "ws1 ticket should be archived");
    assert_eq!(
        ticket1.phase,
        TicketPhase::Done,
        "ws1 phase should remain Done"
    );

    let ticket2 = crate::util::test::expect_ticket(&store, &id2).await;
    assert!(!ticket2.is_archived, "ws2 ticket should NOT be archived");
    assert_eq!(
        ticket2.phase,
        TicketPhase::Done,
        "ws2 ticket should remain Done"
    );
}

#[tokio::test]
async fn test_create_ticket_tool_with_prerequisites() {
    crate::util::test::init_test_stores().await;

    let store = crate::board::BOARD.get().unwrap();
    let ws = test_ws("/tmp/test_ws_tool_prereqs");

    // Create a prerequisite via the store directly
    let p_id = make_ticket(store, &ws, "Pre", TicketPhase::Backlog).await;

    let tool = crate::tools::CreateTicketTool::new("test", &ws);
    let args = serde_json::json!({
        "title": "Test with prereqs",
        "description": "depends on something",
        "prerequisites": [p_id],
    });
    let result = tool.execute(&ws, args).await.expect("execute");
    assert!(
        result.contains(&p_id),
        "Output should mention prerequisite ID"
    );
}

/// Supersede a live ticket (`Backlog` → `Cancelled`).
///
/// This also implicitly covers superseding an already-cancelled ticket: the
/// cancellation UPDATE (in `supersede_and_create`) has no phase guard
/// (`WHERE id = ?3` without `AND phase = ?`), so it runs identically
/// regardless of the old ticket's current phase. A separate test with a
/// `Cancelled` starting phase would exercise the exact same SQL path and
/// assert the same invariants (`assert_superseded_ticket`, `supersedes`
/// back-link), making it redundant with this one.
#[tokio::test]
async fn test_supersede_and_create_basic() {
    init_test_stores().await;
    let store = crate::board::BOARD.get().unwrap();
    let ws = test_ws_named("/ws", "ws");
    let old_id = make_ticket(store, &ws, "Test", TicketPhase::Backlog).await;

    // Supersede it
    let new_id = TicketBuilder::new(store, &ws)
        .title("New title")
        .desc("New desc")
        .supersede(&old_id)
        .await
        .expect("supersede");

    // Old ticket is cancelled and points forward to the new ticket
    let old = expect_ticket(store, &old_id).await;
    assert_superseded_ticket(&old);
    assert_eq!(
        old.superseded_by.as_deref(),
        Some(new_id.as_str()),
        "superseded ticket should point to the new ticket"
    );

    // New ticket is in Backlog and links to old
    let new = expect_ticket(store, &new_id).await;
    assert_eq!(new.phase, TicketPhase::Backlog);
    assert_eq!(new.supersedes.as_deref(), Some(old_id.as_str()));
    assert_eq!(new.title, "New title");
}

#[tokio::test]
async fn test_supersede_rewires_only_matching_prerequisite() {
    init_test_stores().await;
    let store = crate::board::BOARD.get().unwrap();
    let ws = test_ws_named("/ws", "ws");

    // Create ticket A (will be superseded) and ticket C (independent).
    let a_id = make_ticket(store, &ws, "A", TicketPhase::Backlog).await;
    let c_id = make_ticket(store, &ws, "C", TicketPhase::Backlog).await;

    // Create ticket B that depends on both A and C.
    let b_id = TicketBuilder::new(store, &ws)
        .title("B")
        .desc("dep on A and C")
        .prereqs(&[a_id.clone(), c_id.clone()])
        .create()
        .await
        .expect("create B");

    // Create ticket D with no prerequisites — should be untouched.
    let d_id = make_ticket(store, &ws, "D", TicketPhase::Backlog).await;

    // Supersede A → A2.
    let supersede_id = TicketBuilder::new(store, &ws)
        .title("A2")
        .desc("refined")
        .supersede(&a_id)
        .await
        .expect("supersede");

    // B's prerequisites: A→A2, C unchanged.
    let b = store
        .get_ticket(&b_id)
        .await
        .expect("get B")
        .expect("B exists");
    assert_eq!(b.prerequisites, vec![supersede_id.clone(), c_id.clone()]);

    // D untouched.
    let d = store
        .get_ticket(&d_id)
        .await
        .expect("get D")
        .expect("D exists");
    assert!(d.prerequisites.is_empty());
}

#[tokio::test]
async fn test_supersede_tool() {
    crate::util::test::init_test_stores().await;

    let store = crate::board::BOARD.get().unwrap();
    let ws = test_ws("/tmp/test_ws_supersede_tool");

    // Create old ticket
    let old_id = make_ticket(store, &ws, "Old", TicketPhase::Backlog).await;

    let tool = crate::tools::CreateTicketTool::new("test", &ws);
    let args = serde_json::json!({
        "title": "Refined",
        "description": "refined desc",
        "supersede": old_id,
    });
    let result = tool.execute(&ws, args).await.expect("execute");
    assert!(
        result.contains("Superseded"),
        "Output should say Superseded: {result}"
    );
    assert!(
        result.contains(&old_id),
        "Output should mention old ID: {result}"
    );

    // Verify old is cancelled
    let old = expect_ticket(store, &old_id).await;
    assert_superseded_ticket(&old);
}

#[tokio::test]
async fn test_transactional_triple_write() {
    for should_succeed in [false, true] {
        // Exercise the transactional pattern that finalize_commit_and_transition
        // now uses via with_comment_and_transition: all three _tx writes
        // (set_commit_info_tx, add_comment_tx, transition_to_tx) in one
        // transaction → commit → all visible (or error rollback → none persist).
        let (store, _tmp) = open_test_store().await;
        let ws = test_ws_named("/ws", "ws");
        let id = make_ticket(&store, &ws, "Test", TicketPhase::QaPassed).await;

        let label = if should_succeed { "commit" } else { "rollback" };
        let result: anyhow::Result<()> =
            crate::turso::with_tx(&store.conn, &id, "test_triple_write", async |tx| {
                BoardStore::set_commit_info_tx(
                    tx,
                    &id,
                    "abcdef0123456789abcdef0123456789abcd0123",
                    10,
                    5,
                )
                .await?;
                BoardStore::add_comment_tx(
                    tx,
                    &id,
                    crate::role::SYSTEM_ROLE,
                    "triple write comment",
                )
                .await?;
                BoardStore::transition_to_tx(
                    tx,
                    &id,
                    Some(TicketPhase::QaPassed),
                    TicketPhase::Done,
                    None,
                )
                .await?;
                if should_succeed {
                    Ok(())
                } else {
                    Err(anyhow::anyhow!("simulated failure for rollback test"))
                }
            })
            .await;

        if !should_succeed {
            assert!(result.is_err(), "({label}) expected transaction failure");
        }

        let ticket = crate::util::test::expect_ticket(&store, &id).await;
        let comments = store.get_comments(&id).await.expect("get comments");
        if should_succeed {
            // All three changes should be visible.
            assert_eq!(
                ticket.commit_hash.as_deref(),
                Some("abcdef0123456789abcdef0123456789abcd0123"),
                "({label}) commit_hash",
            );
            assert_eq!(ticket.lines_added, Some(10), "({label}) lines_added");
            assert_eq!(ticket.lines_removed, Some(5), "({label}) lines_removed");
            assert_eq!(ticket.phase, TicketPhase::Done, "({label}) phase");
            assert_eq!(comments.len(), 1, "({label}) comments.len");
            assert_eq!(
                comments[0].content, "triple write comment",
                "({label}) comment content"
            );
        } else {
            // No changes should persist after rollback.
            assert_eq!(
                ticket.commit_hash, None,
                "({label}) commit_hash after rollback"
            );
            assert_eq!(
                ticket.lines_added, None,
                "({label}) lines_added after rollback"
            );
            assert_eq!(
                ticket.lines_removed, None,
                "({label}) lines_removed after rollback"
            );
            assert_eq!(
                ticket.phase,
                TicketPhase::QaPassed,
                "({label}) phase after rollback",
            );
            assert_eq!(comments.len(), 0, "({label}) comments.len after rollback");
        }
    }
}

// ── parse_prereqs unit tests ──

#[test]
fn test_parse_prereqs() {
    // ── Valid JSON cases ──
    let valid: &[(&str, &[&str])] = &[
        ("[]", &[] as &[&str]),
        (r#"["a","b","c"]"#, &["a", "b", "c"]),
    ];
    for (input, expected) in valid {
        let got = parse_prereqs(input).expect("should parse valid JSON");
        assert_eq!(got, *expected, "input: {input:?}");
    }

    // ── Invalid / corrupt JSON cases ──
    let invalid: &[&str] = &["", "not valid json {{{", r#"{"key":"value"}"#, "[1, 2, 3]"];
    for input in invalid {
        let err = parse_prereqs(input).unwrap_err();
        assert!(
            err.to_string().contains("Corrupt prerequisites JSON"),
            "input {input:?}: expected 'Corrupt prerequisites JSON' error, got: {err}",
        );
    }

    // ── Long ASCII input (>200 bytes) — preview truncated with ellipsis ──
    let long = format!(r#""{}...""#, "x".repeat(500));
    let msg = parse_prereqs(&long).unwrap_err().to_string();
    assert!(
        msg.contains(''),
        "long input should produce truncated preview: {msg}"
    );
    assert!(
        msg.len() < 500,
        "truncated message should be <500 chars, got len={}",
        msg.len()
    );

    // ── Multi-byte character straddling byte 200 — no panic on truncation ──
    // Without floor_char_boundary, `&raw[..200]` would panic on the mid-char slice.
    let raw = format!("{}éééééééééémore", "x".repeat(199));
    assert!(raw.len() > 200, "need raw longer than 200 chars");
    // Verify byte 200 is indeed within a multi-byte character (not a boundary).
    assert!(
        !raw.is_char_boundary(200),
        "byte 200 must be mid-character for this test to be meaningful"
    );
    let msg = parse_prereqs(&raw).unwrap_err().to_string();
    assert!(
        msg.contains(''),
        "multi-byte input should produce truncated preview: {msg}"
    );
    assert!(
        msg.len() < raw.len() + 50,
        "message too long after truncation: len={}, raw.len()={}",
        msg.len(),
        raw.len()
    );
    assert!(
        msg.contains("Corrupt prerequisites JSON"),
        "should mention corrupt JSON: {msg}"
    );
}

// ── Integration test: corrupt prerequisites in the database ──

#[tokio::test]
async fn corrupt_prerequisites_causes_query_errors() {
    let (store, _tmp, id) = setup().await;

    // Directly corrupt the prerequisites column via raw SQL
    store
        .conn
        .execute(
            "UPDATE tickets SET prerequisites = ?1 WHERE id = ?2",
            crate::turso::params!["{not valid json}", id.clone()],
        )
        .await
        .expect("corrupt update");

    // get_ticket should fail when prerequisites are corrupt
    let result = store.get_ticket(&id).await;
    assert!(
        result.is_err(),
        "get_ticket should fail when prerequisites are corrupt"
    );
    let err = result.unwrap_err();
    let msg = format!("{err:#}");
    assert!(
        msg.contains("Corrupt prerequisites JSON"),
        "error should mention corrupt JSON: {msg}"
    );
    assert!(
        msg.contains(&id),
        "error should include ticket ID {id}: {msg}"
    );

    // list_all_tickets should also fail entirely
    let result = store.list_all_tickets(Some("ws"), None).await;
    assert!(
        result.is_err(),
        "list_all_tickets should fail when any ticket has corrupt prerequisites"
    );
    let err = result.unwrap_err();
    let msg = format!("{err:#}");
    assert!(
        msg.contains("Corrupt prerequisites JSON"),
        "list_all_tickets error should mention corrupt JSON: {msg}"
    );
    assert!(
        msg.contains(&id),
        "list_all_tickets error should include ticket ID {id}: {msg}"
    );
}

// ── claim_diagnostics tests ──

/// Table-driven tests for `claim_diagnostics` covering success,
/// pre-assignment rejection, wrong-phase rejection, and idempotency.
#[tokio::test]
async fn test_claim_diagnostics() {
    enum Scenario {
        /// Ticket is unassigned and in InDiagnostics — claim should succeed.
        Success,
        /// Ticket is already assigned — claim should fail.
        AlreadyAssigned,
        /// Ticket is in a different phase — claim should fail.
        WrongPhase,
    }

    struct Case {
        name: &'static str,
        scenario: Scenario,
    }

    let cases = [
        Case {
            name: "unassigned in diagnostics succeeds",
            scenario: Scenario::Success,
        },
        Case {
            name: "already assigned fails",
            scenario: Scenario::AlreadyAssigned,
        },
        Case {
            name: "wrong phase fails",
            scenario: Scenario::WrongPhase,
        },
    ];

    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    for (i, case) in cases.iter().enumerate() {
        let title = format!("claim-{i}");
        let phase = if matches!(case.scenario, Scenario::WrongPhase) {
            TicketPhase::Backlog
        } else {
            TicketPhase::InDiagnostics
        };
        let id = make_ticket(&store, &ws, &title, phase).await;

        if matches!(case.scenario, Scenario::AlreadyAssigned) {
            store
                .set_assigned_to_no_cancel(&id, Some(DIAGNOSTICS_ROLE))
                .await
                .expect("set_assigned_to");
        }

        let claimed = store
            .claim_diagnostics(&id, DIAGNOSTICS_ROLE)
            .await
            .expect("claim_diagnostics");

        match case.scenario {
            Scenario::Success => {
                assert!(claimed, "Case '{}': expected claim to succeed", case.name);

                // Verify post-claim state.
                let ticket = crate::util::test::expect_ticket(&store, &id).await;
                assert_eq!(
                    ticket.assigned_to.as_deref(),
                    Some(DIAGNOSTICS_ROLE),
                    "Case '{}': assignee should be set",
                    case.name
                );
                assert_eq!(
                    ticket.phase,
                    TicketPhase::InDiagnostics,
                    "Case '{}': phase should remain InDiagnostics",
                    case.name
                );

                // Verify idempotency (second claim returns false).
                let second = store
                    .claim_diagnostics(&id, DIAGNOSTICS_ROLE)
                    .await
                    .expect("second claim");
                assert!(
                    !second,
                    "Case '{}': second claim should return false (idempotent)",
                    case.name
                );
            }
            Scenario::AlreadyAssigned | Scenario::WrongPhase => {
                assert!(!claimed, "Case '{}': expected claim to fail", case.name);
            }
        }
    }
}

// ── claim_sanitation tests ──

/// Table-driven tests for `claim_sanitation` covering success (QaPassed),
/// wrong-phase rejection, and assigned_to verification on successful claim.
#[tokio::test]
async fn test_claim_sanitation() {
    struct Case {
        name: &'static str,
        phase: TicketPhase,
        expected_claim: bool,
    }

    let cases = [
        Case {
            name: "qa_passed succeeds",
            phase: TicketPhase::QaPassed,
            expected_claim: true,
        },
        Case {
            name: "backlog (wrong phase) fails",
            phase: TicketPhase::Backlog,
            expected_claim: false,
        },
        Case {
            name: "in_development (wrong phase) fails",
            phase: TicketPhase::InDevelopment,
            expected_claim: false,
        },
    ];

    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/ws", "ws");

    for (i, case) in cases.iter().enumerate() {
        let title = format!("san-claim-{i}");
        let id = make_ticket(&store, &ws, &title, case.phase).await;

        // Compute before the call (needed as parameter even for non-claim cases).
        let expected_key = crate::session::ticket_agent_id(&id, crate::Role::Sanitation.as_str());

        let claimed = store
            .claim_sanitation(&id, &expected_key)
            .await
            .expect("claim_sanitation");
        assert_eq!(
            claimed, case.expected_claim,
            "Case '{}': unexpected claim result",
            case.name
        );

        if case.expected_claim {
            let ticket = crate::util::test::expect_ticket(&store, &id).await;
            assert_eq!(ticket.phase, TicketPhase::InSanitation);
            assert_eq!(
                ticket.assigned_to.as_deref(),
                Some(expected_key.as_str()),
                "Case '{}': assigned_to should be set to sanitation agent ID",
                case.name
            );
        }
    }
}

/// Sanitation claims serialize per workspace: a second claim in the same
/// workspace is blocked until the first clears the pipeline; other
/// workspaces proceed independently.
#[tokio::test]
async fn test_claim_sanitation_serialization() {
    for same_workspace in [true, false] {
        // Fresh store per iteration so the same-workspace Done transition
        // doesn't leak into the cross-workspace InSanitation assertions.
        let (store, _tmp) = open_test_store().await;
        let ws_a = test_ws_named("/ws_a", "ws_a");
        let ws_b = test_ws_named("/ws_b", "ws_b");
        let second_ws = if same_workspace { &ws_a } else { &ws_b };

        let first_id = make_ticket(&store, &ws_a, "First", TicketPhase::QaPassed).await;
        let second_id = make_ticket(&store, second_ws, "Second", TicketPhase::QaPassed).await;

        let first_key =
            crate::session::ticket_agent_id(&first_id, crate::Role::Sanitation.as_str());
        let second_key =
            crate::session::ticket_agent_id(&second_id, crate::Role::Sanitation.as_str());

        assert!(
            store
                .claim_sanitation(&first_id, &first_key)
                .await
                .expect("first claim"),
            "first claim should succeed"
        );

        let second_claimed = store
            .claim_sanitation(&second_id, &second_key)
            .await
            .expect("second claim");
        if same_workspace {
            assert!(
                !second_claimed,
                "second claim should be blocked while first ticket is in the sanitation pipeline"
            );
            // Direct to Done — SanitationPassed is also in the blocked set,
            // so moving there alone wouldn't clear it.
            store
                .transition_to(&first_id, None, TicketPhase::Done, None)
                .await
                .expect("transition first to Done");
            assert!(
                store
                    .claim_sanitation(&second_id, &second_key)
                    .await
                    .expect("second claim retry"),
                "second claim should succeed after pipeline clears"
            );
        } else {
            assert!(
                second_claimed,
                "claim in another workspace should succeed independently"
            );
            let a = expect_ticket(&store, &first_id).await;
            let b = expect_ticket(&store, &second_id).await;
            assert_eq!(a.phase, TicketPhase::InSanitation);
            assert_eq!(b.phase, TicketPhase::InSanitation);
        }
    }
}

#[tokio::test]
async fn test_set_assigned_to_none() {
    // Successfully clear an assigned assignee
    let (store, _tmp, id) = setup().await;

    store
        .set_assigned_to_no_cancel(&id, Some(DIAGNOSTICS_ROLE))
        .await
        .expect("set_assigned_to");
    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert_eq!(ticket.assigned_to.as_deref(), Some(DIAGNOSTICS_ROLE));

    store
        .set_assigned_to_no_cancel(&id, None)
        .await
        .expect("set_assigned_to(None) should clear assignee");
    let ticket = crate::util::test::expect_ticket(&store, &id).await;
    assert!(ticket.assigned_to.is_none(), "assigned_to should be NULL");

    // Idempotent: clearing an already-None assignee succeeds
    store
        .set_assigned_to_no_cancel(&id, None)
        .await
        .expect("second set_assigned_to(None) should also succeed");

    // Non-existent ticket fails
    let (store2, _tmp2) = open_test_store().await;
    let result = store2.set_assigned_to_no_cancel("nonexistent", None).await;
    assert!(
        result.is_err(),
        "set_assigned_to(None) on nonexistent ticket should fail"
    );
}

/// Round-trip test that exercises ALL column-index constants in
/// [`ticket_from_row`] by creating a ticket, setting every mutable field
/// via public API, then verifying every [`Ticket`] field (including
/// `pipeline_reservation` via its SQL `DEFAULT 0`) survives the
/// SELECT → `ticket_from_row` deserialization path.
///
/// Serves as a regression test for ticket deserialization — the
/// [`columns!`] macro ensures single-sourcing of [`TICKET_COLUMNS`]
/// and [`COL_TICKET_*`], so column-order drift between them is
/// structurally impossible. This test still exercises the full
/// `ticket_from_row` deserialization path, including manual
/// field-by-field extraction via `row.get::<Type>(COL_TICKET_*)`
/// and default-value handling.
#[expect(clippy::too_many_lines)]
#[tokio::test]
async fn test_ticket_roundtrip_all_fields() {
    let (store, _tmp) = open_test_store().await;

    // Non-existent ticket returns None.
    let none = store.get_ticket("nonexistent").await.expect("get");
    assert!(none.is_none(), "non-existent ticket should return None");

    let ws = crate::workspace::test_ws_named("/test_ws", "test_workspace");

    // Create ticket with known values.
    let id = TicketBuilder::new(&store, &ws)
        .title("Roundtrip Title")
        .desc("Roundtrip description")
        .phase(TicketPhase::Backlog)
        .reporter("test_reporter")
        .create()
        .await
        .expect("create_ticket");

    // ── Fresh ticket (defaults: no assigned_to, no comments, no commit info) ─
    let fresh = store
        .get_ticket(&id)
        .await
        .expect("get_ticket")
        .expect("ticket exists");

    assert!(
        fresh.created_at.contains('T'),
        "fresh created_at should be RFC 3339: {}",
        fresh.created_at,
    );
    assert!(
        fresh.updated_at.contains('T'),
        "fresh updated_at should be RFC 3339: {}",
        fresh.updated_at,
    );

    assert_eq!(
        fresh,
        Ticket {
            id: id.clone(),
            title: "Roundtrip Title".into(),
            description: "Roundtrip description".into(),
            phase: TicketPhase::Backlog,
            assigned_to: None,
            workspace_name: "test_workspace".into(),
            created_at: fresh.created_at.clone(),
            updated_at: fresh.updated_at.clone(),
            comments: vec![],
            prerequisites: vec![],
            supersedes: None,
            superseded_by: None,
            commit_hash: None,
            lines_added: None,
            lines_removed: None,
            reporter: "test_reporter".into(),
            is_archived: false,
            pipeline_reservation: false,
            priority: 1,
            reviewed_head: None,
            reviewed_tree: None,
            done_at: None,
            bounce_count: 0,
        },
    );

    // ── Mutated ticket (assigned_to + commit info) ──────────────────────
    store
        .set_assigned_to_no_cancel(&id, Some("test_assignee"))
        .await
        .expect("set_assigned_to");

    let tx = store.conn.begin_tx().await.unwrap();
    BoardStore::set_commit_info_tx(&tx, &id, "abcdef0123456789abcdef0123456789abcd0123", 42, 7)
        .await
        .expect("set_commit_info_tx");
    tx.commit().await.unwrap();

    store
        .set_reviewed_base(&id, Some("reviewed-head-hash"), Some("reviewed-tree-hash"))
        .await
        .expect("set_reviewed_base");

    let ticket = store
        .get_ticket(&id)
        .await
        .expect("get_ticket")
        .expect("ticket exists");

    assert!(
        ticket.created_at.contains('T'),
        "created_at should be RFC 3339: {}",
        ticket.created_at,
    );
    assert!(
        ticket.updated_at.contains('T'),
        "updated_at should be RFC 3339: {}",
        ticket.updated_at,
    );

    assert_eq!(
        ticket,
        Ticket {
            id: id.clone(),
            title: "Roundtrip Title".into(),
            description: "Roundtrip description".into(),
            phase: TicketPhase::Backlog,
            assigned_to: Some("test_assignee".into()),
            workspace_name: "test_workspace".into(),
            created_at: ticket.created_at.clone(),
            updated_at: ticket.updated_at.clone(),
            comments: vec![],
            prerequisites: vec![],
            supersedes: None,
            superseded_by: None,
            commit_hash: Some("abcdef0123456789abcdef0123456789abcd0123".into()),
            lines_added: Some(42),
            lines_removed: Some(7),
            reporter: "test_reporter".into(),
            is_archived: false,
            pipeline_reservation: false,
            priority: 1,
            reviewed_head: Some("reviewed-head-hash".into()),
            reviewed_tree: Some("reviewed-tree-hash".into()),
            done_at: None,
            bounce_count: 0,
        },
    );

    // ── Archived ticket (exercises is_archived bool deserialization) ────
    store.set_archived(&id).await.expect("set_archived");

    let archived = store
        .get_ticket(&id)
        .await
        .expect("get_ticket")
        .expect("ticket exists after archive");

    assert!(
        archived.created_at.contains('T'),
        "archived created_at should be RFC 3339: {}",
        archived.created_at,
    );
    assert!(
        archived.updated_at.contains('T'),
        "archived updated_at should be RFC 3339: {}",
        archived.updated_at,
    );

    assert_eq!(
        archived,
        Ticket {
            id,
            title: "Roundtrip Title".into(),
            description: "Roundtrip description".into(),
            phase: TicketPhase::Backlog,
            assigned_to: None,
            workspace_name: "test_workspace".into(),
            created_at: archived.created_at.clone(),
            updated_at: archived.updated_at.clone(),
            comments: vec![],
            prerequisites: vec![],
            supersedes: None,
            superseded_by: None,
            commit_hash: Some("abcdef0123456789abcdef0123456789abcd0123".into()),
            lines_added: Some(42),
            lines_removed: Some(7),
            reporter: "test_reporter".into(),
            is_archived: true,
            pipeline_reservation: false,
            priority: 1,
            reviewed_head: Some("reviewed-head-hash".into()),
            reviewed_tree: Some("reviewed-tree-hash".into()),
            done_at: None,
            bounce_count: 0,
        },
    );
}

// ── done_at completion timestamp ────────────────────────────────────

/// done_at is stamped on transition to Done, survives later comments, is
/// cleared when the ticket leaves Done, and is re-stamped on re-completion.
#[tokio::test]
async fn test_done_at_transition_semantics() {
    let (store, _tmp) = open_test_store().await;
    let ws = crate::workspace::test_ws_named("/test_ws", "test_workspace");
    let id = TicketBuilder::new(&store, &ws)
        .title("Done timestamp")
        .create()
        .await
        .expect("create_ticket");

    store
        .transition_to(&id, None, TicketPhase::Done, None)
        .await
        .expect("transition to done");
    let done = store.get_ticket(&id).await.expect("get").expect("ticket");
    let first_done_at = done.done_at.expect("done_at set on completion");
    assert!(
        done.created_at < first_done_at,
        "done_at should be later than creation"
    );

    // Later activity (comments) must not move the completion timestamp.
    store
        .add_comment(&id, "manager", "nice work")
        .await
        .expect("add_comment");
    let commented = store.get_ticket(&id).await.expect("get").expect("ticket");
    assert_eq!(commented.done_at.as_deref(), Some(first_done_at.as_str()));
    assert!(
        commented.updated_at > first_done_at,
        "comment should bump updated_at but not done_at"
    );

    // Leaving Done clears the stamp; re-completion re-stamps it.
    store
        .transition_to(&id, Some(TicketPhase::Done), TicketPhase::Backlog, None)
        .await
        .expect("reopen");
    let reopened = store.get_ticket(&id).await.expect("get").expect("ticket");
    assert_eq!(reopened.done_at, None, "done_at cleared when leaving Done");

    store
        .transition_to(&id, Some(TicketPhase::Backlog), TicketPhase::Done, None)
        .await
        .expect("re-complete");
    let redone = store.get_ticket(&id).await.expect("get").expect("ticket");
    assert!(
        redone.done_at.as_deref().unwrap() > first_done_at.as_str(),
        "re-completion re-stamps done_at with the new moment"
    );
}

// ── FTS search (archived + active) ─────────────────────────────────

/// Create an archived ticket with the given title in tests.
async fn create_archived_ticket(
    store: &super::BoardStore,
    title: &str,
    workspace_name: &str,
) -> String {
    let ws = test_ws(workspace_name);
    let id = make_ticket(store, &ws, title, crate::board::TicketPhase::Done).await;
    store.set_archived(&id).await.expect("set_archived");
    id
}

/// Create a non-archived ticket with the given title in tests.
async fn create_active_ticket(
    store: &super::BoardStore,
    title: &str,
    workspace_name: &str,
) -> String {
    let ws = test_ws(workspace_name);
    make_ticket(store, &ws, title, crate::board::TicketPhase::Backlog).await
}

#[tokio::test]
async fn test_search_by_fts_finds_matching_title() {
    let (store, _tmp) = open_test_store().await;
    let archived = create_archived_ticket(&store, "Fix network timeout bug", "ws1").await;
    let active = create_active_ticket(&store, "Fix network timeout bug", "ws_active").await;

    let archived_results = store
        .search_archived_by_fts("network timeout", 10, "ws1")
        .await
        .expect("archived FTS search");
    assert!(
        archived_results.iter().any(|(id, _)| id == &archived),
        "archived search should find the archived ticket"
    );

    let active_results = store
        .search_by_fts("network timeout", 10, Some("ws_active"))
        .await
        .expect("FTS search");
    assert!(
        active_results.iter().any(|t| t.id == active),
        "search should find the active ticket"
    );
}

#[tokio::test]
async fn test_search_by_fts_includes_both_archive_states() {
    let (store, _tmp) = open_test_store().await;
    let archived = create_archived_ticket(&store, "still searching", "ws2").await;
    let active = create_active_ticket(&store, "still active", "ws2").await;

    // General search must find tickets in either archive state.
    let results = store
        .search_by_fts("still", 10, Some("ws2"))
        .await
        .expect("general FTS search");
    assert!(
        results.iter().any(|t| t.id == archived),
        "archived ticket must appear in general search results"
    );
    assert!(
        results.iter().any(|t| t.id == active),
        "active ticket must appear in general search results"
    );

    // Archived-only search keeps its is_archived = 1 filter.
    let archived_results = store
        .search_archived_by_fts("active", 10, "ws2")
        .await
        .expect("archived FTS search");
    assert!(
        archived_results.is_empty(),
        "non-archived ticket must not appear in archived search"
    );
}

#[tokio::test]
async fn test_search_by_fts_sanitize_short_circuit() {
    let (store, _tmp) = open_test_store().await;
    for query in ["!@#$%", ""] {
        let archived = store
            .search_archived_by_fts(query, 10, "ws")
            .await
            .expect("archived FTS search");
        assert!(
            archived.is_empty(),
            "query {query:?} yields no archived results"
        );
        let results = store
            .search_by_fts(query, 10, Some("ws"))
            .await
            .expect("FTS search");
        assert!(
            results.is_empty(),
            "query {query:?} yields no search results"
        );
    }
}

#[tokio::test]
async fn test_search_by_fts_scoped_to_workspace() {
    let (store, _tmp) = open_test_store().await;
    create_active_ticket(&store, "Fix network timeout bug", "ws_scope_a").await;
    create_active_ticket(&store, "Database connection pool error", "ws_scope_b").await;

    let results = store
        .search_by_fts("network timeout", 10, Some("ws_scope_a"))
        .await
        .expect("FTS search scoped to ws_scope_a");
    assert_eq!(results.len(), 1, "should find only ws_scope_a ticket");
    assert_eq!(
        results[0].workspace_name, "ws_scope_a",
        "ticket belongs to ws_scope_a"
    );
}

/// Basic field layout of `detailed_display`: fields present, negative
/// assertions for absent fields, and "(no comments)" when empty.
#[tokio::test]
async fn test_detailed_display_basic() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/test-workspace", "test-ws");

    let prereq_id = make_ticket(&store, &ws, "Prereq", TicketPhase::Backlog).await;

    let id = TicketBuilder::new(&store, &ws)
        .title("Display Test Ticket")
        .desc("A description for testing")
        .phase(TicketPhase::InDevelopment)
        .prereqs(std::slice::from_ref(&prereq_id))
        .reporter("manager")
        .create()
        .await
        .expect("create");

    let ticket = expect_ticket(&store, &id).await;
    let display = ticket.detailed_display();

    assert!(
        display.contains(&format!("Ticket: {id}")),
        "should contain ticket id"
    );
    assert!(
        display.contains("Title: Display Test Ticket"),
        "should contain title"
    );
    assert!(
        display.contains("Description: A description for testing"),
        "should contain description"
    );
    assert!(
        display.contains("Phase: in_development"),
        "should use snake_case phase"
    );
    assert!(
        display.contains("Reporter: manager"),
        "should contain reporter"
    );
    assert!(
        display.contains("Workspace: test-ws"),
        "should contain workspace"
    );
    assert!(
        display.contains("Created:"),
        "should contain created timestamp"
    );
    assert!(
        display.contains("Updated:"),
        "should contain updated timestamp"
    );
    assert!(
        display.contains(&format!("Prerequisites: {prereq_id}")),
        "should show prerequisites"
    );
    assert!(
        display.contains("Comments:"),
        "should have comments section"
    );
    assert!(display.contains("(no comments)"), "should show no comments");
    assert!(
        display.contains("Priority: P1"),
        "should contain priority label (default 1)"
    );

    // Fields that should NOT appear when unset
    assert!(
        !display.contains("Supersedes:"),
        "no supersedes when not set"
    );
    assert!(
        !display.contains("Superseded by:"),
        "no superseded_by when not set"
    );
    assert!(
        !display.contains("Archived:"),
        "no archived line when false"
    );
    assert!(
        !display.contains("assigned_to:"),
        "assigned_to should not be displayed"
    );
    assert!(
        !display.contains("commit_hash:"),
        "commit_hash should not be displayed"
    );
    assert!(
        !display.contains("lines_added:"),
        "lines_added should not be displayed"
    );
    assert!(
        !display.contains("lines_removed:"),
        "lines_removed should not be displayed"
    );
}

/// `detailed_display` with comments (role labels, content) and multiple
/// prerequisites joined by comma+space.
#[tokio::test]
async fn test_detailed_display_with_content() {
    let (store, _tmp) = open_test_store().await;
    let ws = test_ws_named("/test-workspace", "test-ws");

    // ── Comment formatting: two comments with different roles ──

    let id = make_ticket(&store, &ws, "Comment Test", TicketPhase::Backlog).await;

    store
        .add_comment(&id, Role::Analyst.as_str(), "First comment")
        .await
        .expect("add_comment");
    store
        .add_comment(&id, Role::Reviewer.as_str(), "Second comment")
        .await
        .expect("add_comment");

    let ticket = expect_ticket(&store, &id).await;
    let display = ticket.detailed_display();

    assert!(
        display.contains("Comments:"),
        "should have comments section"
    );
    assert!(display.contains("[analyst]"), "should show analyst role");
    assert!(display.contains("[reviewer]"), "should show reviewer role");
    assert!(
        display.contains("First comment"),
        "should show first comment"
    );
    assert!(
        display.contains("Second comment"),
        "should show second comment"
    );
    assert!(
        !display.contains("(no comments)"),
        "should not say 'no comments' when comments exist"
    );

    // ── Multiple prerequisites: all three joined by comma+space ──

    let pre_a = make_ticket(&store, &ws, "Pre-A", TicketPhase::Backlog).await;
    let pre_b = make_ticket(&store, &ws, "Pre-B", TicketPhase::Backlog).await;
    let pre_c = make_ticket(&store, &ws, "Pre-C", TicketPhase::Backlog).await;

    let multi_id = TicketBuilder::new(&store, &ws)
        .title("Multi prereq")
        .prereqs(&[pre_a.clone(), pre_b.clone(), pre_c.clone()])
        .create()
        .await
        .expect("create");

    let ticket = expect_ticket(&store, &multi_id).await;
    let display = ticket.detailed_display();

    assert!(
        display.contains(&format!("Prerequisites: {pre_a}, {pre_b}, {pre_c}")),
        "should show all prerequisites joined with comma+space"
    );
}

/// `detailed_display` for supersedes chains: new ticket shows Supersedes,
/// old ticket shows Superseded by + Archived.
#[tokio::test]
async fn test_detailed_display_supersedes_chain() {
    init_test_stores().await;
    let store = crate::board::BOARD.get().unwrap();
    let ws = test_ws_named("/ws", "ws");

    // Create an old ticket first
    let old_id = make_ticket(store, &ws, "Old ticket", TicketPhase::Backlog).await;

    // Supersede it — new ticket gets supersedes = old_id, old ticket gets
    // superseded_by = new_id and is archived.
    let new_id = TicketBuilder::new(store, &ws)
        .title("New ticket")
        .desc("new desc")
        .supersede(&old_id)
        .await
        .expect("supersede");

    // Check the new ticket shows Supersedes
    let new_ticket = expect_ticket(store, &new_id).await;
    let new_display = new_ticket.detailed_display();
    assert!(
        new_display.contains(&format!("Supersedes: {old_id}")),
        "new ticket should show Supersedes: old_id"
    );

    // Check the old ticket shows Superseded by + Archived
    let old_ticket = expect_ticket(store, &old_id).await;
    let old_display = old_ticket.detailed_display();
    assert!(
        old_display.contains(&format!("Superseded by: {new_id}")),
        "old ticket should show Superseded by: new_id"
    );
    assert!(
        old_display.contains("Archived: yes"),
        "old ticket should be archived"
    );
}

#[tokio::test]
async fn test_list_archived_with_embeddings_returns_deserialized() {
    let (store, _tmp) = open_test_store().await;

    // Empty DB returns empty
    {
        let candidates = store
            .list_archived_with_embeddings("ws")
            .await
            .expect("list");
        assert!(candidates.is_empty(), "no tickets at all");
    }

    let ws = test_ws("ws");

    // Create a ticket with a known embedding blob (two small f32s)
    let embedding: Vec<f32> = vec![1.0, 2.0];
    let blob: Vec<u8> = embedding.iter().flat_map(|f| f.to_le_bytes()).collect();

    let id = TicketBuilder::new(&store, &ws)
        .title("Embedded ticket")
        .phase(crate::board::TicketPhase::Done)
        .embedding(&blob)
        .create()
        .await
        .expect("create_ticket with embedding");
    store.set_archived(&id).await.expect("archive");

    let candidates = store
        .list_archived_with_embeddings("ws")
        .await
        .expect("list");
    assert_eq!(candidates.len(), 1);
    assert_eq!(candidates[0].0, id);
    assert_eq!(candidates[0].1, vec![1.0, 2.0]);
}

// ── route_comment_to_agents tests ─────────────────────────────────────

/// route_comment_to_agents silently skips when no agents are assigned.
#[tokio::test]
async fn test_route_comment_to_agents_no_assignment() {
    crate::util::test::init_management_test_stores().await;
    let store = crate::board::store();
    let ws = crate::workspace::test_ws("/tmp/test_route_comment_no_assign");

    // Create a ticket WITHOUT assigned_to
    let ticket_id = crate::util::test::make_ticket(
        store,
        &ws,
        "no-assign-test",
        crate::board::TicketPhase::Backlog,
    )
    .await;

    // Add a comment — should succeed without routing (no assigned agents)
    store
        .add_comment(&ticket_id, "manager", "No one should get this")
        .await
        .expect("add_comment should succeed");
}

/// route_comment_to_agents delivers a comment to the registered agent with
/// the commenter's role in the AgentJob. The engineer row guards the
/// Role::parse → Manager fallback — the manager row alone would pass silently.
///
/// Serialized with the reset_inflight_tickets tests (shared global board — a
/// concurrent boot reset would clobber the fixture phases).
#[tokio::test]
#[serial_test::serial(reset_inflight)]
async fn test_route_comment_to_agents_delivers_with_commenter_role() {
    crate::util::test::init_management_test_stores().await;
    let store = crate::board::store();

    for (i, (commenter, content, expected_role)) in [
        ("manager", "Hello from test", crate::Role::Manager),
        ("engineer", "Code review feedback", crate::Role::Engineer),
    ]
    .into_iter()
    .enumerate()
    {
        let ws = crate::workspace::test_ws(format!("/tmp/test_route_comment_{i}"));
        let ticket_id = crate::util::test::make_ticket(
            store,
            &ws,
            &format!("route-comment-test-{i}"),
            crate::board::TicketPhase::InDevelopment,
        )
        .await;

        let agent_id = format!("_test_route_comment_agent_{i}");
        store
            .set_assigned_to_no_cancel(&ticket_id, Some(&agent_id))
            .await
            .expect("set assigned_to");
        let mut rx = crate::message_router::register_agent(&agent_id);

        store
            .add_comment(&ticket_id, commenter, content)
            .await
            .expect("add_comment should succeed");

        let received = rx.try_recv().expect("should receive the routed comment");
        assert_eq!(received.content, content);
        assert_eq!(received.kind, crate::message_router::JobKind::TicketComment);
        assert_eq!(received.user_name, commenter);
        assert_eq!(
            received.role, expected_role,
            "role should be the commenter's role ({commenter})",
        );
        assert!(
            rx.try_recv().is_err(),
            "should not have additional messages"
        );

        crate::message_router::unregister_agent(&agent_id);
    }
}

/// Manual "Redo Dev" bounce-back transitions Reviewed → ReadyForDevelopment
/// and increments the bounce counter atomically (so manual bounces consume
/// the same breaker budget as pipeline bounces).
#[tokio::test]
async fn test_bounce_back_to_dev_transitions_and_increments_counter() {
    let (store, _tmp) = open_test_store().await;
    let ws = crate::workspace::test_ws("/tmp/test_bounce_back_to_dev");
    let id = make_ticket(&store, &ws, "Redo Dev", TicketPhase::Reviewed).await;

    assert!(
        store
            .bounce_back_to_dev(&id)
            .await
            .expect("bounce-back succeeds"),
        "bounce-back from Reviewed must apply"
    );

    let ticket = expect_ticket(&store, &id).await;
    assert_eq!(ticket.phase, TicketPhase::ReadyForDevelopment);
    assert_eq!(ticket.bounce_count, 1, "manual bounce must count");

    // A second Redo Dev from Reviewed (e.g. after a fresh review pass)
    // increments again; bouncing from a non-Reviewed phase is rejected.
    store
        .transition_to(&id, None, TicketPhase::Reviewed, None)
        .await
        .expect("move back to Reviewed for a second round");
    assert!(
        store
            .bounce_back_to_dev(&id)
            .await
            .expect("second bounce-back succeeds"),
        "second bounce-back from Reviewed must apply"
    );
    let ticket = expect_ticket(&store, &id).await;
    assert_eq!(ticket.bounce_count, 2);

    store
        .transition_to(&id, None, TicketPhase::InQa, None)
        .await
        .expect("move to InQa");
    // Bouncing from a non-Reviewed phase is a phase-guard miss: the ticket
    // moved externally, which is an expected, silent no-op — not an error
    // (the claim convention: guard miss = `Ok(false)`).
    let outcome = store
        .bounce_back_to_dev(&id)
        .await
        .expect("guard-missed bounce-back must not error");
    assert!(
        !outcome,
        "bounce-back from a non-Reviewed phase must report the guard miss"
    );
    let ticket = expect_ticket(&store, &id).await;
    assert_eq!(
        ticket.phase,
        TicketPhase::InQa,
        "guard-missed bounce-back must leave the ticket untouched"
    );
    assert_eq!(
        ticket.bounce_count, 2,
        "guard-missed bounce-back must not bump the bounce counter"
    );
}