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
//! Ticket/board system — Turso-backed task management.

use crate::turso::{self, IntoParams, TxGuard, Value};
use anyhow::{Context, Result};
use chrono::{Duration, Utc};
use serde::Serialize;
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::LazyLock;
use tracing::{debug, info, warn};

crate::define_store! {
    /// Global board store.
    pub static BOARD: BoardStore,
    db_name = "board",
    schema = SCHEMA,
    post_open = after_open,
    expect = "BOARD not initialized — call init_global() first",
}

/// Background task: auto-archive cancelled tickets older than 1 hour and
/// sweep stale terminal-phase pipeline reservations.
///
/// Runs every 5 minutes, respects the global shutdown token via
/// [`crate::shutdown::sleep_or_shutdown_or_drain`] (same pattern as
/// [`crate::maintainer::run_maintainer_loop`]).
/// Logs per-pass failures and continues.
pub async fn run_archive_cancelled_loop() {
    let interval = std::time::Duration::from_mins(5);

    loop {
        if !crate::shutdown::sleep_or_shutdown_or_drain(interval).await {
            break;
        }

        // Engineer-anchor terminal deletion (S5): remove permanently-NULL
        // seats for tickets in a terminal phase — the TTL guard stops
        // protecting the accumulated engineer session once the anchor is gone
        // (idempotent, ≤5-min delay against the 8h TTL).
        crate::jobs::purge_terminal_engineer_anchors().await;

        let Some(board) = BOARD.get() else {
            warn!("Archive cancelled loop: board not initialized");
            continue;
        };

        match board.archive_stale_cancelled(CANCELLED_ARCHIVE_HOURS).await {
            Ok(n) if n > 0 => info!(count = n, "Archived stale cancelled tickets"),
            Ok(_) => debug!("Archive cancelled loop: no stale tickets"),
            Err(e) => warn!(error = %e, "Archive cancelled loop failed"),
        }

        match board.clear_terminal_reservations().await {
            Ok(n) if n > 0 => info!(count = n, "Cleared stale terminal pipeline reservations"),
            Ok(_) => debug!("Reservation sweep: no stale terminal reservations"),
            Err(e) => warn!(error = %e, "Reservation sweep failed"),
        }
    }
}

const SCHEMA: &str = "\
CREATE TABLE IF NOT EXISTS tickets (
    id              TEXT PRIMARY KEY,
    title           TEXT NOT NULL,
    description     TEXT NOT NULL,
    phase          TEXT NOT NULL DEFAULT 'backlog',
    assigned_to     TEXT,
    workspace_name  TEXT NOT NULL,
    created_at      TEXT NOT NULL,
    updated_at      TEXT NOT NULL,
    prerequisites   TEXT NOT NULL DEFAULT '[]',
    supersedes      TEXT,
    superseded_by   TEXT,
    commit_hash     TEXT,
    lines_added     INTEGER,
    lines_removed   INTEGER,
    reporter        TEXT NOT NULL DEFAULT '',
    is_archived     INTEGER NOT NULL DEFAULT 0,
    embedding       BLOB,
    pipeline_reservation INTEGER NOT NULL DEFAULT 0,
    priority        INTEGER NOT NULL DEFAULT 1,
    reviewed_head   TEXT,
    reviewed_tree   TEXT,
    done_at         TEXT,
    bounce_count    INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS ticket_comments (
    id          TEXT PRIMARY KEY,
    ticket_id   TEXT NOT NULL,
    role        TEXT NOT NULL,
    content     TEXT NOT NULL,
    created_at  TEXT NOT NULL,
    FOREIGN KEY (ticket_id) REFERENCES tickets(id)
);
CREATE INDEX IF NOT EXISTS idx_ticket_comments_ticket_id ON ticket_comments(ticket_id);
CREATE TABLE IF NOT EXISTS ticket_counters (
    workspace_name TEXT PRIMARY KEY,
    next_id        INTEGER NOT NULL DEFAULT 1
);
";

const TICKETS_FTS_INDEX_NAME: &str = "idx_tickets_title_fts";
const TICKETS_FTS_INDEX_DDL: &str = "\
CREATE INDEX IF NOT EXISTS idx_tickets_title_fts ON tickets \
USING fts (title) WITH (tokenizer = 'ngram')";

/// Stale-cancelled archival window (hours): Cancelled tickets this old are
/// archived by [`run_archive_cancelled_loop`].
const CANCELLED_ARCHIVE_HOURS: i64 = 1;

// Column definitions for ticket SELECT/RETURNING queries.
crate::columns! {
    TICKET_COLUMNS [TICKET] {
        ID                     => "id",
        TITLE                  => "title",
        DESCRIPTION            => "description",
        PHASE                  => "phase",
        ASSIGNED_TO            => "assigned_to",
        WORKSPACE_NAME         => "workspace_name",
        CREATED_AT             => "created_at",
        UPDATED_AT             => "updated_at",
        PREREQUISITES          => "prerequisites",
        SUPERSEDES             => "supersedes",
        SUPERSEDED_BY          => "superseded_by",
        COMMIT_HASH            => "commit_hash",
        LINES_ADDED            => "lines_added",
        LINES_REMOVED          => "lines_removed",
        REPORTER               => "reporter",
        IS_ARCHIVED            => "is_archived",
        PIPELINE_RESERVATION   => "pipeline_reservation",
        PRIORITY               => "priority",
        REVIEWED_HEAD          => "reviewed_head",
        REVIEWED_TREE          => "reviewed_tree",
        DONE_AT                => "done_at",
        BOUNCE_COUNT           => "bounce_count",
    }
}

// Column definitions for comment SELECT queries.
// Note: `id` and `ticket_id` are intentionally excluded from the column list
// because they are not consumed by the comment rendering path:
// - `ticket_id` is already known from the parent ticket query context
// - `id` is not read by any comment consumer
// These columns remain in the database schema and are not candidates for removal.
crate::columns! {
    COMMENT_COLUMNS [COMMENT] {
        ROLE       => "role",
        CONTENT    => "content",
        CREATED_AT => "created_at",
    }
}

/// Phases where a ticket occupies the dev/review/QA pipeline.
///
/// Only one ticket at a time per workspace may be in this pipeline. Any ticket in one of these
/// phases blocks new Engineer dispatches for that workspace. The Maintainer uses a separate
/// pre-development threshold (Analysis + Planning + ReadyForDevelopment) and is no longer
/// directly suppressed by this constant.
///
/// Note: [`BoardStore::reset_inflight_tickets`] (via [`BoardStore::RESET_TRANSITIONS`]) only resets a subset
/// of these (InDevelopment, InDiagnostics, InSanitation, InReview, InQa) plus Analysis — see its
/// docs for rationale. The remaining four phases (DiagnosticsDone, SanitationPassed, Reviewed, QaPassed) are transitory
/// handoff states intentionally excluded from reset. The `tests::test_pipeline_blockers_coverage`
/// test enforces that every non-transitory pipeline blocker has a corresponding reset transition.
const PIPELINE_BLOCKING_PHASES: &[TicketPhase] = &[
    TicketPhase::InDevelopment,
    TicketPhase::InDiagnostics,
    TicketPhase::DiagnosticsDone,
    TicketPhase::InReview,
    TicketPhase::Reviewed,
    TicketPhase::InQa,
    TicketPhase::QaPassed,
    TicketPhase::InSanitation,
    TicketPhase::SanitationPassed,
];

/// The sanitation pipeline — only one ticket per workspace may be in these
/// phases at a time (serialization enforced by [`BoardStore::claim_sanitation`]).
///
/// Subset of [`PIPELINE_BLOCKING_PHASES`].
const SANITATION_PIPELINE_PHASES: &[TicketPhase] =
    &[TicketPhase::InSanitation, TicketPhase::SanitationPassed];

/// Pipeline-blocking phases that are transitory handoff states — no agent is
/// mid-execution in these phases, so they don't need a reset transition. The
/// poller picks them up within seconds.
///
/// This is a subset of [`PIPELINE_BLOCKING_PHASES`]. The relationship is
/// mechanically verified by `tests::test_pipeline_blockers_coverage`.
#[cfg(test)]
const TRANSITORY_HANDOFF_PHASES: &[TicketPhase] = &[
    TicketPhase::DiagnosticsDone,
    TicketPhase::SanitationPassed,
    TicketPhase::Reviewed,
    TicketPhase::QaPassed,
];

/// Phases that unblock dependent tickets.
///
/// When a ticket transitions to one of these phases, any tickets that
/// depend on it become eligible for claiming (their prerequisite filter
/// no longer blocks them).
///
/// [`TicketPhase::Failed`] is intentionally excluded — a failed ticket
/// permanently blocks its dependents, requiring manual intervention.
///
/// [`TicketPhase::is_unblocking`] delegates to this constant to ensure
/// the unblocking set is always authoritative. If a new phase is added
/// here, `is_unblocking()` automatically picks it up; if the set ever
/// needs to diverge from the unblocking set, this delegation must be
/// broken explicitly.
pub const UNBLOCKING_PHASES: &[TicketPhase] = &[TicketPhase::Done, TicketPhase::Cancelled];

/// Terminal phases — a ticket in one of these can no longer be claimed.
///
/// [`TicketPhase::is_terminal`] delegates to this constant. Used to clear
/// [`pipeline_reservation`](Ticket::pipeline_reservation) on terminal
/// transitions and by the periodic reservation sweep.
///
/// Note: `Failed` is deliberately included here even though it is excluded
/// from [`UNBLOCKING_PHASES`] (a failed ticket permanently blocks dependents).
pub const TERMINAL_PHASES: &[TicketPhase] = &[
    TicketPhase::Done,
    TicketPhase::Cancelled,
    TicketPhase::Failed,
];

/// Produces an SQL fragment listing phases as quoted, comma-separated
/// strings — e.g. `'done', 'cancelled'`.
///
/// # Precondition
///
/// The input slice must be non-empty. Passing an empty slice produces
/// `WHERE phase IN ()` which is invalid SQL.
fn phase_list_sql_fragment(phases: &[TicketPhase]) -> String {
    phases
        .iter()
        .map(|p| format!("'{}'", p.as_ref()))
        .collect::<Vec<_>>()
        .join(", ")
}

fn parse_prereqs(raw: &str) -> Result<Vec<String>> {
    serde_json::from_str(raw).with_context(|| {
        let preview = if raw.len() > 200 {
            format!("{}", crate::util::truncate_bytes(raw, 200))
        } else {
            raw.to_string()
        };
        format!("Corrupt prerequisites JSON in database: {preview}")
    })
}

/// Bundled parameters for ticket creation.
///
/// Reduces parameter explosion across [`BoardStore::insert_ticket_tx`],
/// [`BoardStore::create_ticket`], and [`BoardStore::supersede_and_create`].
#[derive(Debug, Clone)]
pub(crate) struct TicketParams {
    pub title: String,
    pub description: String,
    pub workspace_name: String,
    pub phase: TicketPhase,
    pub prerequisites: Vec<String>,
    pub reporter: String,
    pub embedding: Option<Vec<u8>>,
    pub priority: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TicketComment {
    pub role: String,
    pub content: String,
    pub created_at: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Ticket {
    pub id: String,
    pub title: String,
    pub description: String,
    pub phase: TicketPhase,
    pub assigned_to: Option<String>,
    pub workspace_name: String,
    pub created_at: String,
    pub updated_at: String,
    pub comments: Vec<TicketComment>,
    /// IDs of tickets that must be completed before this one can be claimed.
    pub prerequisites: Vec<String>,
    /// ID of the ticket this one supersedes (set when created via supersede).
    /// The superseded ticket is cancelled atomically during creation.
    pub supersedes: Option<String>,
    /// ID of the ticket that supersedes this one (set on the old ticket when
    /// it is superseded). Purely informational — never drives logic.
    pub superseded_by: Option<String>,
    /// Full commit SHA (40 hex chars), `None` if no commit recorded.
    pub commit_hash: Option<String>,
    /// Lines added (non-negative) from the associated commit.
    pub lines_added: Option<i64>,
    /// Lines removed (non-negative) from the associated commit.
    pub lines_removed: Option<i64>,
    /// Creator/tool identity — set at construction time.
    /// Also used in the GUI board display: when the value matches a known role
    /// name, the role's display label is shown (e.g. "Manager"); otherwise the
    /// content is shown with the first character uppercased (e.g. "Test" for
    /// "test"). May be empty when no reporter is recorded.
    pub reporter: String,
    /// Whether this ticket has been archived (hidden from normal listings).
    pub is_archived: bool,
    /// Whether this ticket holds a pipeline reservation (bounced back for
    /// rework — review/QA bounce-back, diagnostics/sanitation failure, or
    /// engineer hard failure — and awaiting rework). When set, the ticket
    /// gets priority over other ReadyForDevelopment tickets during claim.
    pub pipeline_reservation: bool,
    pub priority: i64,
    /// HEAD commit hash at the last completed reviewer round on this ticket.
    /// `None` until the first reviewer pass finishes — used by the reviewer
    /// skip-gate to detect brand-new content that must never skip review.
    pub reviewed_head: Option<String>,
    /// `git write-tree` index tree hash at the last completed reviewer round
    /// (captured after the post-review auto-stage). Together with
    /// [`reviewed_head`](Self::reviewed_head) and a clean porcelain this
    /// identifies the exact content reviewers saw.
    pub reviewed_tree: Option<String>,
    /// Exact completion timestamp: set on transition to Done, cleared when the
    /// ticket leaves Done. `None` for never-done or not-currently-done tickets.
    pub done_at: Option<String>,
    /// Number of times this ticket bounced back into development (review/QA
    /// bounce-backs and engineer hard failures). Drives the bounce-based
    /// circuit breaker (max 10).
    pub bounce_count: i64,
}

impl Ticket {
    /// Short single-line display for listing tickets in agent-facing output.
    ///
    /// Returns `"  [{reporter}] [{phase}] {id}: {title}"` (note the leading
    /// two-space indent for alignment within a multi-line block). The trailing
    /// newline is omitted — callers add it via `writeln!` or equivalent.
    ///
    /// The `{phase}` field uses the snake_case Display representation from
    /// [`TicketPhase`] (e.g. `"in_development"`), which is the canonical form
    /// for agent-facing output. For user-facing labels with spaces instead of
    /// underscores, use [`TicketPhase::display_name()`] directly.
    ///
    /// ## Related formatting (not duplicated here)
    ///
    /// - `crate::prompt::format_ticket_block` produces a Markdown
    ///   `<current-ticket>` block for system messages — intentionally different
    ///   format and should not be unified.
    /// - `search_archived_tickets` format omits the reporter field
    ///   (`"  [{phase}] {id}: {title}"`) — intentionally different.
    #[must_use]
    pub fn short_display(&self) -> String {
        format!(
            "  [{}] [{}] {}: {}",
            self.reporter, self.phase, self.id, self.title
        )
    }

    /// Produce a detailed multi-line display of the ticket, suitable for
    /// [`GetTicketTool`](crate::tools::ticket::GetTicketTool) and other agent-facing output.
    ///
    /// The output includes these fields (when present):
    ///
    /// - Ticket ID, Title, Description
    /// - Phase (snake_case — e.g. `ready_for_development`)
    /// - Priority (P0–P4+ label)
    /// - Reporter, Workspace, Created, Updated
    /// - Supersedes, Superseded by, Prerequisites (conditionally when non-empty)
    /// - Archived flag (conditionally when `true`)
    /// - Comments block (via [`Self::format_comments`])
    ///
    /// ## Fields *not* displayed
    ///
    /// The following [`Ticket`] fields are deliberately omitted — they are
    /// available in the board UI but not meaningful for agent context:
    ///
    /// - `assigned_to`
    /// - `commit_hash`
    /// - `lines_added` / `lines_removed`
    ///
    /// ## Output size
    ///
    /// The returned string can be arbitrarily large (unbounded descriptions
    /// and comments). Callers that need truncation should apply their own
    /// limits (see `GetTicketTool::preserve_full_output` for an example that
    /// disables the default 5 KB truncation).
    ///
    /// ## Changing this output
    ///
    /// Because agent tool calls depend on this exact format, changes to
    /// displayed fields or layout must be kept in sync with
    /// [`crate::tools::ticket::GetTicketTool`] (the primary consumer). If new fields are
    /// added here, update the integration test `test_get_ticket_tool`
    /// to prevent silent divergence.
    #[must_use]
    pub fn detailed_display(&self) -> String {
        let mut out = format!(
            "Ticket: {id}\n\
             Title: {title}\n\
             Description: {description}\n\
             Phase: {phase}\n\
             Reporter: {reporter}\n\
             Workspace: {workspace}\n\
             Created: {created}\n\
             Updated: {updated}\n\
             Priority: P{priority}\n",
            id = self.id,
            title = self.title,
            description = self.description,
            phase = self.phase,
            reporter = self.reporter,
            workspace = self.workspace_name,
            created = self.created_at,
            updated = self.updated_at,
            priority = self.priority,
        );
        if let Some(ref s) = self.supersedes {
            let _ = writeln!(out, "Supersedes: {s}");
        }
        if let Some(ref s) = self.superseded_by {
            let _ = writeln!(out, "Superseded by: {s}");
        }
        if !self.prerequisites.is_empty() {
            let _ = writeln!(out, "Prerequisites: {}", self.prerequisites.join(", "));
        }
        if self.is_archived {
            out.push_str("Archived: yes\n");
        }
        out.push_str(&self.format_comments());
        out
    }

    /// Format comments as a `"Comments:"` block suitable for [`crate::tools::ticket::GetTicketTool`].
    ///
    /// Returns a string starting with `"Comments:"` followed by one line per
    /// comment in the format `"\n  [{role}] ({timestamp}): {content}"`, or
    /// `"Comments:\n  (no comments)"` if the comment list is empty.
    ///
    /// Timestamps are truncated to seconds (`[..19]` of the RFC 3339 string),
    /// with a defensive `min()` guard against abnormally short strings.
    #[must_use]
    fn format_comments(&self) -> String {
        let mut s = String::from("Comments:");
        if self.comments.is_empty() {
            s.push_str("\n  (no comments)");
        } else {
            for c in &self.comments {
                let end = 19.min(c.created_at.len());
                let ts = &c.created_at[..end];
                let _ = write!(s, "\n  [{}] ({}): {}", c.role, ts, c.content);
            }
        }
        s
    }
}
/// Lowercase snake_case strings matching the DB column values — no schema
/// migration needed. Display, AsRefStr, and EnumIter are derived via `strum`;
/// FromStr is implemented manually for user-friendly error messages.
#[derive(
    Debug, Clone, Copy, PartialEq, Serialize, strum::Display, strum::AsRefStr, strum::EnumIter,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TicketPhase {
    Backlog,
    Analysis,
    /// Ticket is waiting for Manager review. Not picked up automatically by any agent —
    /// the Manager or user must manually advance it to ReadyForDevelopment or cancel it.
    Planning,
    ReadyForDevelopment,
    InDevelopment,
    InDiagnostics,
    DiagnosticsDone,
    InSanitation,
    SanitationPassed,
    InReview,
    Reviewed,
    InQa,
    QaPassed,
    Done,
    Cancelled,
    Failed,
}

impl TicketPhase {
    /// Returns `true` for transitory handoff phases — pipeline-blocking
    /// phases where no agent is mid-execution.
    ///
    /// Delegates to `TRANSITORY_HANDOFF_PHASES` so the transitory handoff set can never
    /// accidentally diverge from the definition used in coverage tests.
    #[cfg(test)]
    #[must_use]
    fn is_transitory_handoff(self) -> bool {
        TRANSITORY_HANDOFF_PHASES.contains(&self)
    }

    /// Returns `true` for phases that unblock dependent tickets.
    ///
    /// Delegates to [`UNBLOCKING_PHASES`] so the unblocking set can never
    /// accidentally diverge from the prerequisite-unblocking set.
    /// [`TicketPhase::Failed`] is not in [`UNBLOCKING_PHASES`] and is
    /// therefore not unblocking — a failed ticket permanently blocks its
    /// dependents and remains visible in active views for manual triage.
    #[must_use]
    pub fn is_unblocking(&self) -> bool {
        UNBLOCKING_PHASES.contains(self)
    }

    /// Returns `true` for terminal phases (`Done`, `Cancelled`, `Failed`) — a
    /// ticket in one of these can no longer be claimed, so the rework-priority
    /// reservation must be cleared.
    ///
    /// Delegates to [`TERMINAL_PHASES`] so the terminal set is authoritative
    /// for both the transition-clearing clause and the reservation sweep.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        TERMINAL_PHASES.contains(self)
    }

    /// Returns `true` if the ticket is in a pipeline-blocking phase.
    ///
    /// Tickets in these phases are actively being worked on by agents
    /// (development, diagnostics, review, QA). Automated tools (create,
    /// update, add_comment) should refuse to modify them to prevent
    /// race conditions with running agents.
    #[must_use]
    pub fn is_pipeline_blocking(&self) -> bool {
        PIPELINE_BLOCKING_PHASES.contains(self)
    }

    /// Human-readable display label with spaces instead of underscores
    /// (e.g. `"in development"` from [`TicketPhase::InDevelopment`]).
    ///
    /// This is the presentation-oriented counterpart to `AsRefStr::as_ref`
    /// (which returns the machine-oriented `snake_case` form like
    /// `"in_development"`). Use `display_name()` for user-facing UI labels;
    /// keep `as_ref()` for tool output, SQL fragments, and agent-facing text
    /// where agents expect the snake_case phase string.
    #[must_use]
    pub fn display_name(&self) -> String {
        self.as_ref().replace('_', " ")
    }
}

/// Valid phase names, pre-computed once to avoid re-iteration in error paths.
static ALL_TICKET_PHASE_NAMES: LazyLock<String> = LazyLock::new(|| {
    <TicketPhase as strum::IntoEnumIterator>::iter()
        .map(|p| p.to_string())
        .collect::<Vec<_>>()
        .join(", ")
});

impl std::str::FromStr for TicketPhase {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Case-sensitive matching to preserve backward compatibility with
        // the previous `strum::EnumString` derive.
        <TicketPhase as strum::IntoEnumIterator>::iter()
            .find(|p| p.as_ref() == s)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Invalid phase '{s}'. Valid phases: {}",
                    *ALL_TICKET_PHASE_NAMES
                )
            })
    }
}

// Display and AsRefStr are provided by strum derives. FromStr is implemented
// manually above to produce user-friendly error messages.

/// Bundles a SQL mutation statement with its parameters and ticket id.
/// Returned by [`BoardStore::build_transition_sql`]; executed via
/// [`PreparedUpdate::execute_no_cancel`], [`PreparedUpdate::execute_tx`],
/// [`PreparedUpdate::execute_and_cancel`] or
/// [`PreparedUpdate::execute_tx_matched`].
struct PreparedUpdate {
    sql: String,
    params: Vec<turso::Value>,
    ticket_id: String,
}

impl PreparedUpdate {
    /// Execute within an existing transaction, verifying that a row was
    /// affected. Does NOT cancel registered agents — the caller manages
    /// transaction lifecycle and should cancel agents before starting the
    /// transaction when needed.
    async fn execute_tx(self, tx: &turso::TxGuard<'_>) -> Result<()> {
        let rows = tx.execute(&self.sql, self.params).await?;
        BoardStore::ensure_ticket_found(rows, &self.ticket_id)?;
        Ok(())
    }

    /// Execute the update without cancelling any agent.
    ///
    /// Use this for post-agent operations where the caller knows no agent
    /// is running and the implicit cancellation of
    /// [`execute_and_cancel`](Self::execute_and_cancel) is unnecessary.
    async fn execute_no_cancel(self, conn: &turso::Connection) -> Result<()> {
        let rows = conn.execute(&self.sql, self.params).await?;
        BoardStore::ensure_ticket_found(rows, &self.ticket_id)?;
        Ok(())
    }

    /// Execute the update, verify it affected a row, then cancel any agent
    /// registered on this ticket.
    ///
    /// This is a convenience for single-ticket mutations that follow the
    /// pattern: execute → verify → cancel stale agent.
    ///
    /// # When NOT to use
    ///
    /// Do **not** use this helper for operations where cancellation is
    /// unnecessary or has different semantics. Prefer [`execute_no_cancel`](Self::execute_no_cancel)
    /// for simple post-agent updates that do not need stale-agent cancellation.
    /// Additionally, avoid this helper for:
    /// - **`BoardStore::claim_diagnostics`** — returns `Result<bool>`, only cancels on success.
    /// - **`BoardStore::supersede_and_create`** — runs inside a transaction, cancels
    ///   before commit via a different pattern.
    /// - **`BoardStore::claim_sanitation`** — returns `Result<bool>`, does NOT cancel
    ///   (QaPassed has no running agent).
    async fn execute_and_cancel(self, conn: &turso::Connection) -> Result<()> {
        let rows = conn.execute(&self.sql, self.params).await?;
        BoardStore::ensure_ticket_found(rows, &self.ticket_id)?;
        crate::registry::AGENT_REGISTRY.cancel_by_ticket_id(&self.ticket_id);
        Ok(())
    }

    /// Execute within an existing transaction, reporting whether the CAS
    /// guard matched: `Ok(true)` when a row was updated, `Ok(false)` when no
    /// row matched — the ticket is no longer in the expected phase (moved
    /// externally) or does not exist. Follows the claim convention
    /// (guard miss = `Ok(false)`, an expected no-op), unlike the other
    /// executors which treat a no-row match as an error.
    async fn execute_tx_matched(self, tx: &turso::TxGuard<'_>) -> Result<bool> {
        let rows = tx.execute(&self.sql, self.params).await?;
        Ok(rows > 0)
    }
}

/// A single reset transition: when a ticket in `from` phase is found on startup,
/// it is rolled back to `to` phase. If `pipeline_reservation` is true, the ticket
/// gets `pipeline_reservation = 1` so it is claimed before any fresh ticket in the
/// same phase (preserving rework priority across restarts).
#[derive(Debug, Clone, Copy)]
struct ResetTransition {
    from: TicketPhase,
    to: TicketPhase,
    /// Whether to set `pipeline_reservation = 1` on the reset ticket.
    ///
    /// When `true`: the reset ticket gets priority re-dispatch — it will be
    /// claimed before any fresh ticket in the same phase.
    /// When `false`: normal queue order.
    ///
    /// See [`BoardStore::RESET_TRANSITIONS`] for the rationale behind each entry.
    pipeline_reservation: bool,
}

/// Controls whether the pipeline-occupancy check is enforced when claiming tickets.
///
/// Pipeline-blocking tickets (those in [`PIPELINE_BLOCKING_PHASES`]) prevent
/// multiple tickets from being worked concurrently in the same workspace.
///
/// - [`Skip`](Self::Skip): claim the next available ticket without checking
///   for pipeline blockers (used by parallel phases like analysis, review, QA).
/// - [`Enforce`](Self::Enforce): only claim if no pipeline-blocking ticket exists
///   in the workspace (used by serial phases like development, diagnostics, sanitation).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum PipelineCheck {
    /// Skip pipeline occupancy check — claim the next available ticket.
    Skip,
    /// Only claim if no pipeline-blocking ticket exists in the workspace.
    Enforce,
}

/// Whether to load comments when fetching tickets.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum LoadComments {
    /// Load comments alongside the ticket.
    Yes,
    /// Skip loading comments.
    No,
}

impl BoardStore {
    /// Post-open setup: create the FTS index.
    async fn after_open(&self) -> anyhow::Result<()> {
        crate::turso::ensure_fts_index(
            &self.conn,
            TICKETS_FTS_INDEX_NAME,
            "ngram",
            TICKETS_FTS_INDEX_DDL,
        )
        .await?;
        Ok(())
    }

    /// Shared INSERT logic for [`BoardStore::create_ticket`] and [`BoardStore::supersede_and_create`].
    ///
    /// The `embedding` column is write-once — stored at creation time and later
    /// read by `list_archived_with_embeddings` for vector search. It is not
    /// included in `TICKET_COLUMNS` (SELECT queries) because only the dedicated
    /// `list_archived_with_embeddings` method reads it.
    ///
    /// Computes the timestamp and serializes prerequisites internally. Does NOT
    /// commit the transaction — the caller is responsible for calling
    /// `tx.commit()` after any additional writes.
    async fn insert_ticket_tx(
        tx: &TxGuard<'_>,
        ticket_id: &str,
        params: &TicketParams,
        supersedes: Option<&str>,
    ) -> Result<()> {
        let now = turso::now();
        let prereqs_json = serde_json::to_string(&params.prerequisites)?;
        tx.execute(
            "INSERT INTO tickets (id, title, description, phase, workspace_name, \
             created_at, updated_at, prerequisites, supersedes, reporter, embedding, priority) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
            turso::params![
                ticket_id,
                params.title.as_str(),
                params.description.as_str(),
                params.phase.as_ref(),
                params.workspace_name.as_str(),
                now.as_str(),
                now.as_str(),
                prereqs_json.as_str(),
                supersedes,
                params.reporter.as_str(),
                params.embedding.as_deref(),
                params.priority,
            ],
        )
        .await?;
        Ok(())
    }

    /// Rewire dependents after supersede: tickets whose prerequisites mention
    /// `supersede_id` get updated to point to `new_id`. Queried and updated within
    /// the same transaction — no TOCTOU window between SELECT and UPDATE.
    ///
    /// Uses `json_each()` for exact prerequisite matching (consistent with
    /// [`claim_ticket_in_workspace`](Self::claim_ticket_in_workspace)).
    async fn rewire_dependents_tx(
        tx: &TxGuard<'_>,
        supersede_id: &str,
        new_id: &str,
        workspace_name: &str,
    ) -> Result<()> {
        let dep_rows = tx
            .query(
                "SELECT DISTINCT t.id, t.prerequisites \
                 FROM tickets t, json_each(t.prerequisites) AS je \
                 WHERE je.value = ?1 AND t.workspace_name = ?2",
                turso::params![supersede_id, workspace_name],
            )
            .await?;

        for row in &dep_rows {
            let dep_id: String = row.get(0)?;
            let raw: String = row.get(1)?;
            let mut prereqs: Vec<String> = parse_prereqs(&raw)
                .with_context(|| format!("Failed to parse prerequisites for ticket {dep_id}"))?;
            let mut changed = false;
            for p in &mut prereqs {
                if *p == supersede_id {
                    *p = new_id.to_string();
                    changed = true;
                }
            }
            if changed {
                let new_json = serde_json::to_string(&prereqs)?;
                tx.execute(
                    "UPDATE tickets SET prerequisites = ?1, updated_at = ?2 WHERE id = ?3",
                    turso::params![new_json, turso::now(), dep_id],
                )
                .await?;
            }
        }
        Ok(())
    }

    /// Begin a transaction, generate a ticket ID, and validate prerequisites.
    ///
    /// Performs the shared validation preamble used by both [`BoardStore::create_ticket`]
    /// and [`BoardStore::supersede_and_create`]: starts a transaction, generates a
    /// sequential ticket ID via counter upsert, checks that the new ID
    /// doesn't appear in its own prerequisites, then validates all
    /// prerequisites exist and belong to the same workspace.
    ///
    /// Callers must not call `self.conn` methods until the guard is dropped
    /// or committed — `TxGuard` holds a tokio mutex lock.
    ///
    /// # Correctness (TOCTOU)
    ///
    /// Correctness relies on both the tokio mutex inside `conn` (serializes
    /// Rust-level writes) and the SQLite transaction `tx` (provides
    /// database-level isolation) — no concurrent write can change
    /// prerequisite tickets between validation and the caller's INSERT.
    /// Validation runs inside the transaction via `tx.query()` (which
    /// uses the upstream connection through the MutexGuard, avoiding
    /// mutex deadlock with `self.conn.query()`).
    async fn begin_tx_and_validate_prerequisites(
        &self,
        workspace_name: &str,
        prerequisites: &[String],
    ) -> Result<(TxGuard<'_>, String)> {
        let tx = self.conn.begin_tx().await?;
        let seq: i64 = tx
            .query_row(
                "INSERT INTO ticket_counters (workspace_name, next_id) VALUES (?1, 1) \
                 ON CONFLICT(workspace_name) DO UPDATE SET next_id = ticket_counters.next_id + 1 \
                 RETURNING next_id - 1",
                turso::params![workspace_name],
                |row| row.get(0),
            )
            .await?;
        let id = format!("{workspace_name}-{seq}");
        anyhow::ensure!(
            !prerequisites.contains(&id),
            "Ticket cannot depend on itself: {id}"
        );
        // Validate prerequisites using the transaction's query method —
        // tx.query() uses the upstream connection through the MutexGuard
        // so it doesn't deadlock with the mutex held by TxGuard.
        Self::validate_prerequisites(&tx, prerequisites, workspace_name).await?;
        Ok((tx, id))
    }

    /// Create a new ticket at the requested phase. Returns the ticket id.
    pub(crate) async fn create_ticket(&self, params: &TicketParams) -> Result<String> {
        let (tx, id) = self
            .begin_tx_and_validate_prerequisites(&params.workspace_name, &params.prerequisites)
            .await?;

        Self::insert_ticket_tx(&tx, &id, params, None).await?;

        tx.commit().await?;
        Ok(id)
    }

    /// Create a new ticket that supersedes (replaces) an existing ticket.
    ///
    /// Atomically cancels `supersede_id`, creates the new ticket with a
    /// `supersedes` back-link, and rewires any dependent tickets' prerequisites
    /// to point to the new ID. All writes happen in a single transaction
    /// via `begin_tx()` + parameterized queries.
    ///
    /// Before commit, any running agent on the superseded ticket is cancelled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The superseded ticket does not exist
    /// - The superseded ticket is in a different workspace
    /// - A self-reference is detected (supersede ID in the new ticket's prerequisites)
    /// - Any prerequisite is invalid (doesn't exist or cross-workspace)
    pub(crate) async fn supersede_and_create(
        &self,
        supersede_id: &str,
        params: &TicketParams,
    ) -> Result<String> {
        anyhow::ensure!(
            !params.prerequisites.iter().any(|p| p == supersede_id),
            "Ticket cannot supersede and depend on the same ticket: {supersede_id}"
        );

        let (tx, new_id) = self
            .begin_tx_and_validate_prerequisites(&params.workspace_name, &params.prerequisites)
            .await?;

        // Verify the superseded ticket exists and belongs to the same workspace.
        // This runs INSIDE the transaction (tx.query() uses the upstream
        // connection through the MutexGuard) to eliminate the TOCTOU race
        // between validation and cancellation.
        let rows = tx
            .query(
                "SELECT workspace_name FROM tickets WHERE id = ?1",
                turso::params![supersede_id],
            )
            .await?;
        let row = rows
            .into_iter()
            .next()
            .ok_or_else(|| anyhow::anyhow!("Superseded ticket not found: {supersede_id}"))?;
        let old_ws: String = row.get(0)?;
        anyhow::ensure!(
            old_ws == params.workspace_name,
            "Superseded ticket {supersede_id} belongs to workspace '{old_ws}', \
             not the current workspace '{}'. \
             Cross-workspace supersede is not allowed.",
            params.workspace_name,
        );

        let now = turso::now();
        let cancelled_rows = tx
            .execute(
                "UPDATE tickets SET phase = ?1, updated_at = ?2, assigned_to = NULL, \
                 superseded_by = ?4, is_archived = 1, done_at = NULL, pipeline_reservation = 0 \
                 WHERE id = ?3",
                turso::params![
                    TicketPhase::Cancelled.as_ref(),
                    now,
                    supersede_id,
                    new_id.as_str(),
                ],
            )
            .await?;
        Self::ensure_ticket_found(cancelled_rows, supersede_id)?;

        Self::insert_ticket_tx(&tx, &new_id, params, Some(supersede_id)).await?;

        Self::rewire_dependents_tx(&tx, supersede_id, &new_id, &params.workspace_name).await?;

        // Cancel agents on the superseded ticket BEFORE the transaction commits.
        // If the process crashes between commit and cancellation, the superseded
        // ticket is Cancelled in the database but its agents remain registered and
        // keep running (orphaned agents on a cancelled ticket). Cancelling first
        // flips the trade-off: if the commit subsequently fails, agents were
        // cancelled unnecessarily but will be re-registered on re-dispatch.
        crate::registry::AGENT_REGISTRY.cancel_by_ticket_id(supersede_id);

        // No ticket_buffer push for the cancellation: supersede is only reachable
        // through agent tools (Manager or Maintainer CreateTicketTool) and agent
        // actions are intentionally silent — the GUI board path is the user
        // surface that notifies the Manager.
        tx.commit().await?;

        Ok(new_id)
    }

    /// Build a [`Ticket`] from a row returned by a
    /// [`TICKET_COLUMNS`] SELECT, optionally including its comments.
    async fn ticket_from_row(
        &self,
        row: &turso::Row,
        load_comments: LoadComments,
    ) -> Result<Ticket> {
        let id: String = row.get(COL_TICKET_ID)?;
        let comments = if load_comments == LoadComments::Yes {
            self.get_comments(&id).await?
        } else {
            Vec::new()
        };
        let prerequisites_raw: String = row.get(COL_TICKET_PREREQUISITES)?;
        let prerequisites = parse_prereqs(&prerequisites_raw)
            .with_context(|| format!("Failed to parse prerequisites for ticket {id}"))?;
        Ok(Ticket {
            id,
            title: row.get(COL_TICKET_TITLE)?,
            description: row.get(COL_TICKET_DESCRIPTION)?,
            phase: row
                .get::<String>(COL_TICKET_PHASE)?
                .parse::<TicketPhase>()?,
            assigned_to: row.get(COL_TICKET_ASSIGNED_TO)?,
            workspace_name: row.get(COL_TICKET_WORKSPACE_NAME)?,
            created_at: row.get(COL_TICKET_CREATED_AT)?,
            updated_at: row.get(COL_TICKET_UPDATED_AT)?,
            comments,
            prerequisites,
            supersedes: row.get(COL_TICKET_SUPERSEDES)?,
            superseded_by: row.get(COL_TICKET_SUPERSEDED_BY)?,
            commit_hash: row.get(COL_TICKET_COMMIT_HASH)?,
            lines_added: row.get(COL_TICKET_LINES_ADDED)?,
            lines_removed: row.get(COL_TICKET_LINES_REMOVED)?,
            reporter: row.get::<String>(COL_TICKET_REPORTER)?,
            is_archived: row.get::<bool>(COL_TICKET_IS_ARCHIVED)?,
            pipeline_reservation: row.get::<bool>(COL_TICKET_PIPELINE_RESERVATION)?,
            priority: row.get::<i64>(COL_TICKET_PRIORITY)?,
            reviewed_head: row.get(COL_TICKET_REVIEWED_HEAD)?,
            reviewed_tree: row.get(COL_TICKET_REVIEWED_TREE)?,
            done_at: row.get(COL_TICKET_DONE_AT)?,
            bounce_count: row.get(COL_TICKET_BOUNCE_COUNT)?,
        })
    }

    /// Grace window for Backlog→Analysis claims: tickets younger than this are
    /// not claimed into Analysis. Gives the Manager ~5s after create_ticket to
    /// move the ticket straight to Planning/ReadyForDevelopment — claiming it
    /// into Analysis within the window would spawn analysts that immediately
    /// get cancelled (plus a spurious phase-change notification).
    pub(crate) const BACKLOG_CLAIM_GRACE: Duration = Duration::seconds(5);

    /// Claim a ticket scoped to a single workspace and transition it to
    /// `target_phase`. Always filters by `workspace_name` so only tickets from
    /// that workspace are eligible.
    ///
    /// Only tickets currently in `current_phase` are eligible for claiming.
    /// The WHERE clause includes `t1.phase = ?` bound to `current_phase`,
    /// providing CAS-style atomicity for phase transitions — if no ticket
    /// matches the current phase, the claim returns `None`.
    ///
    /// When `claim_grace` is `Some(duration)`, tickets created within that
    /// duration before the claim are excluded from the candidate set via a SQL
    /// `created_at <=` cutoff — they stay in `current_phase` until the window
    /// elapses. The Backlog→Analysis claim passes [`BACKLOG_CLAIM_GRACE`] so
    /// freshly created tickets are not immediately picked up; all other claims
    /// pass `None` and are unaffected.
    ///
    /// When `pipeline_check` is [`PipelineCheck::Enforce`], the claim is rejected
    /// (returns `None`) if any pipeline-blocking ticket exists in the same workspace. The
    /// occupancy check is part of the same atomic SQL UPDATE statement (no
    /// separate SELECT + UPDATE window). Pipeline-blocking phases are defined
    /// in [`PIPELINE_BLOCKING_PHASES`].
    ///
    /// Note that a reserved ReadyForDevelopment ticket (one with
    /// `pipeline_reservation = 1`) is **not** treated as a pipeline blocker for
    /// the purpose of this claim — [`has_pipeline_blocker_for_workspace`] (a
    /// test-only query) considers such tickets blockers, but the claim subquery
    /// orders by `pipeline_reservation DESC` and clears reservation on claim,
    /// so a reserved ticket at ReadyForDevelopment will be claimed before any
    /// other ticket at the same phase — no pipeline blocking needed.
    ///
    /// When `pipeline_check` is [`PipelineCheck::Skip`], the claim uses a
    /// simple LIMIT 1 subquery with no pipeline gating. This is used for phases
    /// that should not be blocked by in-flight pipeline tickets (e.g., analysis,
    /// review, and QA).
    ///
    /// The subquery orders by `pipeline_reservation DESC, priority ASC, created_at ASC` so that
    /// tickets bounced back for rework (reservation = 1) are claimed
    /// before fresh tickets at the same phase. Among tickets with equal reservation,
    /// tickets with lower priority (higher urgency) are claimed first, then the oldest ticket
    /// (earliest created_at) is claimed first.
    ///
    /// Note: the UPDATE sets `assigned_to = NULL` and `pipeline_reservation = 0` —
    /// this intentionally drops the previous claimant and clears any pipeline
    /// reservation so the cleared slot is available for other tickets.
    /// Callers that require agent-level assignment
    /// (single-owner dispatches like the Engineer) should call
    /// [`set_assigned_to_no_cancel`](Self::set_assigned_to_no_cancel) after claiming. Parallel-agent
    /// dispatches (analysts, verifiers) intentionally leave `assigned_to` NULL.
    pub(crate) async fn claim_ticket_in_workspace(
        &self,
        current_phase: TicketPhase,
        target_phase: TicketPhase,
        workspace_name: &str,
        pipeline_check: PipelineCheck,
        claim_grace: Option<Duration>,
    ) -> Result<Option<Ticket>> {
        let now = turso::now();

        // Filter that excludes tickets with unmet prerequisites.
        let prereq_filter = format!(
            "AND NOT EXISTS ( \
               SELECT 1 FROM json_each(t1.prerequisites) AS je \
               JOIN tickets t_pre ON t_pre.id = je.value \
               WHERE t_pre.phase NOT IN ({}) \
             )",
            phase_list_sql_fragment(UNBLOCKING_PHASES),
        );

        let pipeline_blocker_clause = if pipeline_check == PipelineCheck::Enforce {
            let blocker_sql = phase_list_sql_fragment(PIPELINE_BLOCKING_PHASES);
            format!(
                "AND NOT EXISTS (SELECT 1 FROM tickets t2 \
                 WHERE t2.workspace_name = t1.workspace_name \
                 AND t2.phase IN ({blocker_sql}) \
                 AND t2.id != t1.id) "
            )
        } else {
            String::new()
        };

        // Candidate-set age cutoff: excludes tickets created within the grace
        // window so fresh tickets stay in `current_phase` a bit longer.
        let grace_clause = if claim_grace.is_some() {
            "AND t1.created_at <= ?5 "
        } else {
            ""
        };

        let sql = format!(
            "UPDATE tickets SET phase = ?1, assigned_to = NULL, updated_at = ?2, \
             pipeline_reservation = 0 \
             WHERE id = (SELECT t1.id FROM tickets t1 \
             WHERE t1.phase = ?3 AND t1.assigned_to IS NULL AND t1.workspace_name = ?4 \
             AND t1.is_archived = 0 \
             {grace_clause}{pipeline_blocker_clause}{prereq_filter} \
             ORDER BY t1.pipeline_reservation DESC, t1.priority ASC, t1.created_at ASC LIMIT 1) \
             RETURNING {TICKET_COLUMNS}"
        );

        let mut params: Vec<Value> = vec![
            Value::from(target_phase.as_ref()),
            Value::from(now),
            Value::from(current_phase.as_ref()),
            Value::from(workspace_name),
        ];
        if let Some(grace) = claim_grace {
            params.push(Value::from((Utc::now() - grace).to_rfc3339()));
        }

        let rows = self.conn.query(&sql, params).await?;
        match rows.into_iter().next() {
            Some(row) => Ok(Some(self.ticket_from_row(&row, LoadComments::Yes).await?)),
            None => Ok(None),
        }
    }

    /// Select tickets matching a SQL suffix (everything after `FROM tickets`),
    /// parsing each row via [`ticket_from_row`](Self::ticket_from_row).
    ///
    /// This is the shared building block for all `SELECT {TICKET_COLUMNS}` queries.
    /// Accepts the full suffix — typically starting with `WHERE` and optionally
    /// including `ORDER BY`, `LIMIT`, etc. — and forwards `params` directly to
    /// the underlying query so callers can use `turso::params![]` without conversions.
    pub(crate) async fn select_tickets(
        &self,
        suffix: &str,
        params: impl IntoParams + Send + 'static,
        load_comments: LoadComments,
    ) -> Result<Vec<Ticket>> {
        let sql = format!("SELECT {TICKET_COLUMNS} FROM tickets {suffix}");
        let rows = self.conn.query(&sql, params).await?;
        let mut tickets = Vec::with_capacity(rows.len());
        for row in rows {
            tickets.push(self.ticket_from_row(&row, load_comments).await?);
        }
        Ok(tickets)
    }

    /// Get a ticket by id, loading its comments.
    pub async fn get_ticket(&self, ticket_id: &str) -> Result<Option<Ticket>> {
        Ok(self
            .select_tickets(
                "WHERE id = ?1",
                turso::params![ticket_id],
                LoadComments::Yes,
            )
            .await?
            .into_iter()
            .next())
    }

    /// Fetch multiple tickets by their IDs.
    ///
    /// Returns an empty vec if `ids` is empty (no SQL round-trip).
    /// Tickets are returned in **arbitrary order** — callers that need to
    /// preserve input ordering must re-sort after receiving the result.
    pub(crate) async fn get_tickets_by_ids(
        &self,
        ids: &[String],
        load_comments: LoadComments,
    ) -> Result<Vec<Ticket>> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }
        let (suffix, params) = Self::in_clause_for_ids(ids);
        self.select_tickets(&suffix, params, load_comments).await
    }

    /// Build a `WHERE id IN (?, ?, ...)` suffix and parameter vector from
    /// ticket IDs.
    ///
    /// Callers must ensure `ids` is non-empty — the resulting SQL is invalid
    /// (syntax error from SQLite) when the list is empty.
    fn in_clause_for_ids(ids: &[String]) -> (String, Vec<Value>) {
        let suffix = format!("WHERE id IN ({})", turso::sql_in_placeholders(ids.len()));
        let params: Vec<Value> = ids.iter().map(|id| Value::Text(id.clone())).collect();
        (suffix, params)
    }

    /// Get a ticket's phase by id — lightweight, no comments loaded.
    pub async fn get_ticket_phase(&self, ticket_id: &str) -> Result<Option<TicketPhase>> {
        self.conn
            .query_optional(
                "SELECT phase FROM tickets WHERE id = ?1",
                turso::params![ticket_id],
                |row| {
                    let phase: String = row.get(0)?;
                    phase.parse()
                },
            )
            .await
    }

    /// Get a ticket's priority by id — lightweight, no comments loaded.
    ///
    /// Used by the priority-inheritance path in `CreateTicketTool::execute` to
    /// read the superseded ticket's priority without loading comments. Priority
    /// is immutable after ticket creation, so this single-column read outside
    /// the supersede transaction is safe — there is no TOCTOU race with the
    /// supersede transaction's own SELECT for existence/workspace/phase checks.
    pub(crate) async fn get_ticket_priority(&self, ticket_id: &str) -> Result<Option<i64>> {
        let sql = "SELECT priority FROM tickets WHERE id = ?1";
        self.conn
            .query_optional(sql, turso::params![ticket_id], |row| row.get::<i64>(0))
            .await
    }

    /// Build a [`PreparedUpdate`] for an `UPDATE tickets` statement, appending
    /// `updated_at = ?` and `WHERE id = ?` as the last two parameters.
    ///
    /// Callers provide the SET-clause-specific columns (without `updated_at` or
    /// `WHERE`) together with their parameter values.  The helper appends the
    /// current timestamp and the ticket id as the final parameters, keeping the
    /// parameter ordering consistent across all `UPDATE tickets` producers.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let prep = Self::build_ticket_update_with_updated_at(
    ///     "assigned_to = ?",
    ///     vec![Value::from("user-123")],
    ///     "ticket-456",
    /// );
    /// // SQL:  "UPDATE tickets SET assigned_to = ?, updated_at = ? WHERE id = ?"
    /// // params: [user-123, now, ticket-456]
    /// ```
    fn build_ticket_update_with_updated_at(
        set_clause: &str,
        set_params: Vec<turso::Value>,
        ticket_id: &str,
    ) -> PreparedUpdate {
        let now = turso::now();
        let sql = format!("UPDATE tickets SET {set_clause}, updated_at = ? WHERE id = ?");
        let mut params = set_params;
        params.push(Value::from(now));
        params.push(Value::from(ticket_id));
        PreparedUpdate {
            sql,
            params,
            ticket_id: ticket_id.to_string(),
        }
    }

    /// Build the SQL, params, and action description for a ticket phase
    /// transition. Shared by [`transition_to`](Self::transition_to) and
    /// [`transition_to_tx`](Self::transition_to_tx).
    ///
    /// Note: this does **not** use [`Self::build_ticket_update_with_updated_at`]
    /// because it has extra SET columns (`assigned_to = NULL`,
    /// `pipeline_reservation = COALESCE(?5, pipeline_reservation)`,
    /// `done_at = CASE ...`) and an
    /// additional WHERE condition (`AND (?4 IS NULL OR phase = ?4)`) that
    /// don't fit the helper's fixed pattern.
    ///
    /// `done_at` is set to `?2` (now) when the target is `done` — overwriting
    /// on re-completion — and cleared when the ticket leaves `done`, so the
    /// column holds a timestamp iff the ticket is currently in the Done phase.
    /// Later non-transition activity (comments, archive) never touches it.
    ///
    /// Terminal targets ([`TicketPhase::is_terminal`]) always clear
    /// `pipeline_reservation` regardless of `reservation`: a ticket that can
    /// no longer be claimed must not keep a stale rework-priority flag.
    fn build_transition_sql(
        ticket_id: &str,
        expected_phase: Option<TicketPhase>,
        target_phase: TicketPhase,
        reservation: Option<bool>,
    ) -> PreparedUpdate {
        let now = turso::now();
        let guard: Option<&str> = expected_phase.as_ref().map(TicketPhase::as_ref);
        let reservation = if target_phase.is_terminal() {
            Some(false)
        } else {
            reservation
        };
        let sql = "UPDATE tickets SET phase = ?1, assigned_to = NULL, updated_at = ?2, \
                    pipeline_reservation = COALESCE(?5, pipeline_reservation), \
                    done_at = CASE WHEN ?1 = 'done' THEN ?2 \
                                   WHEN phase = 'done' THEN NULL \
                                   ELSE done_at END \
                    WHERE id = ?3 AND (?4 IS NULL OR phase = ?4)";
        let params: Vec<turso::Value> = vec![
            Value::from(target_phase.as_ref()),
            Value::from(now),
            Value::from(ticket_id),
            Value::from(guard),
            Value::from(reservation),
        ];
        PreparedUpdate {
            sql: sql.to_string(),
            params,
            ticket_id: ticket_id.to_string(),
        }
    }

    /// Update ticket phase, optionally guarded by an expected phase for CAS-style
    /// atomicity. Always clears `assigned_to` and cancels running agents.
    ///
    /// # Note on [`pipeline_reservation`](Ticket::pipeline_reservation)
    ///
    /// When `reservation` is `None`, the column is left untouched so bounce-back
    /// transitions can set it atomically, and manual transitions leave stale
    /// reservations inert (claim/blocker queries filter by phase). When
    /// `Some(value)`, it's set in the same UPDATE to avoid a race on crash/restart
    /// recovery or rework priority. Terminal targets
    /// ([`TicketPhase::is_terminal`]) always clear the flag — see
    /// [`build_transition_sql`](Self::build_transition_sql).
    ///
    /// # Errors
    ///
    /// Returns an error when the UPDATE matched 0 rows or a database error occurs.
    pub async fn transition_to(
        &self,
        ticket_id: &str,
        expected_phase: Option<TicketPhase>,
        target_phase: TicketPhase,
        reservation: Option<bool>,
    ) -> Result<()> {
        let prepared =
            Self::build_transition_sql(ticket_id, expected_phase, target_phase, reservation);
        prepared.execute_and_cancel(&self.conn).await
    }

    /// Transactional variant of [`transition_to`](Self::transition_to) —
    /// uses an existing transaction instead of `self.conn.execute()`.
    /// Does NOT cancel registered agents — the caller is responsible for
    /// cancelling agents **before** beginning the transaction (or at least
    /// before `tx.commit()`) to avoid orphaned agents on crash.
    ///
    /// # Return value
    ///
    /// Returns `Ok(true)` when the CAS guard matched and the row was
    /// updated; `Ok(false)` when no row matched — the ticket is no longer in
    /// the expected phase (moved externally while the stage finished) or does
    /// not exist. The guard miss follows the board layer's claim convention
    /// (expected no-op, not an error), unlike
    /// [`transition_to`](Self::transition_to) whose callers perform
    /// user-initiated actions on a ticket that must exist.
    pub(crate) async fn transition_to_tx(
        tx: &TxGuard<'_>,
        ticket_id: &str,
        expected_phase: Option<TicketPhase>,
        target_phase: TicketPhase,
        reservation: Option<bool>,
    ) -> Result<bool> {
        let prepared =
            Self::build_transition_sql(ticket_id, expected_phase, target_phase, reservation);
        prepared.execute_tx_matched(tx).await
    }

    /// Verify that a mutation query affected at least one row, returning an
    /// error with a descriptive message if the ticket was not found.
    fn ensure_ticket_found(rows: u64, ticket_id: &str) -> Result<()> {
        anyhow::ensure!(rows > 0, "Ticket {ticket_id} not found");
        Ok(())
    }

    /// Set or clear the assignee for a ticket **without** cancelling any running
    /// agent.
    ///
    /// When `assigned_to` is `Some(value)`, sets the `assigned_to` column to that
    /// value. When `None`, clears the assignee (sets `assigned_to = NULL`).
    ///
    /// This is the safe choice for parallel agent phases (analysis, review, QA)
    /// where multiple agents are registered and should NOT be cancelled by the
    /// assignment update, and for all post-agent cleanup (no agent is running,
    /// so the cancellation side-effect would be misleading).
    pub async fn set_assigned_to_no_cancel(
        &self,
        ticket_id: &str,
        assigned_to: Option<&str>,
    ) -> Result<()> {
        let prepared = Self::build_ticket_update_with_updated_at(
            "assigned_to = ?",
            vec![Value::from(assigned_to)],
            ticket_id,
        );
        prepared.execute_no_cancel(&self.conn).await
    }

    /// Transactional variant of `set_assigned_to_no_cancel` —
    /// uses an existing transaction instead of opening its own.
    /// Does NOT cancel registered agents — the caller is responsible
    /// for cancelling stale agents **before** beginning the transaction
    /// when a cancel is needed (e.g., via `AGENT_REGISTRY.cancel_by_ticket_id`).
    /// This is safe for post-agent operations (e.g., clearing assignment
    /// after an agent has already finished) where no cancel is needed.
    pub(crate) async fn set_assigned_to_tx(
        tx: &TxGuard<'_>,
        ticket_id: &str,
        assigned_to: Option<&str>,
    ) -> Result<()> {
        let prepared = Self::build_ticket_update_with_updated_at(
            "assigned_to = ?",
            vec![Value::from(assigned_to)],
            ticket_id,
        );
        prepared.execute_tx(tx).await
    }

    /// Atomically claim a ticket for diagnostics execution.
    ///
    /// Sets `assigned_to` to the caller-provided value, only when the ticket
    /// is unassigned AND still in [`TicketPhase::InDiagnostics`] — a single
    /// atomic SQL guard that prevents the TOCTOU race between the poll
    /// listing pre-filter and the subsequent claim. The assignee set and phase
    /// check are fused into one UPDATE; callers do not need a separate
    /// assignment after claiming.
    ///
    /// Returns `Ok(true)` if a row was updated (claim succeeded), `Ok(false)`
    /// if no row matched (already claimed by another dispatch or ticket moved
    /// out of [`TicketPhase::InDiagnostics`]). On a successful claim, cancels
    /// any agent registered on this ticket as a safety-in-depth measure against
    /// stale dispatches.
    pub async fn claim_diagnostics(&self, ticket_id: &str, assigned_to: &str) -> Result<bool> {
        let now = turso::now();
        let rows = self
            .conn
            .execute(
                "UPDATE tickets \
                 SET assigned_to = ?1, updated_at = ?2 \
                 WHERE id = ?3 \
                 AND assigned_to IS NULL \
                 AND phase = ?4 \
                 AND is_archived = 0",
                turso::params![
                    assigned_to,
                    now,
                    ticket_id,
                    TicketPhase::InDiagnostics.as_ref()
                ],
            )
            .await?;

        if rows > 0 {
            crate::registry::AGENT_REGISTRY.cancel_by_ticket_id(ticket_id);
        }

        Ok(rows > 0)
    }

    /// Claim a QaPassed ticket for sanitation processing.
    ///
    /// Atomically transitions the ticket from [`TicketPhase::QaPassed`] to
    /// [`TicketPhase::InSanitation`], sets `assigned_to` to the caller-provided
    /// value, and enforces the per-workspace serialization invariant: only one
    /// ticket at a time may be in `SANITATION_PIPELINE_PHASES`.
    ///
    /// Returns `Ok(true)` if the claim succeeded, `Ok(false)` if:
    /// - The ticket is no longer in QaPassed (already claimed by another handler), or
    /// - Another ticket is already in the sanitation pipeline for this workspace.
    ///
    /// Unlike [`transition_to`](Self::transition_to), this method does NOT
    /// cancel registered agents — QaPassed is a transitory handoff phase
    /// with no running agent, so cancellation is unnecessary.
    pub async fn claim_sanitation(&self, ticket_id: &str, assigned_to: &str) -> Result<bool> {
        let now = turso::now();
        let blocker = phase_list_sql_fragment(SANITATION_PIPELINE_PHASES);
        let sql = format!(
            "UPDATE tickets SET phase = ?1, assigned_to = ?2, updated_at = ?3 \
             WHERE id = ?4 AND phase = ?5 AND is_archived = 0 \
             AND NOT EXISTS (SELECT 1 FROM tickets t2 \
               WHERE t2.workspace_name = \
                 (SELECT workspace_name FROM tickets WHERE id = ?4) \
               AND t2.id != ?4 \
               AND t2.phase IN ({blocker}))"
        );
        let rows = self
            .conn
            .execute(
                &sql,
                turso::params![
                    TicketPhase::InSanitation.as_ref(),
                    assigned_to,
                    now,
                    ticket_id,
                    TicketPhase::QaPassed.as_ref(),
                ],
            )
            .await?;
        Ok(rows > 0)
    }

    /// Record commit metadata on a ticket using an existing transaction.
    /// Does NOT commit or rollback the transaction; the caller controls that.
    pub(crate) async fn set_commit_info_tx(
        tx: &TxGuard<'_>,
        ticket_id: &str,
        hash: &str,
        lines_added: i64,
        lines_removed: i64,
    ) -> Result<()> {
        debug_assert!(
            lines_added >= 0,
            "lines_added must be non-negative: {lines_added}"
        );
        debug_assert!(
            lines_removed >= 0,
            "lines_removed must be non-negative: {lines_removed}"
        );
        // Build the SQL and params for setting commit info.
        let prepared = Self::build_ticket_update_with_updated_at(
            "commit_hash = ?, lines_added = ?, lines_removed = ?",
            vec![
                Value::from(hash),
                Value::from(lines_added),
                Value::from(lines_removed),
            ],
            ticket_id,
        );
        prepared.execute_tx(tx).await
    }

    /// Record the reviewed content base (HEAD + index tree) on a ticket.
    ///
    /// Set after a completed reviewer round so later rounds can skip the
    /// reviewer pass only when their content is identical to this base.
    /// `None` values clear the base (ticket becomes never-reviewed).
    pub(crate) async fn set_reviewed_base(
        &self,
        ticket_id: &str,
        head: Option<&str>,
        tree: Option<&str>,
    ) -> Result<()> {
        let prepared = Self::build_ticket_update_with_updated_at(
            "reviewed_head = ?, reviewed_tree = ?",
            vec![Value::from(head), Value::from(tree)],
            ticket_id,
        );
        prepared.execute_no_cancel(&self.conn).await
    }

    /// Increment the ticket's bounce counter inside an existing transaction.
    ///
    /// Called atomically with the bounce-back transition (review/QA bounce or
    /// engineer hard failure) so the counter can never drift from the
    /// transitions that produce it.
    pub(crate) async fn increment_bounce_count_tx(
        tx: &TxGuard<'_>,
        ticket_id: &str,
    ) -> Result<i64> {
        let rows = tx
            .query(
                "UPDATE tickets SET bounce_count = bounce_count + 1, updated_at = ?1 \
                 WHERE id = ?2 RETURNING bounce_count",
                turso::params![turso::now(), ticket_id],
            )
            .await
            .map_err(anyhow::Error::from)?;
        match rows.into_iter().next() {
            Some(row) => row.get::<i64>(0).map_err(anyhow::Error::from),
            None => Err(anyhow::anyhow!(
                "ticket {ticket_id} not found — bounce counter not incremented"
            )),
        }
    }

    /// Manual "Redo Dev" bounce-back: transition a Reviewed ticket back to
    /// ReadyForDevelopment and increment its bounce counter atomically, so
    /// manual bounce-backs consume the same breaker budget as pipeline
    /// bounce-backs. Sets `pipeline_reservation` for
    /// rework priority (matching pipeline bounce-backs). Cancels any
    /// registered agent only after the transition succeeds — a CAS
    /// guard miss (ticket moved externally) must not cancel a just-claimed
    /// agent.
    ///
    /// # Return value
    ///
    /// Returns `Ok(true)` when the bounce-back committed and `Ok(false)`
    /// when the guard missed (the ticket is no longer in
    /// [`TicketPhase::Reviewed`]) — the expected, silent no-op for a ticket
    /// that was moved externally while the user was clicking. Follows the
    /// board layer's claim convention (guard miss = `Ok(false)`).
    pub(crate) async fn bounce_back_to_dev(&self, ticket_id: &str) -> Result<bool> {
        let applied = crate::turso::with_tx_outcome(
            &self.conn,
            ticket_id,
            "bounce back to dev",
            async |tx| {
                if Self::transition_to_tx(
                    tx,
                    ticket_id,
                    Some(TicketPhase::Reviewed),
                    TicketPhase::ReadyForDevelopment,
                    Some(true),
                )
                .await?
                {
                    Self::increment_bounce_count_tx(tx, ticket_id).await?;
                    Ok(true)
                } else {
                    Ok(false)
                }
            },
        )
        .await?;
        if applied {
            crate::registry::AGENT_REGISTRY.cancel_by_ticket_id(ticket_id);
        }
        Ok(applied)
    }

    /// Transition pairs for crash/restart recovery (extracted so tests can verify
    /// coverage against [`PIPELINE_BLOCKING_PHASES`] without duplicating the pairs).
    ///
    /// Each entry maps a phase where an agent may have crashed mid-work back to the
    /// phase the ticket should resume in. Must be kept in sync with
    /// [`PIPELINE_BLOCKING_PHASES`] — see `tests::test_pipeline_blockers_coverage`.
    ///
    /// Asymmetry: `Analysis → Backlog` is included (backlog analysts may crash mid-analysis),
    /// but `Analysis` is intentionally NOT in [`PIPELINE_BLOCKING_PHASES`] (it's a pre-flight
    /// phase, not a pipeline blocker).
    ///
    /// Transitory handoff phases (DiagnosticsDone, SanitationPassed, Reviewed, QaPassed) are pipeline
    /// blocking but don't need a reset entry — the poller picks them up within seconds
    /// of restart, so no agent session is mid-execution in those states.
    ///
    /// `pipeline_reservation` choice per entry:
    /// - `true`: expensive production-side phases (development, diagnostics, sanitation)
    ///   — losing queue position wastes significant work, so reset tickets get priority.
    /// - `false`: lighter inspection phases (analysis, review, QA) — re-queuing is cheap,
    ///   so normal queue order is fine.
    const RESET_TRANSITIONS: &[ResetTransition] = &[
        ResetTransition {
            from: TicketPhase::InDevelopment,
            to: TicketPhase::ReadyForDevelopment,
            pipeline_reservation: true,
        },
        ResetTransition {
            from: TicketPhase::InDiagnostics,
            to: TicketPhase::ReadyForDevelopment,
            pipeline_reservation: true,
        },
        ResetTransition {
            from: TicketPhase::InSanitation,
            to: TicketPhase::QaPassed,
            pipeline_reservation: true,
            // Note: pipeline_reservation = true on InSanitation → QaPassed is inert —
            // QaPassed uses list-based dispatch (spawn_for_each_ticket_in_phase), not the
            // claim loop where pipeline_reservation provides ordering. Set `true` to match
            // the production-side convention (sanitation is substantive work, like
            // development and diagnostics); the flag is harmless for list-based dispatch.
        },
        ResetTransition {
            from: TicketPhase::InQa,
            to: TicketPhase::Reviewed,
            pipeline_reservation: false,
        },
        ResetTransition {
            from: TicketPhase::InReview,
            to: TicketPhase::DiagnosticsDone,
            pipeline_reservation: false,
        },
        ResetTransition {
            from: TicketPhase::Analysis,
            to: TicketPhase::Backlog,
            pipeline_reservation: false,
        },
    ];
    /// Lookup a reset transition by `from` phase. Shared by the boot reset and
    /// the stale-purge rollback in jobs.rs so both paths use one table.
    pub(crate) fn reset_transition(from: TicketPhase) -> Option<(TicketPhase, bool)> {
        Self::RESET_TRANSITIONS
            .iter()
            .find(|t| t.from == from)
            .map(|t| (t.to, t.pipeline_reservation))
    }
    /// SET clause shared by the boot reset ([`Self::reset_inflight_tickets`])
    /// and the stale-purge rollback in jobs.rs: phase + assignee clear +
    /// updated_at + pipeline reservation.
    ///
    /// Parameter slots: `?1` = target phase, `?2` = now, `?4` =
    /// pipeline_reservation (`?3`/`?5` are WHERE-bound at the call sites —
    /// board.rs binds `?3` = source phase; jobs.rs binds `?3` = ticket id and
    /// `?5` = source phase).
    ///
    /// Interpolated via `format!` at both call sites — must never contain a
    /// literal `{` or `}`.
    pub(crate) const RESET_TICKET_SET_CLAUSE: &str =
        "phase = ?1, assigned_to = NULL, updated_at = ?2, pipeline_reservation = ?4";
    /// Reset all in-flight tickets to their ready state (for crash/restart recovery).
    ///
    /// Resets:
    /// - 5 of the 9 `PIPELINE_BLOCKING_PHASES` where agents may have been mid-work
    ///   (InDevelopment, InDiagnostics, InSanitation, InReview, InQa) — roll back to
    ///   their pre-pipeline state
    /// - `Analysis` (not a pipeline blocker, but backlog analysts may crash mid-work)
    ///
    /// Tickets that are bounced to `ReadyForDevelopment` (InDevelopment and InDiagnostics)
    /// get `pipeline_reservation = 1` so they are claimed before any fresh
    /// `ReadyForDevelopment` ticket — this preserves the rework priority across restarts.
    ///
    /// Excludes DiagnosticsDone, SanitationPassed, Reviewed, and QaPassed — these are transitory handoff states
    /// that the poller picks up within the next poll cycle.
    ///
    /// Uses `Self::RESET_TRANSITIONS` (extracted as an associated const so tests
    /// can verify coverage against `PIPELINE_BLOCKING_PHASES`).
    ///
    /// `exclude_ticket_ids`: tickets with a RESUMED active job at boot must be
    /// skipped — resetting them to a claimable phase would re-claim via the 1s
    /// poll loop while the resumed agent runs (duplicate work/double LLM
    /// cost/conflicting verdicts). An empty exclusion omits the clause.
    pub async fn reset_inflight_tickets(&self, exclude_ticket_ids: &[String]) -> Result<()> {
        let tx = self.conn.begin_tx().await?;
        let now = turso::now();
        for transition in Self::RESET_TRANSITIONS {
            let mut values: Vec<turso::Value> = vec![
                turso::Value::Text(transition.to.as_ref().to_string()),
                turso::Value::Text(now.clone()),
                turso::Value::Text(transition.from.as_ref().to_string()),
                turso::Value::Integer(i64::from(transition.pipeline_reservation)),
            ];
            let clause = if exclude_ticket_ids.is_empty() {
                String::new()
            } else {
                // `IN ()` is invalid SQL — the empty exclusion omits the clause.
                values.extend(
                    exclude_ticket_ids
                        .iter()
                        .map(|s| turso::Value::Text(s.clone())),
                );
                format!(
                    " AND id NOT IN ({})",
                    turso::sql_in_placeholders(exclude_ticket_ids.len())
                )
            };
            let sql = format!(
                "UPDATE tickets SET {} WHERE phase = ?3{clause}",
                Self::RESET_TICKET_SET_CLAUSE
            );
            tx.execute(&sql, values).await?;
        }
        tx.commit().await?;
        Ok(())
    }

    /// Shared implementation for checking if a workspace has active tickets.
    ///
    /// Returns `true` if any ticket in the workspace has a pipeline-blocking
    /// phase ([`PIPELINE_BLOCKING_PHASES`]), or a
    /// [`ReadyForDevelopment`](TicketPhase::ReadyForDevelopment) ticket,
    /// optionally excluding a specific ticket ID.
    ///
    /// [`has_active_tickets_excluding`] delegates to this helper. The test-only
    /// [`has_pipeline_blocker_for_workspace`] delegates too, with
    /// `require_rfd_reservation = true`.
    ///
    /// # Parameters
    ///
    /// * `workspace_name` — The workspace to check.
    /// * `exclude_ticket_id` — When `Some(id)`, that ticket is excluded from
    ///   the check. When `None`, no exclusion is applied (the SQL clause
    ///   `(?2 IS NULL OR id != ?2)` short-circuits to `TRUE`).
    /// * `require_rfd_reservation` — When `true`, only ReadyForDevelopment
    ///   tickets with `pipeline_reservation = 1` are counted as active (used
    ///   by the pipeline-blocker check). When `false`, all ReadyForDevelopment
    ///   tickets are active regardless of reservation (notification-suppression
    ///   policy for [`has_active_tickets_excluding`]).
    ///
    /// Excludes archived tickets — the only phases that ever get archived are
    /// `Done` and `Cancelled`, neither of which appears in
    /// `PIPELINE_BLOCKING_PHASES`, so this is a defensive consistency measure.
    ///
    /// # Parameter binding note
    ///
    /// The SQL always binds three positional parameters:
    /// - `?1`: `workspace_name`
    /// - `?2`: `exclude_ticket_id` (may be `None`)
    /// - `?3`: ReadyForDevelopment phase value
    ///
    /// When `require_rfd_reservation = true` the RFD branch adds
    /// `AND pipeline_reservation = 1` to the same `?3` position.
    async fn has_active_tickets_internal(
        &self,
        workspace_name: &str,
        exclude_ticket_id: Option<&str>,
        require_rfd_reservation: bool,
    ) -> Result<bool> {
        let blocker_sql = phase_list_sql_fragment(PIPELINE_BLOCKING_PHASES);
        let rfd_condition = if require_rfd_reservation {
            "(phase = ?3 AND pipeline_reservation = 1)".to_string()
        } else {
            "phase = ?3".to_string()
        };
        let sql = format!(
            "SELECT 1 FROM tickets WHERE \
             (phase IN ({blocker_sql}) OR {rfd_condition}) \
             AND workspace_name = ?1 AND is_archived = 0 \
             AND (?2 IS NULL OR id != ?2) LIMIT 1",
        );
        let rfd = TicketPhase::ReadyForDevelopment.as_ref();
        let rows = self
            .conn
            .query(&sql, turso::params![workspace_name, exclude_ticket_id, rfd])
            .await?;
        Ok(!rows.is_empty())
    }

    /// Returns `true` if the given workspace has any ticket with a
    /// pipeline-blocking phase (dev/review/QA), OR any reserved
    /// ReadyForDevelopment ticket that was bounced back and is awaiting rework.
    ///
    /// **Test-only query** — retained to provide coverage of the pipeline-blocker
    /// SQL variant. Production code uses [`has_active_tickets_excluding`] or
    /// [`count_by_phase`].
    ///
    /// Delegates to [`has_active_tickets_internal`] with
    /// `exclude_ticket_id = None` and `require_rfd_reservation = true`.
    ///
    /// Note this includes `AND pipeline_reservation = 1` for ReadyForDevelopment
    /// tickets, unlike [`has_active_tickets_excluding`] (the production entry
    /// point) which treats all ReadyForDevelopment tickets as active regardless
    /// of reservation.
    ///
    /// # Maintenance warning
    ///
    /// If a future feature needs this in production, remove the `#[cfg(test)]`
    /// gate and add a real caller. The doc comment and tests will validate the
    /// query is correct before any production use.
    ///
    /// Excludes archived tickets — the only phases that ever get archived are
    /// `Done` and `Cancelled`, neither of which appears in
    /// `PIPELINE_BLOCKING_PHASES`, so this is a defensive consistency measure.
    #[cfg(test)]
    pub(crate) async fn has_pipeline_blocker_for_workspace(
        &self,
        workspace_name: &str,
    ) -> Result<bool> {
        self.has_active_tickets_internal(workspace_name, None, true)
            .await
    }

    /// Check if the workspace has any active tickets other than the excluded one.
    ///
    /// "Active" means a ticket whose phase is either a pipeline-blocking phase
    /// (`PIPELINE_BLOCKING_PHASES`) or [`TicketPhase::ReadyForDevelopment`]
    /// (regardless of `pipeline_reservation` — unstarted backlog tickets are
    /// considered active to suppress Done notifications until the pipeline is
    /// fully drained).
    ///
    /// Delegates to `has_active_tickets_internal`. The test-only
    /// `has_pipeline_blocker_for_workspace` additionally requires
    /// `pipeline_reservation = 1` for ReadyForDevelopment tickets.
    ///
    /// Non-active phases (not matched by the query): `Done`, `Cancelled`,
    /// `Failed`, `Backlog`, `Analysis`, `Planning`.
    ///
    /// # Race condition note
    ///
    /// When multiple QaPassed tickets in the same workspace are finalized
    /// concurrently (each via [`tokio::spawn`] in the poller), both may see
    /// each other as active and both buffer their Done transitions. In this
    /// scenario all tickets are already in Done in the database — the only
    /// consequence is that Done notifications are delayed until the next
    /// [`crate::message_router::JobKind::UserMessage`] drains the buffer. This is an accepted trade-off:
    /// the race window is small and the buffer always drains eventually.
    pub async fn has_active_tickets_excluding(
        &self,
        workspace_name: &str,
        exclude_ticket_id: &str,
    ) -> Result<bool> {
        self.has_active_tickets_internal(workspace_name, Some(exclude_ticket_id), false)
            .await
    }

    /// Add a comment to a ticket (append-only).
    ///
    /// After persisting the comment, routes it to any running agents assigned
    /// to this ticket via the message router. If no agent is registered
    /// (the agent finished before the comment arrived), the comment stays in
    /// the DB and will be picked up by the next dispatch.
    pub async fn add_comment(&self, ticket_id: &str, role: &str, content: &str) -> Result<()> {
        crate::turso::with_tx(&self.conn, ticket_id, "add comment", async |tx| {
            Self::add_comment_tx(tx, ticket_id, role, content).await
        })
        .await?;

        // Route the comment to any running agents assigned to this ticket.
        self.route_comment_to_agents(ticket_id, role, content).await;

        Ok(())
    }

    /// Route a newly-persisted comment to any running agents assigned to the ticket.
    ///
    /// Looks up the ticket's `assigned_to` field. If agents are assigned and
    /// registered in the message router, the comment is delivered to each one.
    /// This is best-effort — failures are logged but not propagated.
    async fn route_comment_to_agents(&self, ticket_id: &str, role: &str, content: &str) {
        // Fetch the ticket's assigned_to and workspace_name
        let ticket = match self.get_ticket(ticket_id).await {
            Ok(Some(t)) => t,
            Ok(None) => {
                warn!(ticket = %ticket_id, "Comment routing: ticket not found");
                return;
            }
            Err(e) => {
                warn!(ticket = %ticket_id, error = %e, "Comment routing: failed to fetch ticket");
                return;
            }
        };

        let Some(assigned_to) = ticket.assigned_to.as_ref() else {
            return; // No agents assigned
        };

        for agent_id in assigned_to.split(',') {
            let agent_id = agent_id.trim();
            if agent_id.is_empty() {
                continue;
            }

            // Use the commenter's role. If it doesn't parse as a standard Role
            // (e.g. "engineer_1" from parallel-agent verdict comments), fall
            // back to Manager. This fallback is safe: pipeline agents receive
            // comments via try_route() → direct inbox delivery, NOT via the
            // consumer loop. AgentJob.role is only used for response delivery
            // in the consumer loop path, which pipeline agents never enter.
            let commenter_role = role.parse::<crate::Role>().unwrap_or(crate::Role::Manager);

            let job = crate::message_router::AgentJob {
                content: content.to_string(),
                workspace_name: ticket.workspace_name.clone(),
                user_name: role.to_string(),
                channel: String::new(),
                kind: crate::message_router::JobKind::TicketComment,
                role: commenter_role,
                reply_target: None,
                pending_job_id: None,
            };

            if crate::message_router::try_route(agent_id, job) {
                debug!(
                    ticket = %ticket_id,
                    agent = %agent_id,
                    "Routed comment to running agent",
                );
            }
        }
    }

    /// Transactional variant of [`add_comment`](Self::add_comment) —
    /// uses an existing transaction instead of opening its own.
    /// Does NOT commit or rollback; the caller controls outer transaction lifecycle.
    ///
    /// Inserts the comment record AND updates the ticket's `updated_at` timestamp.
    ///
    /// NOTE: Unlike [`add_comment`](Self::add_comment), this method does NOT route
    /// the comment to running agents via the message router. All current callers
    /// (verdict recording, system comments, failure reports) are post-agent phases
    /// where no running agent exists to receive the comment. If adding a new caller
    /// that runs mid-execution, use [`add_comment`](Self::add_comment) instead, or
    /// call [`route_comment_to_agents`](Self::route_comment_to_agents) manually
    /// after the transaction commits.
    pub(crate) async fn add_comment_tx(
        tx: &TxGuard<'_>,
        ticket_id: &str,
        role: &str,
        content: &str,
    ) -> Result<()> {
        let comment_id = crate::generate_id();
        let now = turso::now();
        tx.execute(
            "INSERT INTO ticket_comments (id, ticket_id, role, content, created_at) \
             VALUES (?1, ?2, ?3, ?4, ?5)",
            turso::params![comment_id, ticket_id, role, content, now.as_str()],
        )
        .await?;
        tx.execute(
            "UPDATE tickets SET updated_at = ?1 WHERE id = ?2",
            turso::params![now.as_str(), ticket_id],
        )
        .await?;
        Ok(())
    }

    /// Get all comments for a ticket, ordered by creation time.
    pub async fn get_comments(&self, ticket_id: &str) -> Result<Vec<TicketComment>> {
        let sql = format!(
            "SELECT {COMMENT_COLUMNS} FROM ticket_comments WHERE ticket_id = ?1 ORDER BY created_at ASC"
        );
        let rows = self.conn.query(&sql, turso::params![ticket_id]).await?;
        let mut comments = Vec::new();
        for row in rows {
            comments.push(TicketComment {
                role: row.get(COL_COMMENT_ROLE)?,
                content: row.get(COL_COMMENT_CONTENT)?,
                created_at: row.get(COL_COMMENT_CREATED_AT)?,
            });
        }
        Ok(comments)
    }

    /// Validate prerequisites for a new ticket being created.
    ///
    /// Checks that every prerequisite ticket exists and belongs to the same
    /// workspace. Self-reference is checked separately by the caller (before
    /// this function is called, using the real ID generated within the transaction).
    ///
    /// At creation time, transitive cycles cannot exist because no existing
    /// ticket depends on the new ticket yet. Redundant prerequisites (e.g.,
    /// A and B where B already depends on A) are allowed — they do not form
    /// a cycle.
    async fn validate_prerequisites(
        tx: &TxGuard<'_>,
        prerequisite_ids: &[String],
        workspace_name: &str,
    ) -> Result<()> {
        // Guard against empty list — SQLite rejects WHERE id IN ().
        if prerequisite_ids.is_empty() {
            return Ok(());
        }

        // Batch query: fetch id + workspace_name for all prerequisites in one
        // round trip. Uses tx.query() — the transaction's query method operates
        // on the upstream connection through the MutexGuard, avoiding mutex
        // deadlock with conn.query().
        let (suffix, params) = Self::in_clause_for_ids(prerequisite_ids);
        let sql = format!("SELECT id, workspace_name FROM tickets {suffix}");
        let rows = tx.query(&sql, params).await?;

        // Build a lookup map for O(1) prerequisite resolution.
        let mut found: HashMap<String, String> = HashMap::new();
        for row in rows {
            let id: String = row.get(0)?;
            let ws_name: String = row.get(1)?;
            found.insert(id, ws_name);
        }

        for pid in prerequisite_ids {
            let ws_name = found
                .get(pid)
                .ok_or_else(|| anyhow::anyhow!("Prerequisite ticket not found: {pid}"))?;
            anyhow::ensure!(
                ws_name == workspace_name,
                "Prerequisite {pid} belongs to workspace '{ws_name}', \
                 not the ticket's workspace '{workspace_name}'. \
                 Cross-workspace prerequisites are not allowed.",
            );
        }

        Ok(())
    }

    /// List all tickets, optionally filtered by workspace and/or phase.
    /// Used by the dashboard to show tickets across all workspaces.
    pub async fn list_all_tickets(
        &self,
        workspace_name: Option<&str>,
        phase_filter: Option<TicketPhase>,
    ) -> Result<Vec<Ticket>> {
        let phase_str: Option<&str> = phase_filter.as_ref().map(TicketPhase::as_ref);
        self.select_tickets(
            "WHERE (?1 IS NULL OR workspace_name = ?1) \
             AND (?2 IS NULL OR phase = ?2) \
             AND is_archived = 0 \
             ORDER BY priority ASC, created_at DESC",
            turso::params![workspace_name, phase_str],
            LoadComments::No,
        )
        .await
    }

    /// Count how many tickets have the given phase, optionally filtered by workspace.
    ///
    /// Excludes archived tickets to stay consistent with [`list_all_tickets`](Self::list_all_tickets)
    /// and most other read paths in this module. Currently unused for `Done` or `Cancelled`
    /// (the only phases that ever get archived), so this is a defensive consistency fix —
    /// callers that pass a terminal phase will not see archived tickets in the count.
    pub async fn count_by_phase(
        &self,
        phase: TicketPhase,
        workspace_name: Option<&str>,
    ) -> Result<i64> {
        self.conn
            .query_row(
                "SELECT COUNT(*) FROM tickets \
                 WHERE phase = ?1 \
                   AND (?2 IS NULL OR workspace_name = ?2) \
                   AND is_archived = 0",
                turso::params![phase.as_ref(), workspace_name],
                |row| row.get(0),
            )
            .await
            .map_err(Into::into)
    }

    /// Archive a single ticket by ID.
    ///
    /// Sets `is_archived = 1` and clears `assigned_to` (archived tickets should
    /// not remain assigned). Returns an error if the ticket does not exist.
    ///
    /// **Ordering constraint:** The caller must transition the ticket to a
    /// terminal state (`done` or `cancelled`) *before* calling this method.
    /// There is no `assigned_to IS NULL` guard — [`transition_to`](Self::transition_to)
    /// already clears the assignee, and a single-ticket archive on an assigned
    /// ticket is intentionally allowed to resolve stale assignments.
    pub async fn set_archived(&self, ticket_id: &str) -> Result<()> {
        let prepared = Self::build_ticket_update_with_updated_at(
            "is_archived = 1, assigned_to = NULL",
            vec![],
            ticket_id,
        );
        prepared.execute_and_cancel(&self.conn).await
    }

    /// Move all non-archived ReadyForDevelopment tickets in the given workspace
    /// to Planning, clearing their assignments.
    ///
    /// Used by the circuit breaker to drain sibling ReadyForDevelopment tickets
    /// when a ticket in the same workspace fails, ensuring pipeline reservation
    /// ordering is preserved (bounced tickets get priority over fresh ones).
    ///
    /// Uses a single atomic UPDATE so there is no TOCTOU window between reading
    /// current ReadyForDevelopment tickets and updating them. Per-sibling
    /// notifications are intentionally suppressed — each sibling will discover
    /// its new phase on the next poll cycle via the standard poll loop.
    ///
    /// Returns the number of tickets moved.
    pub(crate) async fn drain_ready_for_development_to_planning(
        &self,
        workspace_name: &str,
    ) -> Result<u64> {
        let now = turso::now();
        let updated = self
            .conn
            .execute(
                "UPDATE tickets SET phase = ?1, assigned_to = NULL, updated_at = ?2 \
                 WHERE phase = ?3 AND workspace_name = ?4 AND is_archived = 0",
                turso::params![
                    TicketPhase::Planning.as_ref(),
                    now,
                    TicketPhase::ReadyForDevelopment.as_ref(),
                    workspace_name,
                ],
            )
            .await?;
        Ok(updated)
    }

    pub async fn archive_stale_cancelled(&self, hours: i64) -> Result<u64> {
        let now = turso::now();
        let cutoff = (Utc::now() - Duration::hours(hours)).to_rfc3339();
        let updated = self
            .conn
            .execute(
                "UPDATE tickets SET is_archived = 1, updated_at = ?1 \
                 WHERE phase = ?2 AND updated_at < ?3 AND assigned_to IS NULL \
                 AND is_archived = 0",
                turso::params![now, TicketPhase::Cancelled.as_ref(), cutoff],
            )
            .await
            .context("Failed to archive stale cancelled tickets")?;
        Ok(updated)
    }

    /// Idempotently clear stale `pipeline_reservation` flags on
    /// terminal-phase tickets ([`TERMINAL_PHASES`]).
    ///
    /// Terminal phases cannot be claimed, so a reservation left over from a
    /// pre-terminal bounce is inert garbage. The sweep is a pure flag purge:
    /// it does **not** bump `updated_at`/`done_at` (bumping `updated_at` would
    /// delay stale-cancelled archival, which filters by `updated_at` cutoff)
    /// and does **not** filter `is_archived` (archived terminal rows can still
    /// carry the flag). Non-terminal reserved rows (e.g. ReadyForDevelopment
    /// waiting for the pipeline) are deliberately left untouched.
    pub(crate) async fn clear_terminal_reservations(&self) -> Result<u64> {
        let sql = format!(
            "UPDATE tickets SET pipeline_reservation = 0 \
             WHERE phase IN ({}) AND pipeline_reservation = 1",
            phase_list_sql_fragment(TERMINAL_PHASES),
        );
        let updated = self
            .conn
            .execute(&sql, turso::params![])
            .await
            .context("Failed to clear stale terminal pipeline reservations")?;
        Ok(updated)
    }

    pub async fn archive_all_done_and_cancelled(
        &self,
        workspace_name: Option<&str>,
    ) -> Result<u64> {
        let now = turso::now();
        let sql = format!(
            "UPDATE tickets SET is_archived = 1, updated_at = ?1 \
             WHERE phase IN ({}) AND assigned_to IS NULL AND is_archived = 0 \
             AND (?2 IS NULL OR workspace_name = ?2)",
            phase_list_sql_fragment(UNBLOCKING_PHASES),
        );
        let updated = self
            .conn
            .execute(&sql, turso::params![now, workspace_name])
            .await
            .context("Failed to archive done/cancelled tickets")?;
        Ok(updated)
    }

    // ── Board display ordering (shared with the GUI) ─────────────────────
    //
    // The GUI board and the Telegram `/board` command must show tickets in
    // exactly the same order. These helpers are the single source of truth —
    // the GUI column rendering and the Telegram listing both use them.

    /// Partition tickets into the three kanban columns, in the same order the
    /// GUI board displays them: completed ([`TicketPhase::is_unblocking`]),
    /// pipeline ([`TicketPhase::is_pipeline_blocking`] plus
    /// `ReadyForDevelopment`), pending (everything else — the safe fallback
    /// for unclassified phases). Archived tickets are excluded.
    ///
    /// Non-completed tickets sort by priority ASC (0 = highest) then
    /// created_at ASC; completed tickets sort Done-first by exact done
    /// timestamp DESC (created_at fallback), then Cancelled by created_at
    /// DESC.
    #[must_use]
    pub fn partition_board_tickets(
        tickets: &[Ticket],
    ) -> (Vec<&Ticket>, Vec<&Ticket>, Vec<&Ticket>) {
        let mut pending = Vec::new();
        let mut pipeline = Vec::new();
        let mut completed = Vec::new();

        for ticket in tickets {
            if ticket.is_archived {
                continue; // hidden from board
            }
            if ticket.phase.is_unblocking() {
                completed.push(ticket);
            } else if ticket.phase.is_pipeline_blocking()
                || ticket.phase == TicketPhase::ReadyForDevelopment
            {
                pipeline.push(ticket);
            } else {
                // Unknown future phases silently default to pending — the
                // safe bucket for unclassified phases.
                pending.push(ticket);
            }
        }

        // Sort: pending and pipeline by priority (ASC), then oldest-first (ASC);
        // completed: Done tickets newest-done_first (DESC), then Cancelled
        // newest-first (DESC) below them.
        // Priority is an integer — 0 = highest, so ASC puts urgent tickets first.
        // Ticket created_at is an ISO 8601 string, so lexical sort = chronological sort
        pending.sort_by(|a, b| {
            a.priority
                .cmp(&b.priority)
                .then(a.created_at.cmp(&b.created_at))
        });
        pipeline.sort_by(|a, b| {
            a.priority
                .cmp(&b.priority)
                .then(a.created_at.cmp(&b.created_at))
        });
        completed.sort_by(|a, b| {
            let (a_done, b_done) = (a.phase == TicketPhase::Done, b.phase == TicketPhase::Done);
            match (a_done, b_done) {
                // Done first, newest completion on top (created_at fallback
                // for Done tickets with no done_at, e.g. test-created ones).
                (true, true) => Self::board_done_sort_key(b).cmp(Self::board_done_sort_key(a)),
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                (false, false) => b.created_at.cmp(&a.created_at),
            }
        });

        (pending, pipeline, completed)
    }

    /// The four board sections in display order: In Progress (pipeline minus
    /// ReadyForDevelopment), Ready, Pending, Completed. Shared by the GUI
    /// column rendering and the Telegram `/board` listing so the two surfaces
    /// can never diverge. Empty sections are included (callers skip them).
    #[must_use]
    pub fn board_sections(tickets: &[Ticket]) -> [Vec<&Ticket>; 4] {
        let (pending, pipeline, completed) = Self::partition_board_tickets(tickets);
        let in_progress = pipeline
            .iter()
            .filter(|t| t.phase != TicketPhase::ReadyForDevelopment)
            .copied()
            .collect();
        let ready = pipeline
            .iter()
            .filter(|t| t.phase == TicketPhase::ReadyForDevelopment)
            .copied()
            .collect();
        [in_progress, ready, pending, completed]
    }

    /// Flatten [`Self::board_sections`] into a single display-order list —
    /// the exact order the GUI board shows them. Used by the Telegram
    /// `/board` command so its listing can never diverge from the GUI.
    #[must_use]
    pub fn board_display_order(tickets: &[Ticket]) -> Vec<&Ticket> {
        Self::board_sections(tickets)
            .into_iter()
            .flatten()
            .collect()
    }

    /// Completion ordering key for a completed-column ticket: its exact done
    /// timestamp, falling back to creation time when `done_at` is absent.
    fn board_done_sort_key(ticket: &Ticket) -> &str {
        ticket.done_at.as_deref().unwrap_or(&ticket.created_at)
    }

    // ── Ticket FTS/embedding search methods ───────────────────────────────
    //
    // The archived-search methods contain the FTS and embedding SQL used by
    // [`SearchArchivedTicketsTool`](crate::tools::search_archived_tickets);
    // [`search_by_fts`] backs the GUI sidebar search. The board owns the
    // schema (`ngram` tokenizer, FTS index name, blob format) and the tool
    // layer owns the hybrid RRF merge logic.

    /// Search archived tickets by FTS keyword match, scoped to a workspace.
    ///
    /// Sanitizes the input query (strips non-alphanumeric characters) before
    /// matching against the `ngram`-tokenized FTS index on `title`.
    ///
    /// Returns up to `limit` `(id, fts_score)` pairs, highest score first.
    /// On SQL error (e.g. corrupt FTS index), logs a warning and returns an
    /// empty vec — the caller may fall through to vector search as a graceful
    /// degradation strategy.
    pub async fn search_archived_by_fts(
        &self,
        query: &str,
        limit: usize,
        workspace_name: &str,
    ) -> Result<Vec<(String, f64)>> {
        let sanitized = crate::turso::sanitize_fts_query(query);
        if sanitized.is_empty() {
            return Ok(Vec::new());
        }

        // Param order mirrors search_by_fts: ?1 = workspace, ?2 = query.
        let sql = format!(
            "SELECT t.id, fts_score(t.title, ?2) AS score \
             FROM tickets t \
             WHERE t.is_archived = 1 \
               AND t.workspace_name = ?1 \
               AND t.title MATCH ?2 \
             ORDER BY score DESC LIMIT {limit}"
        );
        match self
            .conn
            .query_map(
                &sql,
                turso::params![workspace_name, sanitized.clone()],
                |row| {
                    let id: String = row.get(0)?;
                    let score: f64 = row.get(1)?;
                    Ok::<_, anyhow::Error>((id, score))
                },
            )
            .await
        {
            Ok(items) => Ok(items
                .into_iter()
                .collect::<std::result::Result<Vec<_>, _>>()?),
            Err(e) => {
                tracing::warn!(
                    query = %sanitized,
                    error = %e,
                    "FTS search for archived tickets failed"
                );
                Ok(Vec::new())
            }
        }
    }

    /// Search tickets (both active and archived) by FTS keyword match, scoped
    /// to an optional workspace.
    ///
    /// Sanitizes the input query (strips non-alphanumeric characters) before
    /// matching against the `ngram`-tokenized FTS index on `title`.
    ///
    /// Returns full [`Ticket`] objects (without comments) ordered by FTS
    /// relevance (`fts_score DESC`), up to `limit` results.
    /// On SQL error, logs a warning and returns an empty vec.
    pub async fn search_by_fts(
        &self,
        query: &str,
        limit: usize,
        workspace_name: Option<&str>,
    ) -> Result<Vec<Ticket>> {
        let sanitized = crate::turso::sanitize_fts_query(query);
        if sanitized.is_empty() {
            return Ok(Vec::new());
        }

        // Use an explicit `FROM tickets t` alias so `fts_score(t.title, ?2)`
        // resolves correctly — the `select_tickets` helper does not support
        // table aliases in FTS scoring expressions.
        let sql = format!(
            "SELECT {TICKET_COLUMNS} \
             FROM tickets t \
             WHERE (?1 IS NULL OR t.workspace_name = ?1) \
               AND t.title MATCH ?2 \
             ORDER BY fts_score(t.title, ?2) DESC \
             LIMIT {limit}"
        );
        match self
            .conn
            .query(&sql, turso::params![workspace_name, sanitized.clone()])
            .await
        {
            Ok(rows) => {
                let mut tickets = Vec::with_capacity(rows.len());
                for row in rows {
                    match self.ticket_from_row(&row, LoadComments::No).await {
                        Ok(t) => tickets.push(t),
                        Err(e) => {
                            tracing::warn!(
                                error = %e,
                                "Failed to parse ticket row from FTS search"
                            );
                        }
                    }
                }
                Ok(tickets)
            }
            Err(e) => {
                tracing::warn!(
                    query = %sanitized,
                    error = %e,
                    "FTS search failed"
                );
                Ok(Vec::new())
            }
        }
    }

    /// List archived tickets with non-NULL embeddings, deserialized, scoped to
    /// a workspace.
    ///
    /// Returns `(id, embedding)` pairs for all archived tickets that have
    /// a stored embedding blob. Embeddings are deserialized from the
    /// on-disk `[u8]` byte layout (4-byte little-endian `f32`) into
    /// `Vec<f32>` via [`crate::vector::bytes_to_vec`].
    ///
    /// This returns ALL archived tickets with embeddings — there is no
    /// LIMIT because the caller (the tool layer) needs all candidates for
    /// cosine-similarity ranking, and the archive size is bounded in practice
    /// by the total ticket volume of the installation.
    pub async fn list_archived_with_embeddings(
        &self,
        workspace_name: &str,
    ) -> Result<Vec<(String, Vec<f32>)>> {
        let rows = self
            .conn
            .query(
                "SELECT id, embedding FROM tickets \
                 WHERE is_archived = 1 AND workspace_name = ?1 AND embedding IS NOT NULL",
                turso::params![workspace_name],
            )
            .await?;

        let mut candidates: Vec<(String, Vec<f32>)> = Vec::new();
        for row in &rows {
            let id: String = row.get(0)?;
            let stored: Vec<u8> = row.get(1)?;
            let emb = crate::vector::bytes_to_vec(&stored);
            candidates.push((id, emb));
        }
        Ok(candidates)
    }
}

/// Open a [`BoardStore`] in a fresh temp directory (no global CONFIG dependency).
///
/// Thin wrapper around [`crate::open_test_store!`] that avoids touching the 32
/// call sites inside `self::tests`.  Delegates to the shared macro so the
/// actual boilerplate lives in one place.
///
/// Internal test convenience — external modules should use the macro directly.
#[cfg(test)]
async fn open_test_store() -> (BoardStore, tempfile::TempDir) {
    crate::open_test_store!(BoardStore, "board")
}

#[cfg(test)]
#[path = "board_tests.rs"]
mod tests;