mahbot 0.5.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Ticket/board system — Turso-backed task management.

use crate::db::{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,
    post_open = after_open,
    expect = "BOARD not initialized — call init_all_stores() first",
}

/// Background task: auto-archive cancelled tickets older than 1 hour.
///
/// Runs every 5 minutes, respects the global shutdown token via
/// [`crate::shutdown::sleep_or_shutdown_or_drain`] (same pattern as
/// [`crate::agent::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;
        }

        // Session-pin terminal deletion (S5): remove permanently-NULL seats
        // for tickets in a terminal phase — the TTL guard stops protecting
        // the accumulated stage session once the pin is gone
        // (idempotent, ≤5-min delay against the 8h TTL).
        crate::jobs::purge_terminal_session_pins().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"),
        }
    }
}

/// 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",
        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",
        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 + Queued) and is no longer
/// directly suppressed by this constant.
///
/// Occupancy is owned by the phase job (a short-lived job whose `kind` is the
/// ticket's current phase) — a ticket in any of these phases always has a
/// live phase job, and that job is the single authority that runs the stage
/// then advances the ticket to the next phase. `tickets.phase` is both the
/// displayed pipeline state and the input gate for the claim step
/// (Backlog → Analysis, Queued → InDevelopment) — not a mirror
/// of a long-lived job.
const PIPELINE_OCCUPIED_PHASES: &[TicketPhase] = &[
    TicketPhase::InDevelopment,
    TicketPhase::InDiagnostics,
    TicketPhase::InReview,
    TicketPhase::InQa,
    TicketPhase::InSanitation,
];

/// The six phases the poll loop drives with phase jobs, in dispatch order.
///
/// Note: this is deliberately NOT the [`TicketPhase`] declaration order —
/// `InSanitation` is dispatched last, after review and QA. Both the dispatch
/// snapshot query and its phase-major grouping derive from this constant.
pub(crate) const WORKING_PHASES: &[TicketPhase] = &[
    TicketPhase::Analysis,
    TicketPhase::InDevelopment,
    TicketPhase::InDiagnostics,
    TicketPhase::InReview,
    TicketPhase::InQa,
    TicketPhase::InSanitation,
];

/// 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.
///
/// 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(", ")
}

/// The claim-candidate eligibility predicate, shared verbatim by the claim
/// UPDATE and its read-only probe (single source — the two cannot drift).
/// `source` selects the claim shape: only Backlog→Analysis applies the
/// [`BACKLOG_CLAIM_GRACE`] cutoff, only Queued→InDevelopment enforces
/// pipeline occupancy. Placeholders are numbered from `base`: `?{base}` =
/// source phase, `?{base+1}` = workspace name and, for Backlog,
/// `?{base+2}` = grace cutoff.
fn claim_candidate_where(base: usize, source: TicketPhase) -> String {
    let mut parts = vec![
        format!("t1.phase = ?{base}"),
        format!("t1.workspace_name = ?{}", base + 1),
        "t1.is_archived = 0".to_string(),
    ];
    if source == TicketPhase::Backlog {
        parts.push(format!("t1.created_at <= ?{}", base + 2));
    }
    if source == TicketPhase::Queued {
        parts.push(format!(
            "NOT EXISTS (SELECT 1 FROM tickets t2 \
                WHERE t2.workspace_name = t1.workspace_name \
                AND t2.phase IN ({}) \
                AND t2.is_archived = 0 \
                AND t2.id != t1.id)",
            phase_list_sql_fragment(PIPELINE_OCCUPIED_PHASES),
        ));
    }
    parts.push(format!(
        "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),
    ));
    parts.join(" AND ")
}

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 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,
    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 from a
    /// validation-phase non-success (diagnostics/review/QA/sanitation). Drives
    /// the bounce-based circuit breaker (max 10). Engineer hard failures are
    /// pause-only (workspace pause, implementation frozen) and do not consume this
    /// budget.
    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. `queued`)
    /// - 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:
    ///
    /// - `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). `GetTicketTool` uses
    /// [`Self::detailed_display_limited`] for its default truncated view.
    ///
    /// ## 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 = self.header(&self.description);
        out.push_str(&self.format_comments());
        out
    }

    /// Return a truncated version of [`Self::detailed_display`] for agent-facing
    /// output where the caller only needs the ticket's latest state.
    ///
    /// The description value is capped at `desc_max_chars` characters (a trailing
    /// `…` is appended when it exceeds the cap) and each comment's content is
    /// capped at `comment_max_chars` characters, EXCEPT the newest `last_n_full`
    /// comments which are always shown in full. Header metadata (id, title, phase,
    /// priority, reporter, workspace, dates, supersede/prerequisite links,
    /// archived flag) is never truncated.
    #[must_use]
    pub(crate) fn detailed_display_limited(
        &self,
        desc_max_chars: usize,
        comment_max_chars: usize,
        last_n_full: usize,
    ) -> String {
        let description = crate::util::truncate(&self.description, desc_max_chars);
        let mut out = self.header(&description);
        out.push_str(&self.format_comments_limited(comment_max_chars, last_n_full));
        out
    }

    /// Build the shared header of [`Self::detailed_display`] and
    /// [`Self::detailed_display_limited`], rendering `description` verbatim.
    #[must_use]
    fn header(&self, description: &str) -> 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 = 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
    }

    /// 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.
    #[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 {
                s.push_str(&Self::comment_line(c, &c.content));
            }
        }
        s
    }

    /// Like [`Self::format_comments`], but caps each comment's content at
    /// `max_chars` characters (appending `…` when truncated) except for the
    /// newest `last_n_full` comments, which are shown in full.
    #[must_use]
    fn format_comments_limited(&self, max_chars: usize, last_n_full: usize) -> String {
        let mut s = String::from("Comments:");
        if self.comments.is_empty() {
            s.push_str("\n  (no comments)");
        } else {
            let n = self.comments.len();
            for (i, c) in self.comments.iter().enumerate() {
                let content = if i + last_n_full < n {
                    crate::util::truncate(&c.content, max_chars)
                } else {
                    c.content.clone()
                };
                s.push_str(&Self::comment_line(c, &content));
            }
        }
        s
    }

    /// Format a single comment line: `"\n  [{role}] ({timestamp}): {content}"`.
    ///
    /// Timestamps are truncated to seconds (`[..19]` of the RFC 3339 string),
    /// with a defensive `min()` guard against abnormally short strings.
    #[must_use]
    fn comment_line(c: &TicketComment, content: &str) -> String {
        let end = 19.min(c.created_at.len());
        let ts = &c.created_at[..end];
        format!("\n  [{}] ({}): {}", c.role, ts, content)
    }
}
/// 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 Queued or cancel it.
    Planning,
    Queued,
    InDevelopment,
    InDiagnostics,
    InSanitation,
    InReview,
    InQa,
    Done,
    Cancelled,
    Failed,
}

impl TicketPhase {
    /// 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 its phase job is
    /// finished.
    ///
    /// Delegates to [`TERMINAL_PHASES`] so the terminal set is authoritative
    /// for both the transition-clearing clause and the implementation completion.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        TERMINAL_PHASES.contains(self)
    }

    /// Returns `true` if the ticket is in a pipeline-occupied phase.
    ///
    /// Tickets in these phases occupy the dev/review/QA pipeline — only one
    /// ticket per workspace may be in the pipeline at a time. Each phase is
    /// owned by its own short-lived phase job (development, diagnostics,
    /// review, QA, sanitation). The automated
    /// create-ticket tool (when superseding an existing ticket) and the
    /// update-ticket tool refuse to modify tickets in any of these phases to
    /// prevent race conditions during phase transitions. `add_comment` is the
    /// exception: it is allowed during any phase and delivers to a running
    /// agent as a soft deferred message (or persists for the next agent).
    #[must_use]
    pub fn is_pipeline_occupied(&self) -> bool {
        PIPELINE_OCCUPIED_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<db::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: &db::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: &db::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::supersede_and_create`** — runs inside a transaction, cancels
    ///   before commit via a different pattern.
    async fn execute_and_cancel(self, conn: &db::Connection) -> Result<()> {
        let rows = conn.execute(&self.sql, self.params).await?;
        BoardStore::ensure_ticket_found(rows, &self.ticket_id)?;
        crate::agent::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: &db::TxGuard<'_>) -> Result<bool> {
        let rows = tx.execute(&self.sql, self.params).await?;
        Ok(rows > 0)
    }
}

/// 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: ensure the FTS index exists with the correct tokenizer.
    ///
    /// The index is ALSO declared in the schema catalog
    /// ([`crate::db::migrations`]) so the consolidated schema creates it before
    /// the one-time import (guaranteeing imported tickets are FTS-searchable).
    /// This hook therefore only tokenizer-migrates an existing index (drops
    /// and recreates if the tokenizer changed); it is idempotent and runs from
    /// both [`crate::db::init_all_stores`] (production, on the shared
    /// consolidated connection) and each isolated board store open. The board
    /// schema changes are NOT run here — every schema change is an entry in the
    /// append-only catalog ([`crate::db::migrations`]) applied once by
    /// [`crate::db::open_consolidated_store`].
    ///
    /// After the FTS index is ensured, a boot-time detect+repair of corruption
    /// localized to the title FTS index runs (fail-safe: it never fails the
    /// boot — see [`crate::db::repair_ticket_title_fts_if_corrupt`]).
    pub(crate) async fn after_open(&self) -> anyhow::Result<()> {
        crate::db::ensure_fts_index(
            &self.conn,
            crate::db::TICKETS_FTS_INDEX_NAME,
            "ngram",
            crate::db::TICKETS_FTS_INDEX_DDL,
        )
        .await?;
        crate::db::repair_ticket_title_fts_if_corrupt(
            &self.conn,
            crate::db::TICKETS_FTS_INDEX_NAME,
            crate::db::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 = db::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)",
            db::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_backlog_for_analysis`](Self::claim_backlog_for_analysis)).
    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",
                db::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",
                    db::params![new_json, db::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",
                db::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",
                db::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 = db::now();
        let cancelled_rows = tx
            .execute(
                "UPDATE tickets SET phase = ?1, updated_at = ?2, \
                 superseded_by = ?4, is_archived = 1, done_at = NULL \
                 WHERE id = ?3",
                db::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::agent::registry::AGENT_REGISTRY.cancel_by_ticket_id(supersede_id);

        // No chronicle 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: &db::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>()?,
            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)?,
            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; the rationale lives on
    /// [`claim_backlog_for_analysis`](Self::claim_backlog_for_analysis).
    pub(crate) const BACKLOG_CLAIM_GRACE: Duration = Duration::seconds(5);

    /// Claim a workspace's oldest eligible [`TicketPhase::Backlog`] ticket and
    /// transition it to Analysis. See [`claim_for_phase`] for the shared
    /// semantics. The Backlog shape additionally applies a `created_at <= ?5`
    /// cutoff excluding tickets younger than [`BACKLOG_CLAIM_GRACE`], so a
    /// fresh ticket stays in Backlog ~5s — claiming it into Analysis within
    /// the window would spawn analysts that immediately get cancelled (plus a
    /// spurious phase-change notification), while the Manager gets time to
    /// move it straight to Planning/Queued.
    pub(crate) async fn claim_backlog_for_analysis(
        &self,
        workspace_name: &str,
        now: String,
        grace_cutoff: String,
    ) -> Result<Option<Ticket>> {
        self.claim_for_phase(
            workspace_name,
            now,
            TicketPhase::Backlog,
            TicketPhase::Analysis,
            Some(&grace_cutoff),
        )
        .await
    }

    /// Claim a workspace's oldest eligible [`TicketPhase::Queued`] ticket and
    /// transition it to InDevelopment. See [`claim_for_phase`] for the shared
    /// semantics. The Queued shape additionally rejects the claim (returns
    /// `None`) while any pipeline-occupied ticket ([`PIPELINE_OCCUPIED_PHASES`])
    /// exists in the same workspace, enforcing a single ticket at a time in the
    /// dev/review/QA pipeline. The occupancy check's `t2.is_archived = 0` guard
    /// is a deliberate no-op today — only Done/Cancelled tickets get archived
    /// and neither is a pipeline phase — but kept for consistency.
    pub(crate) async fn claim_queued_for_development(
        &self,
        workspace_name: &str,
        now: String,
    ) -> Result<Option<Ticket>> {
        self.claim_for_phase(
            workspace_name,
            now,
            TicketPhase::Queued,
            TicketPhase::InDevelopment,
            None,
        )
        .await
    }

    /// Core claim: atomically transition a workspace's oldest eligible ticket
    /// from `source` to `target` in a single `UPDATE..RETURNING`. Always
    /// filters by `workspace_name` so only tickets from that workspace are
    /// eligible. The WHERE clause includes `t1.phase = ?3` bound to `source`,
    /// providing CAS-style atomicity — if no matching ticket exists, the claim
    /// returns `None`.
    ///
    /// The WHERE predicate comes from [`claim_candidate_where`] with base
    /// placeholder offset 3 (`?1`/`?2` are the SET-clause phase/updated_at
    /// binds), the same builder the read-only probe uses — so the claim and
    /// its probe cannot drift. Only Backlog carries the `grace_cutoff` bind
    /// (it must be `Some` only for [`TicketPhase::Backlog`]); only Queued
    /// enforces pipeline occupancy. `now` and `grace_cutoff` are supplied by
    /// the caller, computed once per poll round and shared with the probe, so
    /// the probe and the claim can never disagree about the clock or the
    /// cutoff.
    ///
    /// The prereq filter is part of the same atomic UPDATE (no separate
    /// SELECT+UPDATE window): a candidate with an unmet prerequisite is excluded
    /// via `NOT EXISTS` over `json_each(t1.prerequisites)`, joining to each
    /// prerequisite ticket and rejecting the candidate unless every
    /// prerequisite is in an unblocking phase ([`UNBLOCKING_PHASES`]) — so a
    /// Manager moving a Backlog ticket straight to Queued (or a prereq being
    /// re-opened after its dependent entered the pipeline) cannot advance it
    /// out of dependency order.
    ///
    /// The candidate subquery orders by `priority ASC, created_at ASC` so
    /// tickets with lower priority (higher urgency) are claimed first, then
    /// the oldest ticket (earliest created_at) first.
    ///
    /// The SQL text per (source, grace_cutoff) combination is invariant, which
    /// the [`Connection::query_cached`] cache contract requires. Note: the
    /// claim SELECT is kept to the tickets table, and the agents roster is a
    /// separate logical table checked by the caller (via the phase-job +
    /// launched-roster guard) — Backlog/Queued tickets have no running agent.
    async fn claim_for_phase(
        &self,
        workspace_name: &str,
        now: String,
        source: TicketPhase,
        target: TicketPhase,
        grace_cutoff: Option<&str>,
    ) -> Result<Option<Ticket>> {
        let sql = format!(
            "UPDATE tickets SET phase = ?1, updated_at = ?2 \
             WHERE id = (SELECT t1.id FROM tickets t1 \
             WHERE {} \
             ORDER BY t1.priority ASC, t1.created_at ASC LIMIT 1) \
             RETURNING {TICKET_COLUMNS}",
            claim_candidate_where(3, source),
        );
        let rows = match grace_cutoff {
            Some(cutoff) => {
                self.conn
                    .query_cached(
                        &sql,
                        db::params![
                            target.as_ref(),
                            now,
                            source.as_ref(),
                            workspace_name,
                            cutoff
                        ],
                    )
                    .await?
            }
            None => {
                self.conn
                    .query_cached(
                        &sql,
                        db::params![target.as_ref(), now, source.as_ref(), workspace_name],
                    )
                    .await?
            }
        };
        match rows.into_iter().next() {
            Some(row) => Ok(Some(self.ticket_from_row(&row, LoadComments::Yes).await?)),
            None => Ok(None),
        }
    }

    /// Read-only existence probe for the Backlog→Analysis claim: `true` when at
    /// least one ticket satisfies the exact claim predicate (same shared
    /// builder, same bound grace cutoff — no drift). Existence only: no ORDER
    /// BY, no column fetch.
    pub(crate) async fn backlog_claim_candidate_exists(
        &self,
        workspace_name: &str,
        grace_cutoff: &str,
    ) -> Result<bool> {
        self.claim_candidate_exists(TicketPhase::Backlog, workspace_name, Some(grace_cutoff))
            .await
    }

    /// Read-only existence probe for the Queued→InDevelopment claim.
    pub(crate) async fn queued_claim_candidate_exists(&self, workspace_name: &str) -> Result<bool> {
        self.claim_candidate_exists(TicketPhase::Queued, workspace_name, None)
            .await
    }

    /// Core probe: `SELECT 1 FROM tickets t1 WHERE {claim_candidate_where} LIMIT 1`
    /// through the prepared-cached path. The SQL text is invariant (phase lists
    /// are compile-time constants; workspace/cutoff are bound parameters), which
    /// the [`Connection::query_cached`] cache contract requires. The text is a
    /// plain SELECT — read-only by construction, since `query_cached` does not
    /// enforce read-only the way `query_readonly` does. Existence only, so
    /// unlike the claim there is no ORDER BY sorter to pay for.
    async fn claim_candidate_exists(
        &self,
        source: TicketPhase,
        workspace_name: &str,
        grace_cutoff: Option<&str>,
    ) -> Result<bool> {
        let sql = format!(
            "SELECT 1 FROM tickets t1 WHERE {} LIMIT 1",
            claim_candidate_where(1, source),
        );
        let rows = match grace_cutoff {
            Some(cutoff) => {
                self.conn
                    .query_cached(&sql, db::params![source.as_ref(), workspace_name, cutoff])
                    .await?
            }
            None => {
                self.conn
                    .query_cached(&sql, db::params![source.as_ref(), workspace_name])
                    .await?
            }
        };
        Ok(!rows.is_empty())
    }

    /// 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 `db::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", db::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 ({})", db::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",
                db::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, db::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.
    ///
    fn build_ticket_update_with_updated_at(
        set_clause: &str,
        set_params: Vec<db::Value>,
        ticket_id: &str,
    ) -> PreparedUpdate {
        let now = db::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 an extra SET column (`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.
    fn build_transition_sql(
        ticket_id: &str,
        expected_phase: Option<TicketPhase>,
        target_phase: TicketPhase,
    ) -> PreparedUpdate {
        let now = db::now();
        let guard: Option<&str> = expected_phase.as_ref().map(TicketPhase::as_ref);
        let sql = "UPDATE tickets SET phase = ?1, updated_at = ?2, \
                    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<db::Value> = vec![
            Value::from(target_phase.as_ref()),
            Value::from(now),
            Value::from(ticket_id),
            Value::from(guard),
        ];
        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 cancels running agents.
    ///
    /// # 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,
    ) -> Result<()> {
        let prepared = Self::build_transition_sql(ticket_id, expected_phase, target_phase);
        prepared.execute_and_cancel(&self.conn).await?;
        // A terminal transition (Done/Cancelled/Failed) completes the ticket's
        // phase jobs (idempotent; no-op when the ticket has none) so a manual
        // Done/Cancelled does not leave a lingering 'launched' phase job. The
        // pipeline path completes the phase jobs at its own Done handoff
        // functions, so this only fires for external/manual callers.
        // Guard on the session store being initialized: this is the MANUAL
        // path, and some board-only contexts (tests) never open the session DB.
        if target_phase.is_terminal()
            && let Some(session) = crate::session::SESSIONS.get()
        {
            let _ = crate::jobs::complete_ticket_phase_jobs(&session.conn, ticket_id).await;
        }
        Ok(())
    }

    /// 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,
    ) -> Result<bool> {
        let prepared = Self::build_transition_sql(ticket_id, expected_phase, target_phase);
        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(())
    }

    /// 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",
                db::params![db::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"
            )),
        }
    }

    /// Shared implementation for checking if a workspace has active tickets.
    ///
    /// Returns `true` if any ticket in the workspace has a pipeline-occupied
    /// phase ([`PIPELINE_OCCUPIED_PHASES`]), or a
    /// [`Queued`](TicketPhase::Queued) ticket,
    /// optionally excluding a specific ticket ID.
    ///
    /// [`has_active_tickets_excluding`] delegates to this helper.
    ///
    /// # 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`).
    ///
    /// Excludes archived tickets — the only phases that ever get archived are
    /// `Done` and `Cancelled`, neither of which appears in
    /// `PIPELINE_OCCUPIED_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`: Queued phase value
    async fn has_active_tickets_internal(
        &self,
        workspace_name: &str,
        exclude_ticket_id: Option<&str>,
    ) -> Result<bool> {
        let occupied_sql = phase_list_sql_fragment(PIPELINE_OCCUPIED_PHASES);
        let sql = format!(
            "SELECT 1 FROM tickets WHERE \
             (phase IN ({occupied_sql}) OR phase = ?3) \
             AND workspace_name = ?1 AND is_archived = 0 \
             AND (?2 IS NULL OR id != ?2) LIMIT 1",
        );
        let queued = TicketPhase::Queued.as_ref();
        let rows = self
            .conn
            .query(&sql, db::params![workspace_name, exclude_ticket_id, queued])
            .await?;
        Ok(!rows.is_empty())
    }

    /// Check if the workspace has any active tickets other than the excluded one.
    ///
    /// "Active" means a ticket whose phase is either a pipeline-occupied phase
    /// (`PIPELINE_OCCUPIED_PHASES`) or [`TicketPhase::Queued`]
    /// (unstarted backlog tickets are considered active to suppress Done
    /// notifications until the pipeline is fully drained).
    ///
    /// Delegates to `has_active_tickets_internal`.
    ///
    /// Non-active phases (not matched by the query): `Done`, `Cancelled`,
    /// `Failed`, `Backlog`, `Analysis`, `Planning`.
    ///
    /// # Race condition note
    ///
    /// When multiple occupied 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::agent::message_router::MessageKind::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))
            .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. A comment delivered to a running
    /// agent is a SOFT DEFERRED message consumed at the start of the agent's
    /// next tool round — it never cancels or aborts the agent. If no agent is
    /// registered (the agent finished before the comment arrived), the comment
    /// is surfaced by the next agent that works on the ticket: a fresh dispatch
    /// on a new session re-renders the ticket comment block, and a resumed
    /// deterministic stage session (engineer/sanitation) injects outstanding
    /// comments at the empty-message resume point.
    pub async fn add_comment(&self, ticket_id: &str, role: &str, content: &str) -> Result<()> {
        crate::db::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 currently-running agents (`launched` roster rows
    /// across the ticket's jobs — the replacement for the historical
    /// `tickets.assigned_to`). If agents are 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) {
        // Best-effort: if the sessions store isn't initialized (e.g. a
        // board-only test), there are no active agents to route to.
        let Some(sessions) = crate::session::SESSIONS.get() else {
            return;
        };
        // Fetch the ticket's 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 active =
            match crate::jobs::list_running_agents_for_ticket(&sessions.conn, ticket_id).await {
                Ok(agents) if !agents.is_empty() => agents,
                Ok(_) => return, // No running agents
                Err(e) => {
                    warn!(
                        ticket = %ticket_id,
                        error = %e,
                        "Comment routing: failed to read running agents",
                    );
                    return;
                }
            };

        for agent_id in active {
            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::agent::message_router::AgentJob {
                content: content.to_string(),
                workspace_name: ticket.workspace_name.clone(),
                user_name: role.to_string(),
                channel: String::new(),
                kind: crate::agent::message_router::MessageKind::TicketComment,
                role: commenter_role,
                reply_target: None,
                pending_job_id: None,
            };

            if crate::agent::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 = db::now();
        tx.execute(
            "INSERT INTO ticket_comments (id, ticket_id, role, content, created_at) \
             VALUES (?1, ?2, ?3, ?4, ?5)",
            db::params![comment_id, ticket_id, role, content, now.as_str()],
        )
        .await?;
        tx.execute(
            "UPDATE tickets SET updated_at = ?1 WHERE id = ?2",
            db::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, db::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. The
    /// `is_archived = 0` gate means a ticket appears here iff it is live,
    /// which also backs the CDC removal decision.
    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",
            db::params![workspace_name, phase_str],
            LoadComments::No,
        )
        .await
    }

    /// List the live tickets of a workspace across all working phases
    /// ([`WORKING_PHASES`]) in one snapshot, grouped phase-major in dispatch
    /// order with `priority ASC, created_at DESC` within each phase (the
    /// global `ORDER BY` plus stable per-phase bucketing preserves each
    /// phase's internal order).
    ///
    /// Unlike [`list_all_tickets`](Self::list_all_tickets) (which the GUI
    /// still uses), this is a single snapshot so the polling dispatch sees
    /// one consistent view per tick.
    pub(crate) async fn list_working_tickets(
        &self,
        workspace_name: &str,
    ) -> Result<Vec<(TicketPhase, Ticket)>> {
        // The IN-list placeholders are derived from WORKING_PHASES so the SQL
        // cannot drift from the constant; the interpolated text stays
        // invariant across calls, keeping the statement-cache contract.
        let phase_placeholders = (2..=WORKING_PHASES.len() + 1)
            .map(|i| format!("?{i}"))
            .collect::<Vec<_>>()
            .join(", ");
        let sql = format!(
            "SELECT {TICKET_COLUMNS} FROM tickets \
             WHERE workspace_name = ?1 \
             AND phase IN ({phase_placeholders}) \
             AND is_archived = 0 \
             ORDER BY priority ASC, created_at DESC"
        );
        let mut params: Vec<Value> = vec![Value::from(workspace_name)];
        params.extend(WORKING_PHASES.iter().map(|p| Value::from(p.as_ref())));
        let rows = self.conn.query_cached(&sql, params).await?;
        // Bucket each ticket by its index in WORKING_PHASES. Bucketing is
        // stable, so the global `priority ASC, created_at DESC` order is
        // preserved within each phase.
        let mut buckets: Vec<Vec<Ticket>> = vec![Vec::new(); WORKING_PHASES.len()];
        for row in rows {
            let ticket = self.ticket_from_row(&row, LoadComments::No).await?;
            let Some(idx) = WORKING_PHASES.iter().position(|p| *p == ticket.phase) else {
                continue; // defensive: unreachable via the IN filter
            };
            buckets[idx].push(ticket);
        }
        let mut out = Vec::with_capacity(buckets.iter().map(Vec::len).sum());
        for (idx, phase) in WORKING_PHASES.iter().enumerate() {
            out.extend(buckets[idx].drain(..).map(|ticket| (*phase, ticket)));
        }
        Ok(out)
    }

    /// 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",
                db::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`. 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.
    pub async fn set_archived(&self, ticket_id: &str) -> Result<()> {
        let prepared =
            Self::build_ticket_update_with_updated_at("is_archived = 1", vec![], ticket_id);
        prepared.execute_and_cancel(&self.conn).await
    }

    /// Move all non-archived Queued tickets in the given workspace
    /// to Planning.
    ///
    /// Used by the circuit breaker to drain sibling Queued tickets
    /// when a ticket in the same workspace fails.
    ///
    /// Uses a single atomic UPDATE so there is no TOCTOU window between reading
    /// current Queued 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_queued_to_planning(&self, workspace_name: &str) -> Result<u64> {
        let now = db::now();
        let updated = self
            .conn
            .execute(
                "UPDATE tickets SET phase = ?1, updated_at = ?2 \
                 WHERE phase = ?3 AND workspace_name = ?4 AND is_archived = 0",
                db::params![
                    TicketPhase::Planning.as_ref(),
                    now,
                    TicketPhase::Queued.as_ref(),
                    workspace_name,
                ],
            )
            .await?;
        Ok(updated)
    }

    pub async fn archive_stale_cancelled(&self, hours: i64) -> Result<u64> {
        let now = db::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 is_archived = 0",
                db::params![now, TicketPhase::Cancelled.as_ref(), cutoff],
            )
            .await
            .context("Failed to archive stale cancelled tickets")?;
        Ok(updated)
    }

    pub async fn archive_all_done_and_cancelled(
        &self,
        workspace_name: Option<&str>,
    ) -> Result<u64> {
        let now = db::now();
        let sql = format!(
            "UPDATE tickets SET is_archived = 1, updated_at = ?1 \
             WHERE phase IN ({}) AND is_archived = 0 \
             AND (?2 IS NULL OR workspace_name = ?2)",
            phase_list_sql_fragment(UNBLOCKING_PHASES),
        );
        let updated = self
            .conn
            .execute(&sql, db::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_occupied`] plus
    /// `Queued`), 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_occupied() || ticket.phase == TicketPhase::Queued {
                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
    /// Queued), Queued, 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::Queued)
            .copied()
            .collect();
        let queued = pipeline
            .iter()
            .filter(|t| t.phase == TicketPhase::Queued)
            .copied()
            .collect();
        [in_progress, queued, 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::db::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,
                db::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::db::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, db::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",
                db::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)
    }
}