mahbot 0.10.5

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
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
//! Durable jobs layer: jobs/agents/pending_jobs lifecycle, boot recovery scan and
//! the phase-only stale purge orchestrator.
//!
//! All rows live in the consolidated domain database (`core.db`) behind the one
//! writing connection, so jobs/session/board ordering and crash-safety are expressed
//! in a single transaction. This module owns the row model, the lifecycle helpers and
//! the boot scan; the DDL lives in the append-only catalog
//! ([`crate::db::migrations`]). Purge scope is phase-only: ticket-phase jobs are
//! time-deleted (the puller re-creates them from `tickets.phase`); non-phase launched
//! jobs and pending envelopes are never purged by time — explicit abandon only.

use crate::Role;
use crate::agent::message_router::{AgentJob, MessageKind};
use crate::db::{self, Connection, Row, TxGuard, Value, params};
use crate::pipeline::board::{TicketPhase, WORKING_PHASES};
use anyhow::{Context, Result};
use std::time::Duration;
use tracing::{debug, error, info, warn};

// Values of `jobs.kind` are fully determined by the child row (one kind per
// child — `SpawnChild::kind_str`); the [`MessageKind`] enum travels inside the
// serialized pending_jobs envelope and is unrelated to that vocabulary.

/// Status vocabulary shared by `jobs.status` and `agents.status` — both tables are
/// schema-locked to the same launched/done/failed dictionary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RowStatus {
    Launched,
    Done,
    Failed,
}

impl RowStatus {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Launched => "launched",
            Self::Done => "done",
            Self::Failed => "failed",
        }
    }
}

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Case-sensitive to mirror the schema dictionary exactly.
        match s {
            "launched" => Ok(Self::Launched),
            "done" => Ok(Self::Done),
            "failed" => Ok(Self::Failed),
            _ => Err(anyhow::anyhow!(
                "Invalid row status '{s}'. Valid statuses: launched, done, failed"
            )),
        }
    }
}

/// Explicit dispatch mode of a job — replaces the NULL-sentinel overload of `caller_agent_id`.
/// `Sync` jobs are owned by the caller session pin; `Async` jobs (research/analyze,
/// research_cleanup, ticket phases, pin-less implement dispatches) resume at boot, while
/// `temp_cleanup` rows are terminalized instead.
///
/// The string values are intrinsic Rust/SQL coupling: `as_str()`, the SQL literals in
/// [`find_owned_launched_jobs`] / [`abandon_session_jobs`] and migration delta `30`'s backfill
/// CASE must stay in sync on a rename.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum JobMode {
    Sync,
    Async,
}

impl JobMode {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Sync => "sync",
            Self::Async => "async",
        }
    }
}

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Case-sensitive to mirror the schema dictionary exactly.
        match s {
            "sync" => Ok(Self::Sync),
            "async" => Ok(Self::Async),
            _ => Err(anyhow::anyhow!(
                "Invalid job mode '{s}'. Valid modes: sync, async"
            )),
        }
    }
}

/// Values of `agents.kind` — dispatch-slot kinds.
///
/// A round whose slots form more than one cohort carries a label per cohort
/// (`Reviewer`/`Tester`, `Analyst`/`BlockerVerifier`) because the resume path reads
/// the cohorts back from the stored roster: the label is the cohort identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AgentKind {
    Analyst,
    /// The analysis escalation cohort's blocker-verification slots.
    BlockerVerifier,
    Reviewer,
    Tester,
    Engineer,
    /// Single worker sub-agent for the durable async worker round (`send`'s
    /// `worker` addressee).
    Worker,
    Sanitation,
}

impl AgentKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Analyst => "analyst",
            Self::BlockerVerifier => "blocker_verifier",
            Self::Reviewer => "reviewer",
            Self::Tester => "tester",
            Self::Engineer => "engineer",
            Self::Worker => "worker",
            Self::Sanitation => "sanitation",
        }
    }
}

/// Graceful-shutdown drain cap: in-flight work completes within this window, then
/// stragglers are force-cancelled. Read from outside too: a quit-armed exit bound
/// has to outlast it (`shutdown::macos_quit`).
pub(crate) const DRAIN_CAP_SECS: u64 = 10 * 60;

/// Stale-purge cutoff (hours): only ticket-phase `jobs` rows older than this are
/// purged (they are recoverable from `tickets.phase`). Non-phase launched jobs are
/// never time-deleted (explicit abandon only), and `pending_jobs` envelopes are never
/// time-purged — at-least-once keeps unconfirmed rows alive.
pub const PURGE_CUTOFF_HOURS: i64 = 8;

// Only the columns actually read by the scan paths are copied into memory; caller
// identity is re-queried on demand by `job_caller`. The DB schema columns stay as-is.

#[derive(Debug, Clone)]
pub(crate) struct JobRow {
    pub id: String,
    pub kind: String,
    pub workspace_name: String,
    pub retry_count: i64,
    pub ticket_id: Option<String>,
    /// The caller agent's stable session pin for sync analyze/implement jobs; NULL for
    /// async/boot-resumed jobs.
    pub caller_agent_id: Option<String>,
    /// Explicit dispatch mode (see [`JobMode`]) — the `caller_agent_id` discriminator.
    mode: JobMode,
    /// The absolute folder a delegated round runs in; `None` = the caller's workspace.
    pub exec_dir: Option<String>,
    /// The row's `created_at` — the anchor the caller's resume-completion step
    /// compares against its own frame row to tell a round THIS frame dispatched
    /// from the leftover of an earlier one.
    pub created_at: String,
}

/// A row of the `agents` table. Carries the slot `idx` (in addition to the
/// status/outcome/task) so the slot-resume skeleton can reconstruct a round in
/// place without re-deriving it from live ticket state.
#[derive(Debug, Clone)]
pub(crate) struct AgentRow {
    pub idx: Option<i64>,
    pub agent_id: String,
    /// The row's `agents.kind` label — the roster's cohort identity.
    pub kind: String,
    pub status: String,
    pub outcome: Option<String>,
    pub task: String,
}

#[derive(Debug, Clone)]
pub(crate) struct PendingJobRow {
    pub id: String,
    pub target_agent_id: String,
    pub envelope: String,
    pub created_at: String,
}

crate::columns! {
    JOB_COLUMNS [JOB] {
        ID              => "id",
        KIND            => "kind",
        WORKSPACE_NAME  => "workspace_name",
        RETRY_COUNT     => "retry_count",
        TICKET_ID       => "ticket_id",
        CALLER_AGENT_ID => "caller_agent_id",
        MODE            => "mode",
        EXEC_DIR        => "exec_dir",
        CREATED_AT      => "created_at",
    }
}

fn job_row_from(row: &Row) -> anyhow::Result<JobRow> {
    Ok(JobRow {
        id: row.get(COL_JOB_ID)?,
        kind: row.get(COL_JOB_KIND)?,
        workspace_name: row.get(COL_JOB_WORKSPACE_NAME)?,
        retry_count: row.get(COL_JOB_RETRY_COUNT)?,
        ticket_id: row.get(COL_JOB_TICKET_ID)?,
        caller_agent_id: row.get(COL_JOB_CALLER_AGENT_ID)?,
        exec_dir: row.get(COL_JOB_EXEC_DIR)?,
        created_at: row.get(COL_JOB_CREATED_AT)?,
        // Defensive fallback: the migration backfills every row, so a NULL or bogus value
        // here is a legacy edge — treat it as async rather than dropping the job at boot.
        mode: match row.get::<Option<String>>(COL_JOB_MODE)? {
            Some(s) => s.parse().unwrap_or_else(|e| {
                warn!(mode = %s, error = %e, "Invalid jobs.mode — falling back to async");
                JobMode::Async
            }),
            None => JobMode::Async,
        },
    })
}

crate::columns! {
    AGENT_COLUMNS [AGENT] {
        IDX      => "idx",
        AGENT_ID => "agent_id",
        KIND     => "kind",
        STATUS   => "status",
        OUTCOME  => "outcome",
        TASK     => "task",
    }
}

fn agent_row_from(row: &Row) -> anyhow::Result<AgentRow> {
    Ok(AgentRow {
        idx: row.get(COL_AGENT_IDX)?,
        agent_id: row.get(COL_AGENT_AGENT_ID)?,
        kind: row.get(COL_AGENT_KIND)?,
        status: row.get(COL_AGENT_STATUS)?,
        outcome: row.get(COL_AGENT_OUTCOME)?,
        task: row.get(COL_AGENT_TASK)?,
    })
}

fn pending_row_from(row: &Row) -> anyhow::Result<PendingJobRow> {
    Ok(PendingJobRow {
        id: row.get(0)?,
        target_agent_id: row.get(1)?,
        envelope: row.get(2)?,
        created_at: row.get(3)?,
    })
}

// Each durable INSERT form has two producers — one lock-acquiring (conn), one
// lock-held (TxGuard). The SQL const + params builder is the single source of truth
// for the column set; call sites keep their own executor (never delegate a TxGuard
// call to conn.execute — the guard already holds the mutex).

/// pending_jobs envelope INSERT — producers: `message_router::persist_pending`
/// and `complete_job_with_envelope`.
pub(crate) const PENDING_JOB_INSERT_SQL: &str = "INSERT INTO pending_jobs \
     (id, target_agent_id, envelope, created_at) \
     VALUES (?1, ?2, ?3, ?4)";

/// Build the pending_jobs INSERT params from a durable envelope — the target agent id
/// is derived from the envelope (caller identity lives in the serialized envelope).
pub(crate) fn pending_job_params(id: &str, envelope: &AgentJob, now: &str) -> Result<[Value; 4]> {
    let envelope_json = serde_json::to_string(envelope)?;
    Ok([
        id.into(),
        envelope_target(envelope).into(),
        envelope_json.into(),
        now.into(),
    ])
}

/// agents roster INSERT — producers: `spawn_job` roster loop and the pipeline's
/// `insert_round_slots`. Status is the literal 'launched'.
pub(crate) const AGENT_INSERT_SQL: &str = "INSERT INTO agents \
     (job_id, agent_id, kind, idx, status, task) \
     VALUES (?1, ?2, ?3, ?4, 'launched', ?5)";

/// Build the agents roster INSERT params (status is fixed by the SQL).
pub(crate) fn agent_params(
    job_id: &str,
    agent_id: &str,
    kind: AgentKind,
    idx: Option<i64>,
    task: &str,
) -> [Value; 5] {
    [
        job_id.into(),
        agent_id.into(),
        kind.as_str().into(),
        idx.into(),
        task.into(),
    ]
}

/// Optional kind-specific child row inserted in the SAME tx as the job row
/// (jobs + agents + child are one atomic unit — a crash between a jobs+agents commit
/// and a later child insert would otherwise leave a resumable job without its child).
/// The shared helper takes the child explicitly (never branching on `kind`).
#[derive(Debug, Clone)]
pub(crate) enum SpawnChild {
    /// Pure kind marker — no child row (resume reads the jobs row alone).
    Analyze,
    /// Pure kind marker — no child row. The single worker's roster row holds the
    /// dispatched task; the job row holds the caller identity for resume delivery.
    Implement,
    /// research_jobs (id, state).
    Research,
    /// A research-run cleanup Sanitation agent. No child row: the jobs row's `task` holds
    /// the cleanup prompt, and the row id == the run id (folder name) so the row holds the
    /// run folder until the cleanup completes (folder first, row last).
    ResearchCleanup,
    /// A periodic temp cleaner Sanitation agent (see `crate::temp`). No child row: the jobs row's
    /// `task` holds the prompt. Leftover rows are terminalized at boot (never resumed) — the
    /// cleaner's ephemeral workspace is never a managed workspace.
    TempCleanup,
    /// A per-phase ticket job: `jobs.kind` = `phase.as_ref()` (the single state-machine
    /// authority), `jobs.ticket_id` = the ticket. One short-lived job per phase; roster
    /// grows during the phase, and the job is deleted when the phase completes or resets.
    Phase {
        phase: TicketPhase,
        ticket_id: String,
    },
}

impl SpawnChild {
    /// The `jobs.kind` value — one kind per child row (Analyze is the pure-marker
    /// exception). Deriving kind here closes the drift window of a mismatched pair.
    #[must_use]
    pub fn kind_str(&self) -> &'static str {
        match self {
            Self::Analyze => "analyze",
            Self::Implement => "implement",
            Self::Research => "research",
            Self::ResearchCleanup => "research_cleanup",
            Self::TempCleanup => "temp_cleanup",
            // A phase job is named after its phase (`jobs.kind` mirrors
            // `tickets.phase`, the sole running truth); only the working phases
            // are spawnable, so anything else is a caller bug worth a refusal.
            Self::Phase { phase, .. } => {
                assert!(
                    crate::pipeline::board::WORKING_PHASES.contains(phase),
                    "non-working phase as a job kind: {}",
                    phase.as_ref(),
                );
                <&'static str>::from(*phase)
            }
        }
    }
}

/// `jobs.ticket_id` for a spawn child — `Some` only for ticket phase jobs.
#[must_use]
fn child_ticket_id(child: &SpawnChild) -> Option<&str> {
    match child {
        SpawnChild::Phase { ticket_id, .. } => Some(ticket_id.as_str()),
        _ => None,
    }
}

/// Spawn a job with its pre-generated agent roster in ONE transaction. MUST commit
/// before the agent's first session write. The kind is derived from the child via
/// [`SpawnChild::kind_str`]; a row for a cancelled analyze round is never committed.
#[expect(clippy::too_many_arguments)]
pub(crate) async fn spawn_job(
    conn: &Connection,
    id: &str,
    task: &str,
    workspace_name: &str,
    user_name: &str,
    channel: &str,
    role: Role,
    agents: &[NewAgent],
    child: &SpawnChild,
    caller_agent_id: Option<&str>,
    exec_dir: Option<&str>,
    custom_launch: Option<&crate::Launch>,
) -> Result<()> {
    let tx = conn.begin_tx().await?;
    insert_job_tx(
        &tx,
        id,
        task,
        workspace_name,
        user_name,
        channel,
        role,
        agents,
        child,
        caller_agent_id,
        exec_dir,
        custom_launch,
    )
    .await?;
    // Manual-cancel gate INSIDE the tx (after the INSERT, before the commit), scoped to the
    // child a cancel action can name: the tx holds the single-writer lock, so a dispatch
    // whose row write races the cancel either observes the fired signal here — the row is
    // never committed — or commits first and the cancel sweep's DELETE serializes behind
    // this tx. A cancellation and the analyze row can therefore never both stand. Every
    // other child keeps its dispatch unbounded by cancel signals — a research run's id, for
    // one, is reused by the cleanup row its cancelled-run handoff still has to write.
    if matches!(child, SpawnChild::Analyze) && crate::round_cancel::is_cancelled(id) {
        // Rolled back HERE rather than left to the guard's drop: a cancellation that abandons
        // its own write leaves no deferred-cleanup WARN behind and no dangling transaction.
        tracing::info!(job = %id, "Job dispatch rolled back — round cancelled");
        tx.rollback().await?;
        return Ok(());
    }
    tx.commit().await?;
    Ok(())
}

/// The jobs-row INSERT + agent-roster loop + child-row match, run inside a live
/// transaction (`tx`). Extracted from [`spawn_job`] so callers that already hold a
/// handoff transaction reuse the exact row model. Does NOT commit.
#[expect(clippy::too_many_arguments)]
async fn insert_job_tx(
    tx: &TxGuard<'_>,
    id: &str,
    task: &str,
    workspace_name: &str,
    user_name: &str,
    channel: &str,
    role: Role,
    agents: &[NewAgent],
    child: &SpawnChild,
    caller_agent_id: Option<&str>,
    exec_dir: Option<&str>,
    custom_launch: Option<&crate::Launch>,
) -> Result<()> {
    let kind = child.kind_str();
    let ticket_id = child_ticket_id(child);
    // The mode is derived from the caller pin (sync ⇔ pin present). A sync dispatch
    // without a pin resolves to mode=async, preserving the replaced NULL-sentinel behavior.
    let mode = if caller_agent_id.is_some() {
        JobMode::Sync
    } else {
        JobMode::Async
    };
    // JSON for the custom-role launch the round was dispatched by (`NULL` for built-in
    // callers) — read back by `job_caller` on boot resume.
    let custom_launch_json = custom_launch
        .map(serde_json::to_string)
        .transpose()
        .context("serialize jobs.custom_launch")?;
    let now = db::now();
    tx.execute(
        "INSERT INTO jobs (id, kind, status, task, workspace_name, user_name, channel, role, \
         ticket_id, retry_count, created_at, updated_at, caller_agent_id, mode, exec_dir, \
         custom_launch) \
         VALUES (?1, ?2, 'launched', ?3, ?4, ?5, ?6, ?7, ?8, 0, ?9, ?9, ?10, ?11, ?12, ?13)",
        params![
            id,
            kind,
            task,
            workspace_name,
            user_name,
            channel,
            role.as_str(),
            ticket_id,
            now.clone(),
            caller_agent_id,
            mode.as_str(),
            exec_dir,
            custom_launch_json,
        ],
    )
    .await
    .with_context(|| format!("failed to spawn job {id}"))?;
    for a in agents {
        tx.execute(
            AGENT_INSERT_SQL,
            agent_params(id, &a.agent_id, a.kind, a.idx, &a.task),
        )
        .await
        .with_context(|| format!("failed to insert agent roster for job {id}"))?;
    }
    match child {
        SpawnChild::Analyze
        | SpawnChild::Implement
        | SpawnChild::ResearchCleanup
        | SpawnChild::TempCleanup
        | SpawnChild::Phase { .. } => {}
        SpawnChild::Research => {
            tx.execute(
                "INSERT INTO research_jobs (id, state) VALUES (?1, '{}')",
                params![id],
            )
            .await
            .with_context(|| format!("failed to insert research_jobs row for job {id}"))?;
        }
    }
    Ok(())
}

pub(crate) struct NewAgent {
    pub agent_id: String,
    pub kind: AgentKind,
    pub idx: Option<i64>,
    pub task: String,
}

/// Checkpoint a job row: bump retry_count and touch `updated_at` (a recency marker —
/// the phase-only purge keys off it).
async fn checkpoint_job(conn: &Connection, id: &str, retry_count: i64) -> Result<()> {
    // Boot resume re-arms the row unconditionally — status is reset to Launched
    // regardless of its prior value.
    let status = RowStatus::Launched;
    let now = db::now();
    conn.execute(
        "UPDATE jobs SET status = ?1, retry_count = ?2, updated_at = ?3 WHERE id = ?4",
        params![status.as_str(), retry_count, now, id],
    )
    .await
    .with_context(|| format!("failed to checkpoint job {id}"))?;
    Ok(())
}

/// Write one agent's terminal outcome (agents.outcome per-agent at round collection —
/// no read-modify-write race).
pub(crate) async fn write_agent_outcome(
    conn: &Connection,
    job_id: &str,
    agent_id: &str,
    status: RowStatus,
    outcome: Option<&str>,
) -> Result<()> {
    conn.execute(
        "UPDATE agents SET status = ?1, outcome = ?2 WHERE job_id = ?3 AND agent_id = ?4",
        params![status.as_str(), outcome, job_id, agent_id],
    )
    .await
    .with_context(|| format!("failed to write agent outcome for {agent_id}"))?;
    Ok(())
}

/// Complete a job whose result is a durable envelope: ONE tx — INSERT pending_jobs
/// (id = source jobs.id) + DELETE the jobs row. Exactly-once persistence boundary.
///
/// On INSERT failure the tx rolls back, so the job row SURVIVES and the caller routes the
/// envelope best-effort. The surviving row is resumed at the next boot and delivers a SECOND
/// envelope — an accepted duplicate-delivery window on the DB-error path.
pub(crate) async fn complete_job_with_envelope(
    conn: &Connection,
    job_id: &str,
    envelope: &AgentJob,
) -> Result<()> {
    let now = db::now();
    let tx = conn.begin_tx().await?;
    tx.execute(
        PENDING_JOB_INSERT_SQL,
        pending_job_params(job_id, envelope, &now).context("serialize envelope")?,
    )
    .await
    .with_context(|| format!("failed to persist envelope for job {job_id}"))?;
    delete_job_tx(&tx, job_id).await?;
    // Manual-cancel gate INSIDE the tx (after the INSERT, before the commit): the tx
    // holds the single-writer lock, so a cancel that fired after the caller's
    // pre-completion check is still observed here and rolls the tx back — the pending row
    // is never committed and the job row survives for the cancel sweep, whose DELETE then
    // serializes behind this tx. Job kinds that never register a cancel signal (a worker
    // round) keep their unbounded completion.
    if crate::round_cancel::is_cancelled(job_id) {
        tracing::info!(job = %job_id, "Job completion rolled back — run manually cancelled");
        tx.rollback().await?;
        return Ok(());
    }
    tx.commit().await?;
    Ok(())
}

/// COMPLETE a durable analyze/research job in one tx: INSERT the pending_jobs envelope (id = job
/// id) and DELETE the jobs row (see [`complete_job_with_envelope`]). Returns the envelope with
/// `pending_job_id` set when the row persisted, cleared on INSERT failure so the caller routes
/// best-effort. A cancelled round's in-tx gate rolls the write back and still returns Ok; both
/// call sites check their cancel flag before routing.
///
/// `custom` is the calling custom role's launch, written into the envelope so
/// [`envelope_target`] resolves the custom branch.
#[expect(clippy::too_many_arguments)]
pub(crate) async fn complete_durable_job(
    job_id: &str,
    content: String,
    kind: MessageKind,
    caller_role: Role,
    user_name: &str,
    channel: &str,
    workspace_name: &str,
    custom: Option<crate::Launch>,
) -> AgentJob {
    let mut envelope = AgentJob {
        content,
        workspace_name: workspace_name.to_string(),
        user_name: user_name.to_string(),
        channel: channel.to_string(),
        kind,
        role: caller_role,
        reply_target: None,
        pending_job_id: Some(job_id.to_string()),
        originating_workspace: None,
        custom_role: custom,
        reply_to_custom: None,
        urgent: false,
    };
    // INSERT-failure policy: fall back to a non-durable best-effort route.
    if complete_job_with_envelope(&crate::session::store().conn, job_id, &envelope)
        .await
        .is_err()
    {
        envelope.pending_job_id = None;
    }
    envelope
}

/// Terminalize a job: DELETE the row entirely — CASCADE removes the agent roster and child rows; a
/// no-op when the row is already absent. Safe for any jobs.kind. Ticket-phase call sites use it both
/// on success (the phase body transitions the ticket and deletes its own short-lived job; the puller
/// re-creates a fresh attempt on the next tick) and on hard-failure cleanup. Envelope kinds
/// (analyze/research) are terminal only when the row is gone — the pending row IS the durable record.
pub(crate) async fn terminalize_job(conn: &Connection, job_id: &str) -> Result<()> {
    conn.execute("DELETE FROM jobs WHERE id = ?1", params![job_id])
        .await
        .context("terminalize job")?;
    Ok(())
}

/// Whether a queued `pending_jobs` row still exists — the boot replay's re-check that
/// the envelope it is about to deliver was not discarded since the list was read. A
/// read failure answers `true`: delivering is the safe side.
async fn pending_row_exists(conn: &Connection, id: &str) -> bool {
    conn.query_optional(
        "SELECT 1 FROM pending_jobs WHERE id = ?1",
        params![id],
        |_| Ok::<(), anyhow::Error>(()),
    )
    .await
    .map_or(true, |found| found.is_some())
}

/// The envelope queued for `id`, when one waits — no feature module hand-writes this
/// table's shape. An unparsable envelope answers `None`: it addresses nothing.
pub(crate) async fn pending_envelope(conn: &Connection, id: &str) -> Result<Option<AgentJob>> {
    let raw = conn
        .query_optional(
            "SELECT envelope FROM pending_jobs WHERE id = ?1",
            params![id],
            |r| r.get::<String>(0),
        )
        .await
        .context("read a queued result")?;
    let Some(raw) = raw else {
        return Ok(None);
    };
    match serde_json::from_str(&raw) {
        Ok(job) => Ok(Some(job)),
        Err(e) => {
            tracing::debug!(
                pending_job = %id,
                error = %e,
                "Queued envelope unreadable — nothing to honour",
            );
            Ok(None)
        }
    }
}

/// Remove a gone round's own durable state in ONE tx: its queued result row first (the
/// boot replay would otherwise deliver it), then its `jobs` row (a surviving row would
/// be resumed, and its deletion cascades the roster). Idempotent; a failure rolls back.
pub(crate) async fn delete_round_rows(conn: &Connection, job_id: &str) -> Result<()> {
    let tx = conn
        .begin_tx()
        .await
        .context("begin the gone round's removal tx")?;
    tx.execute("DELETE FROM pending_jobs WHERE id = ?1", params![job_id])
        .await
        .context("delete the gone round's queued result")?;
    tx.execute("DELETE FROM jobs WHERE id = ?1", params![job_id])
        .await
        .context("delete the gone round's job row")?;
    tx.commit()
        .await
        .context("commit the gone round's removal")?;
    Ok(())
}

// Sync caller-owned jobs are never purged by time — only the caller's /clear or the
// deletion of the owning workspace abandons them. This is that path.

/// User-initiated /clear or session-row delete abandons the session's unfinished sync
/// jobs before the session is deleted — no silent orphaning. CASCADE removes the roster
/// rows; sync analyze/implement jobs carry no run folders or pending envelopes.
#[expect(clippy::cast_possible_truncation)] // u64 row count fits usize on all supported targets
pub(crate) async fn abandon_session_jobs(caller_agent_id: &str) -> Result<usize> {
    let conn = &crate::session::store().conn;
    let deleted = conn
        .execute(
            "DELETE FROM jobs WHERE mode = 'sync' AND caller_agent_id = ?1",
            params![caller_agent_id],
        )
        .await
        .context("abandon session sync jobs")?;
    info!(
        caller_agent_id,
        count = deleted,
        "abandoned session sync jobs"
    );
    Ok(deleted as usize)
}

/// Atomic cancel-handoff row transition for a research run being cancelled: DELETE the research
/// job row (and its pending envelope) and INSERT the `research_cleanup` row reusing id == run_id —
/// in ONE tx, so the folder can never be orphaned and boot resume picks cleanup up. The reverse
/// order is impossible (`jobs.id` is a PK).
pub(crate) async fn transition_research_to_cleanup(
    conn: &Connection,
    run_id: &str,
    cleanup_task: &str,
    workspace_name: &str,
) -> Result<()> {
    let tx = conn.begin_tx().await?;
    tx.execute("DELETE FROM pending_jobs WHERE id = ?1", params![run_id])
        .await
        .with_context(|| format!("failed to delete pending envelope for run {run_id}"))?;
    tx.execute("DELETE FROM jobs WHERE id = ?1", params![run_id])
        .await
        .with_context(|| format!("failed to delete research job row for run {run_id}"))?;
    insert_job_tx(
        &tx,
        run_id,
        cleanup_task,
        workspace_name,
        "",
        "",
        Role::Sanitation,
        &[NewAgent {
            agent_id: crate::research_cleanup::cleanup_agent_id(run_id),
            kind: AgentKind::Sanitation,
            idx: None,
            task: cleanup_task.to_string(),
        }],
        &SpawnChild::ResearchCleanup,
        None,
        None,
        None,
    )
    .await?;
    tx.commit().await?;
    Ok(())
}

/// Cancel the workspace's research/research_cleanup runs before its workspace-row deletion: fires
/// each run's cancel signal, cancels its agents, then performs the cancelled-run cleanup handoff
/// (a live orchestrator does its own). Returns the cancelled-run count; the remaining job rows are
/// deleted by the CALLER's workspace-row transaction.
///
/// Known race: the handoff runs asynchronously for a live orchestrator, but the cleanup agent then
/// uses the orchestrator's in-memory [`Workspace`] handle, so the folder is still released.
pub(crate) async fn abandon_workspace_research_runs(workspace_name: &str) -> Result<usize> {
    let conn = &crate::session::store().conn;
    let research_rows = conn
        .query(
            "SELECT id FROM jobs WHERE workspace_name = ?1 AND kind IN ('research','research_cleanup')",
            params![workspace_name],
        )
        .await
        .context("list research jobs for workspace abandon")?;
    let mut cancelled = 0usize;
    for row in &research_rows {
        let id: String = row.get(0)?;
        crate::research_cancel::cancel_research_run(&id).await;
        cancelled += 1;
    }
    Ok(cancelled)
}

// A sync analyze/implement job is owned by the caller session that launched it
// (`jobs.caller_agent_id` = the caller's stable session pin). The JOBS ROW is
// the source of truth for ownership. The caller's universal resume-completion
// step locates every launched caller-owned job by this pin and slot-resumes it.

/// Launched sync analyze/implement jobs owned by `caller_agent_id` (the caller's stable session
/// pin), newest first, awaiting the caller's resume-completion step. There is no freshness gate: a
/// job is dropped only by explicit abandon. The caller scopes its BINDING to its own dangling frame
/// ([`JobRow::created_at`]), so a pool entry that frame did not dispatch is abandoned.
pub(crate) async fn find_owned_launched_jobs(
    conn: &Connection,
    caller_agent_id: &str,
) -> Result<Vec<JobRow>> {
    let rows = conn
        .query(
            &format!(
                "SELECT {JOB_COLUMNS} FROM jobs j \
                 WHERE j.caller_agent_id = ?1 AND j.kind IN ('analyze','implement') AND j.status = 'launched' \
                   AND j.mode = 'sync' \
                 ORDER BY j.created_at DESC"
            ),
            params![caller_agent_id],
        )
        .await
        .context("find owned launched jobs")?;
    rows.iter().map(job_row_from).collect()
}

// A ticket phase job is a short-lived `jobs` row whose `kind` equals the ticket's
// current phase and whose `ticket_id` links it to the ticket. `tickets.phase` is the
// sole durable running truth; the job is created by the single puller when a ticket in
// a working phase has no job, and deleted when the phase completes or is reset.

/// A phase job id (kind = phase, ticket_id set).
#[derive(Debug, Clone)]
pub(crate) struct TicketJobRow {
    pub id: String,
}

fn ticket_job_row_from(row: &Row) -> anyhow::Result<TicketJobRow> {
    Ok(TicketJobRow { id: row.get(0)? })
}

pub(crate) async fn find_phase_job(
    conn: &Connection,
    ticket_id: &str,
    phase: TicketPhase,
) -> Result<Option<TicketJobRow>> {
    conn.query_optional_cached(
        "SELECT id FROM jobs \
         WHERE ticket_id = ?1 AND kind = ?2 AND status = 'launched' LIMIT 1",
        params![ticket_id, phase.as_ref()],
        ticket_job_row_from,
    )
    .await
    .context("find ticket phase job")
}

/// Terminalize every launched phase job for a ticket (idempotent) so no launched row
/// lingers until the stale purge.
pub(crate) async fn complete_ticket_phase_jobs(conn: &Connection, ticket_id: &str) -> Result<()> {
    let rows = conn
        .query(
            "SELECT id FROM jobs WHERE ticket_id = ?1 AND status = 'launched'",
            params![ticket_id],
        )
        .await
        .context("find ticket phase jobs for completion")?;
    for row in rows {
        let id: String = row.get(0)?;
        terminalize_job(conn, &id).await?;
    }
    Ok(())
}

/// Update the phase job's stored `task`; phase dispatch re-derives its prompt from
/// live state, so the stored value is not read for re-dispatch.
pub(crate) async fn update_phase_job_task(
    conn: &Connection,
    job_id: &str,
    task: &str,
) -> Result<()> {
    conn.execute(
        "UPDATE jobs SET task = ?2, updated_at = ?3 WHERE id = ?1",
        params![job_id, task, db::now()],
    )
    .await
    .context("update ticket phase job task")?;
    Ok(())
}

/// Upsert a job-bound roster row for a currently-running stage agent — the
/// active-agent marker that replaces `tickets.assigned_to`. The roster is keyed on
/// (job_id, agent_id) so the NULL-seat engineer anchor remains a distinct row.
///
/// The update half is the re-registration of an existing `(job_id, agent_id)`: the
/// agent id is derived from the ticket and role, so the puller re-driving a job it left
/// in place registers the same pair again and updates the row.
pub(crate) async fn upsert_job_agent(
    conn: &Connection,
    job_id: &str,
    agent_id: &str,
    kind: AgentKind,
    status: RowStatus,
) -> Result<()> {
    conn.upsert_row(
        "UPDATE agents SET status = ?1 WHERE job_id = ?2 AND agent_id = ?3",
        || params![status.as_str(), job_id, agent_id],
        "INSERT INTO agents (job_id, agent_id, kind, idx, status, task) \
         VALUES (?1, ?2, ?3, NULL, ?4, '') \
         ON CONFLICT(job_id, agent_id) DO NOTHING",
        params![job_id, agent_id, kind.as_str(), status.as_str()],
    )
    .await
    .with_context(|| format!("failed to upsert job agent {agent_id} for job {job_id}"))?;
    Ok(())
}

/// List the currently-running agent ids for a ticket (`status='launched'` roster rows
/// across its phase jobs) — drives comment routing to running agents.
pub(crate) async fn list_running_agents_for_ticket(
    conn: &Connection,
    ticket_id: &str,
) -> Result<Vec<String>> {
    let rows = conn
        .query(
            "SELECT a.agent_id FROM agents a \
             JOIN jobs j ON j.id = a.job_id \
             WHERE j.ticket_id = ?1 AND a.status = 'launched'",
            params![ticket_id],
        )
        .await
        .context("list running agents for ticket")?;
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        out.push(row.get::<String>(0)?);
    }
    Ok(out)
}

/// True when a job has a currently-running agent — the re-dispatch guard.
pub(crate) async fn job_has_launched_agents(conn: &Connection, job_id: &str) -> Result<bool> {
    Ok(conn
        .query_optional_cached(
            "SELECT 1 FROM agents WHERE job_id = ?1 AND status = 'launched' LIMIT 1",
            params![job_id],
            |_| Ok::<_, anyhow::Error>(1_i64),
        )
        .await?
        .is_some())
}

// An interrupted parallel round is resumable from its roster: not-Done slots are
// re-run with their stored per-slot `task`, while the phase body reconstructs the Done
// half from each slot's stored `outcome`.

/// Mark a phase job's stale `launched` roster rows as `failed` so the re-dispatch
/// guard sees no running agents while the rows — and their stored per-slot tasks —
/// survive for a slot-resume. Unlike [`clear_launched_agents_for_job`] this preserves
/// the not-Done slots. Used on pause-freeze and boot recovery.
pub(crate) async fn interrupt_phase_job_roster(conn: &Connection, job_id: &str) -> Result<()> {
    conn.execute(
        "UPDATE agents SET status = 'failed' WHERE job_id = ?1 AND status = 'launched'",
        params![job_id],
    )
    .await
    .context("mark interrupted phase roster rows failed")?;
    Ok(())
}

/// Re-arm a resumed round's not-Done roster slots as `launched` so the running-signal
/// blocks a concurrent re-drive and the Running Agents view lists them. Also touches the
/// job's `updated_at` — phase jobs are purge-eligible on stale updated_at. The stored
/// `idx`/`task` are preserved.
pub(crate) async fn rearm_roster_launched(
    conn: &Connection,
    job_id: &str,
    agent_ids: &[String],
) -> Result<()> {
    if agent_ids.is_empty() {
        return Ok(());
    }
    let placeholders = db::sql_in_placeholders(agent_ids.len());
    let mut params: Vec<Value> = vec![job_id.into()];
    params.extend(agent_ids.iter().map(|id| Value::from(id.as_str())));
    conn.execute(
        &format!(
            "UPDATE agents SET status = 'launched' WHERE job_id = ?1 AND agent_id IN ({placeholders})"
        ),
        params,
    )
    .await
    .context("re-arm resumed roster slots as launched")?;
    conn.execute(
        "UPDATE jobs SET updated_at = ?2 WHERE id = ?1",
        params![job_id, db::now()],
    )
    .await
    .context("touch job updated_at on slot resume")?;
    Ok(())
}

/// Clear a job's stale 'launched' roster rows after a stage-completion handoff; the job
/// row survives. For an interrupted PARALLEL round use [`interrupt_phase_job_roster`]
/// instead so the not-Done slots' stored tasks survive for a slot-resume.
pub(crate) async fn clear_launched_agents_for_job(conn: &Connection, job_id: &str) -> Result<()> {
    conn.execute(
        "DELETE FROM agents WHERE job_id = ?1 AND status = 'launched'",
        params![job_id],
    )
    .await
    .context("clear launched agents for job")?;
    Ok(())
}

/// Delete the jobs row (CASCADE destroys research_jobs child rows) inside an existing
/// transaction. The agents roster is cascade-deleted with it.
async fn delete_job_tx(tx: &TxGuard<'_>, job_id: &str) -> Result<()> {
    tx.execute("DELETE FROM jobs WHERE id = ?1", params![job_id])
        .await
        .with_context(|| format!("failed to delete job {job_id}"))?;
    Ok(())
}

/// The delivery address a round's result is routed to, from the round's own
/// identity parts — the ONE derivation shared by [`envelope_target`] (a
/// completed envelope) and the analyze cancel action's ownership check (a live
/// `jobs` row), so what a cancel treats as the caller's can never drift from
/// where the result would be delivered.
pub(crate) fn target_agent_id(
    custom: Option<&crate::Launch>,
    user_name: &str,
    role: &str,
    workspace_name: &str,
) -> String {
    if let Some(custom) = custom {
        return custom.agent_id.clone();
    }
    crate::session::resolve_agent_id(user_name, role, workspace_name)
}

/// Resolve the consumer-loop agent ID for an envelope (Manager role → the workspace Manager
/// session; pinned Assistant in a personal workspace → that user's assistant session).
/// `session::resolve_agent_id` already branches on `role == "manager"`, so this is the single
/// canonical form.
///
/// A custom-role launch's address is carried in the envelope's `custom_role` and returned
/// directly; boot replay uses the STORED `target_agent_id`, so both agree.
pub(crate) fn envelope_target(job: &AgentJob) -> String {
    target_agent_id(
        job.custom_role.as_ref(),
        &job.user_name,
        job.role.as_str(),
        &job.workspace_name,
    )
}

/// Caller identity + task of a job, read from the `jobs` row ALONE — a job whose child
/// row is missing (a crash between the spawn tx and a child insert) still resumes and
/// delivers to the original caller instead of being stranded.
pub(crate) struct JobCaller {
    pub task: String,
    pub role: String,
    pub user_name: String,
    pub channel: String,
    /// The custom-role launch the job was dispatched by, `None` for every built-in caller
    /// and for a NULL/unreadable value — a resume addresses the custom branch instead of a
    /// fabricated built-in address. Boxed to keep the resume-outcome enums small.
    pub custom_launch: Option<Box<crate::Launch>>,
}

/// Discriminated resume preamble: a sync caller never mistakes a gone job for a
/// drain-cut, or a transient DB read error for an abandon.
pub(crate) enum ResumePreamble {
    /// Caller identity + parsed role — the resume may proceed.
    Proceed(JobCaller, Role),
    /// Drain/shutdown active — quiet abort, the job row is untouched.
    DrainCut,
    /// The jobs row is absent — only via an explicit abandon (session /clear or workspace
    /// deletion) or a cancel whose own row deletion raced this resume; no terminalization
    /// happens. The old terminalize-on-missing compensation existed only for purges.
    Gone,
    /// The job row could not be READ (transient DB error) — NOT an abandon.
    /// The row is untouched; the error is carried for infra-failure reporting.
    Unreadable(anyhow::Error),
}

/// Terminal outcome of a resumed sync (analyze/implement) round.
pub(crate) enum SyncResumeOutcome {
    /// The round reached a terminal result (Ok text or Err) — the caller owns delivery and
    /// terminalization.
    Terminal(Role, JobCaller, anyhow::Result<String>),
    /// Drain-cut mid-resume — outcomes checkpointed, the job stays launched.
    DrainCut,
    /// The job row was gone between the ownership lookup and the resume — an explicit
    /// abandon, or a cancel that removed the row while this resume ran.
    Gone,
}

/// Parse a `jobs.custom_launch` value — the ONE policy for every reader: NULL and a
/// corrupted value both mean "no launch", the corruption warned and left to the
/// reader's refusal of that shape. A resume passes it on and is refused downstream in
/// the consumer loop's custom-role funnel; an ownership check derives the fabricated
/// `…_{role}` address, which no live custom/worker session carries (`Launch::agent_id`
/// is always a `role_…`/`rolerun_…`/`worker_…` address), so it refuses the row too.
pub(crate) fn parse_custom_launch(raw: Option<String>) -> Option<crate::Launch> {
    match raw {
        None => None,
        Some(raw) => match serde_json::from_str(&raw) {
            Ok(launch) => Some(launch),
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "jobs.custom_launch is unreadable — treating as absent",
                );
                None
            }
        },
    }
}

/// Load the task + caller identity of a job from the `jobs` row alone.
async fn job_caller(conn: &Connection, job_id: &str) -> Result<Option<JobCaller>> {
    conn.query_optional(
        "SELECT task, role, user_name, channel, custom_launch FROM jobs WHERE id = ?1",
        params![job_id],
        |r| {
            Ok::<_, anyhow::Error>(JobCaller {
                task: r.get::<String>(0)?,
                role: r.get::<String>(1)?,
                user_name: r.get::<String>(2)?,
                channel: r.get::<String>(3)?,
                custom_launch: parse_custom_launch(r.get::<Option<String>>(4)?).map(Box::new),
            })
        },
    )
    .await
    .context("load job caller")
}

/// A live analyze round of the caller's: the cancel action needs the row's ownership
/// AND the execution directory a cancelled round's synthetic search engine is named
/// after ([`crate::tools::delegation::release_placed_engine`]) — both from one read,
/// because neither may be looked up after the rows are gone.
pub(crate) struct CallerAnalyzeRound {
    /// The round's `place`, when it was dispatched with one.
    pub(crate) exec_dir: Option<String>,
}

/// The analyze round named by `job_id` when it is `caller`'s to stop: its `jobs` row
/// must be an analyze round whose delivery address ([`target_agent_id`]) is the caller's
/// session — the ONE derivation, so a cancel can never drift from where the result would
/// be delivered. The `kind = 'analyze'` filter is load-bearing: it refuses the `deep`
/// depth's `research` job and every worker round, however the id was named. An absent row
/// answers `None`; a row whose `custom_launch` cannot be read is read as launch-less.
pub(crate) async fn analyze_round_owned_by(
    conn: &Connection,
    job_id: &str,
    caller: &str,
) -> Result<Option<CallerAnalyzeRound>> {
    let row = conn
        .query_optional(
            "SELECT role, user_name, workspace_name, custom_launch, exec_dir FROM jobs \
             WHERE id = ?1 AND kind = 'analyze'",
            params![job_id],
            |r| {
                Ok::<_, anyhow::Error>((
                    target_agent_id(
                        parse_custom_launch(r.get::<Option<String>>(3)?).as_ref(),
                        &r.get::<String>(1)?,
                        &r.get::<String>(0)?,
                        &r.get::<String>(2)?,
                    ),
                    r.get::<Option<String>>(4)?,
                ))
            },
        )
        .await
        .context("read the round's own row")?;
    Ok(row.and_then(|(target, exec_dir)| {
        (target == caller).then_some(CallerAnalyzeRound { exec_dir })
    }))
}

/// Boot-resume preamble shared by the analyze/research resume paths. Order is
/// load-bearing: aborting-guard FIRST (quiet return — the job row stays for the
/// next boot), then job_caller, then the gone-missing note. Returns the caller
/// and parsed role, or None when the caller should quiet-return. The
/// `abort_site`/`missing_site` params inject each call site's label into its
/// log line so the two callers' texts stay distinguishable.
pub(crate) async fn resume_job_preamble(
    conn: &Connection,
    job_id: &str,
    abort_site: &str,
    missing_site: &str,
) -> Option<(JobCaller, Role)> {
    match resume_job_preamble_discrete(conn, job_id, abort_site, missing_site).await {
        ResumePreamble::Proceed(caller, caller_role) => Some((caller, caller_role)),
        // Quiet abort for boot-resume paths: the row is untouched (drain),
        // already gone (abandon), or unreadable (transient DB error — retried
        // at the next boot).
        ResumePreamble::DrainCut | ResumePreamble::Gone | ResumePreamble::Unreadable(_) => None,
    }
}

/// Discriminating core of [`resume_job_preamble`]: same order and log texts, but the
/// caller gets an explicit [`ResumePreamble`] so it can tell a gone job from a drain-cut.
pub(crate) async fn resume_job_preamble_discrete(
    conn: &Connection,
    job_id: &str,
    abort_site: &str,
    missing_site: &str,
) -> ResumePreamble {
    if crate::shutdown::aborting() {
        tracing::info!(job = %job_id, "{abort_site} aborted — drain/shutdown in progress");
        return ResumePreamble::DrainCut;
    }
    match job_caller(conn, job_id).await {
        Ok(Some(caller)) => {
            let mut caller_role =
                std::str::FromStr::from_str(&caller.role).unwrap_or(Role::Manager);
            // A row that carries a launch resumes as its custom branch: the persisted launch is the
            // address authority, never the tool's own construction role.
            caller_role = caller_role.for_launch(caller.custom_launch.as_deref());
            ResumePreamble::Proceed(caller, caller_role)
        }
        // The row is gone: an explicit abandon, or a cancel, raced this resume.
        Ok(None) => {
            tracing::info!(job = %job_id, "{missing_site}: job row gone (abandoned or cancelled) — skipping resume");
            ResumePreamble::Gone
        }
        // A transient DB read error is NOT an abandon — warn and surface it as an infra failure
        // (fail-safe: no deletion, the row is untouched either way).
        Err(e) => {
            tracing::warn!(job = %job_id, error = %e, "{missing_site}: failed to read job row — skipping resume");
            ResumePreamble::Unreadable(e)
        }
    }
}

/// Read a job's boot-resume retry count (0 = never boot-resumed) — the real resume
/// signal behind the research report's telemetry gate.
pub(crate) async fn job_retry_count(conn: &Connection, job_id: &str) -> i64 {
    match conn
        .query_optional(
            "SELECT retry_count FROM jobs WHERE id = ?1",
            params![job_id],
            |r| r.get::<i64>(0),
        )
        .await
    {
        Ok(Some(n)) => n,
        Ok(None) => 0,
        Err(e) => {
            warn!(job = %job_id, error = %e, "Failed to read job retry_count — assuming 0");
            0
        }
    }
}

/// `RowStatus::Done` as this module's SQL spells it — `as_str` is a `const fn`, so the terminal
/// status has one spelling here and cannot drift from the enum.
const DONE_STATUS: &str = RowStatus::Done.as_str();

/// Load all non-terminal jobs (launched|failed) for the boot scan.
async fn list_active_jobs(conn: &Connection) -> Result<Vec<JobRow>> {
    let rows = conn
        .query(
            &format!(
                "SELECT {JOB_COLUMNS} FROM jobs \
                 WHERE status != '{DONE_STATUS}' ORDER BY created_at"
            ),
            (),
        )
        .await
        .context("list active jobs")?;
    rows.iter().map(job_row_from).collect()
}

pub(crate) async fn list_agents_for_job(conn: &Connection, job_id: &str) -> Result<Vec<AgentRow>> {
    let rows = conn
        .query(
            &format!("SELECT {AGENT_COLUMNS} FROM agents WHERE job_id = ?1 ORDER BY idx"),
            params![job_id],
        )
        .await
        .context("list agents for job")?;
    rows.iter().map(agent_row_from).collect()
}

/// The roster agent ids of every job that has not been terminalized, minus the slots
/// that already finished: the ids a cut round resumes IN PLACE from ([`RowStatus::Done`]
/// slots are reconstructed from their stored outcomes). A purged or terminalized job
/// drops out — the same non-terminal set [`list_active_jobs`] takes.
pub(crate) async fn resumable_roster_agent_ids(conn: &Connection) -> Result<Vec<String>> {
    let rows = conn
        .query(
            &format!(
                "SELECT DISTINCT a.agent_id FROM agents a \
                 WHERE a.job_id IN (SELECT id FROM jobs WHERE status != '{DONE_STATUS}') \
                 AND a.status != '{DONE_STATUS}'"
            ),
            (),
        )
        .await
        .context("list the roster agent ids of non-terminal jobs")?;
    Ok(rows
        .iter()
        .filter_map(|row| row.get::<String>(0).ok())
        .collect())
}

/// Waits for the drain flag, then polls the agent registry AND the non-agent call registry. Clean
/// exit: no agent registered AND no orchestrator-only LLM call in flight (the research orchestrator
/// holds a whole-run guard so the token never fires into an inter-phase window) → fires the global
/// token, which the GUI subscription turns into window exit. Cap expiry (10 min): force-cancel.
///
/// The jobs table is NOT polled: drain-cut rounds leave their jobs status='launched' for boot
/// resume, so a count-based wait would hold the window open for the full cap.
pub async fn run_drain_watch() {
    use crate::shutdown::{force_cancel, shutdown, shutdown_token};
    use std::time::Instant;

    // Wait for the drain to begin (or an already-fired token).
    let token = shutdown_token();
    tokio::select! {
        () = crate::shutdown::drain_wait() => {}
        () = token.cancelled() => return,
    }
    if shutdown_token().is_cancelled() {
        return;
    }

    let start = Instant::now();
    loop {
        // Clean-exit requires BOTH the agent registry AND the non-agent call
        // registry to be empty: orchestrator-only LLM calls (analyze consolidation,
        // research synthesis, joint-verdict grouping) run with no registered
        // agents — firing the token the instant the registry empties would
        // abort an in-flight call via the provider token race the design
        // Drain-cut leftovers are covered: cut rounds leave their agents unregistered AND
        // their jobs status='launched', so the registries drain without them.
        if crate::agent::registry::AGENT_REGISTRY.list().is_empty()
            && crate::agent::registry::NON_AGENT_CALLS.list().is_empty()
        {
            info!("Drain complete — no in-flight agents or orchestrator calls; exiting");
            shutdown();
            return;
        }
        if start.elapsed() >= Duration::from_secs(DRAIN_CAP_SECS) {
            warn!("Drain cap ({DRAIN_CAP_SECS}s) reached — force-cancelling in-flight work");
            crate::agent::registry::AGENT_REGISTRY.shutdown_all();
            force_cancel();
            return;
        }
        if shutdown_token().is_cancelled() {
            return;
        }
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
}

/// Load all outstanding pending_jobs rows (boot replay + drain-recovery).
pub(crate) async fn list_pending_jobs(conn: &Connection) -> Result<Vec<PendingJobRow>> {
    let rows = conn
        .query(
            "SELECT id, target_agent_id, envelope, created_at \
             FROM pending_jobs ORDER BY created_at",
            (),
        )
        .await
        .context("list pending jobs")?;
    rows.iter().map(pending_row_from).collect()
}

/// Delete a delivered pending_jobs row (consumer-confirmed).
pub(crate) async fn delete_pending_job(conn: &Connection, id: &str) -> Result<()> {
    conn.execute("DELETE FROM pending_jobs WHERE id = ?1", params![id])
        .await
        .context("delete pending job")?;
    Ok(())
}

/// Delete every deferred envelope addressed to `target_agent_id`, returning how many
/// rows were dropped. The deliberate-stop path is the ONE place that drops durable
/// envelopes by address, and it waives the at-least-once guarantee (a stopped launch
/// must not be replayed at boot); every other deletion stays by row id.
#[expect(clippy::cast_possible_truncation)] // u64 row count fits usize on all supported targets
pub(crate) async fn delete_pending_jobs_for(target_agent_id: &str) -> Result<usize> {
    let conn = &crate::session::store().conn;
    let deleted = conn
        .execute(
            "DELETE FROM pending_jobs WHERE target_agent_id = ?1",
            params![target_agent_id],
        )
        .await
        .context("delete pending jobs for agent")?;
    info!(
        target_agent_id,
        count = deleted,
        "dropped deferred envelopes for a stopped launch"
    );
    Ok(deleted as usize)
}

/// Outcome of a boot recovery scan: jobs selected for resume.
///
/// Ticket phase jobs are NOT resumed at boot — the single puller re-drives a ticket in
/// a working phase (its row is left in place with stale roster rows cleared). Only the
/// non-ticket envelope kinds carry their own resume semantics.
pub(crate) enum ResumableJob {
    Research {
        job_id: String,
        workspace_name: String,
    },
    Analyze {
        job_id: String,
        workspace_name: String,
        /// The recorded target directory for the round; `None` = the caller's
        /// own workspace.
        exec_dir: Option<String>,
    },
    Implement {
        job_id: String,
        workspace_name: String,
        /// The recorded target directory for the round; `None` = the caller's
        /// own workspace.
        exec_dir: Option<String>,
    },
    /// A research-run cleanup Sanitation agent interrupted by a crash. The
    /// jobs row id == the run id, so the row is the cleanup's resume marker
    /// and holds the folder until the cleanup completes.
    ResearchCleanup {
        job_id: String,
        workspace_name: String,
    },
}

/// Strip the `<timestamp>…</timestamp>` wrapper from a persisted user message,
/// recognizing both the legacy prefix format and the current suffix format. Returns the
/// input unchanged when neither is present. The timestamp body is validated against the
/// [`crate::session::render_timestamp`] shape so content that merely mimics the wrapper
/// is never mis-stripped. Residual: a suffix message whose content begins with a
/// legacy-shaped block is byte-identical to the legacy format and strips from the front
/// — unreachable in practice, failing toward duplicate delivery (never loss).
fn strip_timestamp_wrapper(content: &str) -> &str {
    // Suffix format — only for non-legacy-prefixed messages: a legacy message whose content
    // ends with a timestamp-shaped block must not be stripped from the tail.
    if !content.starts_with("<timestamp>")
        && let Some(body) = content.strip_suffix("</timestamp>")
        && let Some(start) = body.rfind("\n\n<timestamp>")
        && is_timestamp_body(&body[start + "\n\n<timestamp>".len()..])
    {
        return &body[..start];
    }
    // Legacy prefix format — requires the exact `\n\n` separator so a suffix-format message
    // whose content merely STARTS with a timestamp block is never mis-stripped.
    if let Some(body) = content.strip_prefix("<timestamp>")
        && let Some(end) = body.find("</timestamp>")
        && is_timestamp_body(&body[..end])
        && let Some(after) = body[end..].strip_prefix("</timestamp>\n\n")
    {
        return after;
    }
    content
}

/// Whether `s` matches the `%Y-%m-%d %H:%M:%S (%Z)` shape of
/// [`crate::session::render_timestamp`]. The tz must be non-empty — an empty one would
/// fail validation and boot-replay dedup would degrade to duplicate delivery.
fn is_timestamp_body(s: &str) -> bool {
    let Some((datetime, tz)) = s.strip_suffix(')').and_then(|rest| rest.rsplit_once(" (")) else {
        return false;
    };
    !tz.is_empty() && chrono::NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").is_ok()
}

/// Dedup check: was the pending envelope already appended to the target session? Every
/// user message persists with a `<timestamp>…</timestamp>` block, so exact equality
/// would always be false — a SUFFIX match after stripping the wrapper is required. Plus
/// a created_at tiebreaker: skip only if pending.created_at <= the last user message's
/// created_at (closes the silent at-most-once hole for identical consecutive messages).
/// Both are compared via chrono parsing rather than lexical strings.
async fn pending_already_appended(conn: &Connection, row: &PendingJobRow) -> bool {
    let Ok(Some((last_content, last_created))) = conn
        .query_optional(
            "SELECT content, created_at FROM sessions \
             WHERE agent_id = ?1 AND role = 'user' ORDER BY id DESC LIMIT 1",
            params![row.target_agent_id.clone()],
            |r| Ok::<_, anyhow::Error>((r.get::<String>(0)?, r.get::<String>(1)?)),
        )
        .await
    else {
        return false;
    };
    let Ok(envelope) = serde_json::from_str::<AgentJob>(&row.envelope) else {
        return false;
    };
    // chrono parse beats raw lexical comparison (AutoSi trailing-zero
    // trimming can theoretically misorder sub-microsecond-different
    // timestamps); lexical order remains the fallback if either string is
    // unparseable (unreachable in practice — both come from db::now()).
    let appended_before = match (
        crate::db::parse_utc_timestamp(&row.created_at).ok(),
        crate::db::parse_utc_timestamp(&last_created).ok(),
    ) {
        (Some(row_ts), Some(last_ts)) => row_ts <= last_ts,
        _ => row.created_at <= last_created,
    };
    strip_timestamp_wrapper(&last_content).ends_with(&envelope.content) && appended_before
}

/// (0) Replay outstanding pending_jobs — the boot reclaim path for durable envelopes
/// (at-least-once delivery). Runs before anything that could purge.
/// Dedup semantics: the suffix + created_at tiebreaker closes the
/// listener-interleaving race — the scan and channel listeners may run
/// concurrently, the consumer serializes per agent.
async fn replay_pending_jobs(conn: &Connection) -> Result<usize> {
    let rows = list_pending_jobs(conn).await?;
    let mut replayed = 0usize;
    for row in &rows {
        let Ok(mut job) = serde_json::from_str::<AgentJob>(&row.envelope) else {
            warn!(pending_job = %row.id, "Pending job envelope unreadable — skipping");
            continue;
        };
        job.pending_job_id = Some(row.id.clone());
        if pending_already_appended(conn, row).await {
            // The message already reached the session — dedup prevents a
            // duplicate append. The row is reclaimed here (delivery complete;
            // response recovery is the dead-session poller's domain).
            debug!(pending_job = %row.id, "Pending job already appended — skipping");
            if let Err(e) = delete_pending_job(conn, &row.id).await {
                warn!(pending_job = %row.id, error = %e, "Failed to delete deduped pending job");
            }
            continue;
        }
        // Execution-time invariant: re-pin pinned roles (Assistant)
        // to the user's personal workspace; a pinned role with an empty user is
        // refused and the poisoned envelope deleted so it is not replayed forever.
        let Some(workspace_name) =
            crate::users::enforce_personal_pinning(job.role, &job.workspace_name, &job.user_name)
        else {
            error!(
                pending_job = %row.id,
                role = %job.role.as_str(),
                workspace = %job.workspace_name,
                "Pending job replay: pinned role with empty user — dropping poisoned envelope"
            );
            if let Err(e) = delete_pending_job(conn, &row.id).await {
                warn!(pending_job = %row.id, error = %e, "Failed to delete refused pending job");
            }
            continue;
        };
        job.workspace_name = workspace_name;
        // Crash-window cleanup dispatch: a genuinely-undelivered research-completion envelope
        // whose run has NO `research_cleanup` row means the daemon died between
        // complete_durable_job and dispatch_research_cleanup. Create the durable row NOW (the
        // dedup marker + folder-hold); the `research_cleanup` boot-scan arm is the SOLE
        // dispatcher (spawning here would double-run the same `cleanup_{run_id}` id).
        // RUN-FOLDER EXISTENCE is the crash-window classifier: a folder still present means the
        // cleanup never ran; a folder gone means it COMPLETED in a previous lifetime while the
        // envelope stayed undelivered — no re-dispatch, hence no duplicate LLM round.
        if job.kind == MessageKind::ResearchResult
            && !crate::research_cleanup::research_cleanup_row_exists(conn, &row.id)
                .await
                .unwrap_or(true)
        {
            crate::research_cleanup::dispatch_cleanup_for_pending_envelope(&row.id, &job).await;
        }
        if !pending_row_exists(conn, &row.id).await {
            debug!(
                pending_job = %row.id,
                "Pending job discarded by a cancel — not replayed",
            );
            continue;
        }
        // The last look this path can take: a discarded round's queued row is its only trace
        // (its invocation has long exited), and a removal committing between the read above and
        // the route below is the one window this replay cannot close.
        // The dedup above is the authoritative "in session" check: a row whose content is NOT in
        // the session was never appended — route the FULL content. Replaying empty here would
        // silently lose the envelope forever (at-most-once violation).
        crate::agent::message_router::route(&row.target_agent_id, job);
        replayed += 1;
    }
    Ok(replayed)
}

/// Stale-job purge.
///
/// Cutoff = 8h. Deletes only stale TICKET-PHASE jobs whose updated_at predates the cutoff AND
/// whose roster agents' sessions are all stale too (live sessions referenced by unfinished jobs
/// are NEVER purged — the agents table IS the marker). The puller re-creates a purged job on the
/// next tick; paused workspaces' phase jobs are purge-immune. Unfinished non-phase jobs are
/// never time-deleted.
pub async fn purge_stale_jobs(cutoff: &str) -> Result<u64> {
    let conn = &crate::session::store().conn;

    // A paused (frozen) phase job is purge-immune: it holds the workspace's running slot.
    // The kind filter mirrors `is_ticket_phase_kind`.
    let phase_kinds = WORKING_PHASES
        .iter()
        .map(|phase| format!("'{}'", phase.as_ref()))
        .collect::<Vec<_>>()
        .join(", ");
    let rows = conn
        .query(
            &format!(
                "SELECT j.id, j.workspace_name \
                 FROM jobs j \
                 WHERE j.updated_at < ?1 \
                   AND j.kind IN ({phase_kinds}) \
                   AND NOT EXISTS ( \
                     SELECT 1 FROM agents a \
                     JOIN session_metadata sm ON sm.agent_id = a.agent_id \
                     WHERE a.job_id = j.id AND sm.last_activity >= ?1)"
            ),
            params![cutoff],
        )
        .await
        .context("select stale jobs for purge")?;
    if rows.is_empty() {
        return Ok(0);
    }
    // Paused workspace names: a frozen phase job must survive the stale purge. Best-effort
    // — a `workspaces` read failure falls back to purging.
    let paused_ws: std::collections::HashSet<String> = match crate::workspace::store().list().await
    {
        Ok(list) => list
            .into_iter()
            .filter(|w| w.paused)
            .map(|w| w.name)
            .collect(),
        Err(_) => std::collections::HashSet::new(),
    };
    let mut purge_ids: Vec<String> = Vec::with_capacity(rows.len());
    for row in &rows {
        let id: String = row.get(0)?;
        let workspace_name: String = row.get(1)?;
        // A paused workspace's phase job is frozen — purge-immune.
        if paused_ws.contains(&workspace_name) {
            continue;
        }
        purge_ids.push(id);
    }
    if purge_ids.is_empty() {
        return Ok(0);
    }

    // DELETE FROM jobs (CASCADE removes roster rows; the engineer anchor
    // survives — NULL FK child).
    let tx = conn.begin_tx().await?;
    let mut deleted = 0usize;
    for id in &purge_ids {
        delete_job_tx(&tx, id).await?;
        deleted += 1;
    }
    tx.commit().await?;
    if deleted > 0 {
        tracing::debug!(deleted, "Purged stale jobs");
    }
    Ok(deleted as u64)
}

/// Is this `jobs.kind` one of the ticket working-phase kinds? A phase job is
/// named after its phase ([`SpawnChild::kind_str`]), so this is a check against
/// the working phase set itself rather than a second vocabulary list.
#[must_use]
fn is_ticket_phase_kind(kind: &str) -> bool {
    WORKING_PHASES.iter().any(|phase| phase.as_ref() == kind)
}

/// Sync jobs (mode='sync') are settled by the owner's live resume-completion step
/// ([`find_owned_launched_jobs`]) — boot resume must never race it. Research jobs always
/// spawn with mode='async', so only the analyze half can fire.
fn skip_sync_job(job: &JobRow) -> bool {
    if job.mode == JobMode::Sync {
        info!(
            job = %job.id,
            caller = ?job.caller_agent_id,
            "sync job — caller resumes it; skipping boot resume",
        );
        true
    } else {
        false
    }
}

/// Binding 3: a resume-eligible job whose workspace can no longer be resolved is left in place,
/// not terminalized — the boot loop skips it without bumping retry_count or touching the roster.
///
/// Not reported as a failure: the row is parked, not lost, and a merely unmounted workspace resumes
/// on a later boot (a custom role's launch reaches the consumer loop instead).
async fn workspace_unresolvable(job: &JobRow) -> bool {
    if crate::users::resolve_workspace(&job.workspace_name)
        .await
        .is_ok_and(|ws| ws.is_some())
    {
        return false;
    }
    warn!(
        job = %job.id,
        workspace = %job.workspace_name,
        "workspace unresolvable — job stays launched, skipped (no boot resume, no checkpoint)",
    );
    true
}

/// Boot recovery scan: first statement of run_management. Order: (0) replay pending_jobs; (1) one
/// scan over the active jobs — ticket phase jobs only get their stale launched roster cleared (the
/// puller re-drives them), the research/analyze/implement/research_cleanup kinds resume, and
/// temp_cleanup rows are terminalized. An unresolvable workspace skips in place (binding 3).
///
/// Every resumed job gets updated_at = now (the ONLY protection for the pre-first-commit window)
/// and retry_count + 1.
#[expect(clippy::cast_possible_truncation)]
pub(crate) async fn recover_from_restart() -> Result<Vec<ResumableJob>> {
    let start = std::time::Instant::now();
    let conn = &crate::session::store().conn;

    // (0) Deliverable replay — before anything that could purge.
    let replayed = replay_pending_jobs(conn).await?;

    // (1) Scan over the active jobs. Ticket phase jobs are NOT kind-discriminated resume
    // targets — the single puller re-drives them; we only clear their stale launched roster
    // rows so the puller re-dispatches. The remaining kinds resume or terminalize in line.
    let jobs = list_active_jobs(conn).await?;
    let mut resumable: Vec<ResumableJob> = Vec::new();
    let mut resumed_other = 0usize;
    for job in &jobs {
        if is_ticket_phase_kind(&job.kind) {
            // A ticket phase job interrupted by a crash: 'launched' roster rows from the previous
            // process are marked 'failed' (NOT deleted) so the puller re-dispatches a slot-resume
            // that reuses the stored per-slot tasks and already-Done outcomes.
            if let Err(e) = interrupt_phase_job_roster(conn, &job.id).await {
                warn!(
                    job = %job.id,
                    ticket = %job.ticket_id.as_deref().unwrap_or("?"),
                    error = %e,
                    "Failed to mark stale launched agents on ticket phase boot scan",
                );
            }
        } else if job.kind == "research" || job.kind == "analyze" {
            // Resume at the roster/state level (dispatch re-enters the
            // orchestrator with the stored task). Always bump retry_count.
            if skip_sync_job(job) || workspace_unresolvable(job).await {
                continue;
            }
            let kind = job.kind.as_str();
            let _ = checkpoint_job(conn, &job.id, job.retry_count + 1).await;
            resumable.push(if kind == "research" {
                ResumableJob::Research {
                    job_id: job.id.clone(),
                    workspace_name: job.workspace_name.clone(),
                }
            } else {
                ResumableJob::Analyze {
                    job_id: job.id.clone(),
                    workspace_name: job.workspace_name.clone(),
                    exec_dir: job.exec_dir.clone(),
                }
            });
            resumed_other += 1;
        } else if job.kind == "implement" {
            // A single-worker implement round interrupted by a crash: resume it
            // like any other durable envelope kind. The worker roster row holds
            // the terminal outcome; the job row holds the caller identity.
            if skip_sync_job(job) || workspace_unresolvable(job).await {
                continue;
            }
            let _ = checkpoint_job(conn, &job.id, job.retry_count + 1).await;
            resumable.push(ResumableJob::Implement {
                job_id: job.id.clone(),
                workspace_name: job.workspace_name.clone(),
                exec_dir: job.exec_dir.clone(),
            });
            resumed_other += 1;
        } else if job.kind == "research_cleanup" {
            // A research-run cleanup Sanitation agent interrupted by a crash: resume it like any
            // durable job. The folder stays held until the resumed tail releases it; a row removed
            // by the dump-guarded cancel sweep deliberately leaves a dump-holding folder.
            if workspace_unresolvable(job).await {
                continue;
            }
            let _ = checkpoint_job(conn, &job.id, job.retry_count + 1).await;
            resumable.push(ResumableJob::ResearchCleanup {
                job_id: job.id.clone(),
                workspace_name: job.workspace_name.clone(),
            });
            resumed_other += 1;
        } else if job.kind == "temp_cleanup" {
            // A periodic temp cleaner interrupted by a crash: the cleanup is best-effort and the
            // next due pass re-runs it, so a leftover row is terminalized (never resumed). The
            // cleaner's synthetic workspace has no `workspaces` row, so resuming would hit
            // run_management's unresolvable-workspace path.
            info!(
                job = %job.id,
                "Temp cleaner row left over from a previous lifetime — terminalizing (no resume)",
            );
            let _ = terminalize_job(conn, &job.id).await;
        } else {
            warn!(job = %job.id, kind = %job.kind, "Unknown job kind — skipping");
        }
    }

    let elapsed = start.elapsed();
    info!(
        duration_ms = elapsed.as_millis() as u64,
        resumed_other,
        replayed_pending = replayed,
        "Boot recovery scan complete",
    );

    // Boot sweep for session pins (S5 terminal deletion): pins for tickets already in a
    // terminal phase are removed so the TTL guard stops protecting their sessions (the
    // 5-min archive loop re-runs this — boot just catches up after downtime).
    let _ = purge_terminal_session_pins().await;

    Ok(resumable)
}

/// Deterministic session-pin agent ID: the per-ticket accumulated session
/// `ticket_{ticket_id}_{role}`, permanently job_id = NULL.
#[must_use]
pub(crate) fn session_pin_id(ticket_id: &str, role: Role) -> String {
    crate::session::ticket_agent_id(ticket_id, role.as_str())
}

/// Upsert the session pin for `role` (engineer/sanitation). NEVER sets job_id (that removes the
/// row from the partial-index scope → later NULL insert no longer conflicts → duplicate anchor).
/// The DDL and this write use the IDENTICAL `job_id IS NULL` form, so it can never touch the
/// job-bound roster row with the same agent id.
///
/// The update half is the normal path: the claim-time write creates the pin and every later
/// `run_stage_agent` re-upserts it, each bounce/reset round included.
pub(crate) async fn upsert_session_pin(
    conn: &Connection,
    ticket_id: &str,
    task: &str,
    status: RowStatus,
    role: Role,
) -> Result<()> {
    let pin_id = session_pin_id(ticket_id, role);
    conn.upsert_row(
        "UPDATE agents SET status = ?1, task = ?2, outcome = NULL \
         WHERE agent_id = ?3 AND job_id IS NULL",
        || params![status.as_str(), task, pin_id.as_str()],
        "INSERT INTO agents (job_id, agent_id, kind, idx, status, outcome, task) \
         VALUES (NULL, ?1, ?4, NULL, ?2, NULL, ?3) \
         ON CONFLICT(agent_id) WHERE job_id IS NULL DO NOTHING",
        params![pin_id.as_str(), status.as_str(), task, role.as_str()],
    )
    .await
    .with_context(|| format!("failed to upsert {role} session pin for ticket {ticket_id}"))?;
    Ok(())
}

/// Parse `ticket_{ticket_id}_{role}` — the ticket id is everything before the
/// final `_{role}` (workspace names allow underscores, so ticket ids like
/// `my_ws-42` are valid — only the final suffix is stripped).
#[must_use]
fn session_pin_ticket_id(agent_id: &str, role: Role) -> Option<String> {
    agent_id
        .strip_prefix("ticket_")
        .and_then(|rest| {
            rest.strip_suffix(role.as_str())
                .and_then(|r| r.strip_suffix('_'))
        })
        .filter(|id| !id.is_empty())
        .map(str::to_string)
}

/// Terminal deletion of session-pins (S5 — permanently-NULL seats): pins protect the
/// accumulated engineer/sanitation session across bounce rounds and re-attempts. Once
/// the ticket reaches a terminal phase (no future bounces/resets), the pin is
/// removed so the TTL guard stops protecting the session. Centralized here (5-min
/// archive loop + boot sweep). Idempotent: parse ticket_id from the pin agent_id,
/// phase-check on the board side, delete.
pub(crate) async fn purge_terminal_session_pins() -> usize {
    let conn = &crate::session::store().conn;
    let Ok(rows) = conn
        .query(
            "SELECT agent_id, kind FROM agents WHERE job_id IS NULL \
             AND kind IN ('engineer', 'sanitation')",
            (),
        )
        .await
    else {
        return 0;
    };
    let mut deleted = 0usize;
    // Guarded access — the purge may run before BOARD is initialized (the archive loop
    // checks later in the same tick; boot sweep runs after init).
    let board_ready = crate::pipeline::board::BOARD.get().is_some();
    for row in &rows {
        let Ok(agent_id) = row.get::<String>(0) else {
            continue;
        };
        let Ok(kind) = row.get::<String>(1) else {
            continue;
        };
        let role = match kind.as_str() {
            "engineer" => Role::Engineer,
            _ => Role::Sanitation,
        };
        let ticket_id = session_pin_ticket_id(&agent_id, role);
        let Some(ticket_id) = ticket_id else {
            continue;
        };
        let terminal = board_ready
            && crate::pipeline::board::store()
                .get_ticket_phase(&ticket_id)
                .await
                .is_ok_and(|p| p.is_some_and(|ph| ph.is_terminal()));
        if !terminal {
            continue;
        }
        match conn
            .execute(
                "DELETE FROM agents WHERE agent_id = ?1 AND job_id IS NULL",
                params![agent_id.clone()],
            )
            .await
        {
            Ok(_) => deleted += 1,
            Err(e) => {
                warn!(
                    ticket = %ticket_id,
                    agent = %agent_id,
                    error = %e,
                    "Failed to delete terminal session pin",
                );
            }
        }
    }
    if deleted > 0 {
        // Debug: a routine count of pins reclaimed — a failed delete keeps its
        // warn record above.
        debug!(deleted, "Removed session pins for terminal tickets");
    }
    deleted
}

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

    /// A dispatch whose id is already cancelled commits no row: the cancel gate inside
    /// `spawn_job`'s transaction refuses it, roster included.
    #[serial_test::serial(recover_from_restart)]
    #[tokio::test]
    async fn spawn_job_refuses_a_cancelled_rounds_row() {
        crate::util::test::init_management_test_stores().await;
        let conn = &crate::session::store().conn;
        let job_id = "spawn_gate_cancelled_round";
        let _cancel_guard = crate::round_cancel::register(job_id, None);
        crate::round_cancel::cancel(job_id);

        spawn_job(
            conn,
            job_id,
            "task",
            "spawn_gate_ws",
            "caller",
            "telegram",
            crate::Role::Engineer,
            &[NewAgent {
                agent_id: "spawn_gate_agent".to_string(),
                kind: AgentKind::Analyst,
                idx: Some(0),
                task: "task".to_string(),
            }],
            &SpawnChild::Analyze,
            None,
            None,
            None,
        )
        .await
        .unwrap();

        let row = conn
            .query(
                "SELECT 1 FROM jobs WHERE id = ?1",
                crate::db::params![job_id],
            )
            .await
            .unwrap();
        assert!(
            row.is_empty(),
            "a cancelled round must not commit its jobs row"
        );
        let roster = conn
            .query(
                "SELECT 1 FROM agents WHERE job_id = ?1",
                crate::db::params![job_id],
            )
            .await
            .unwrap();
        assert!(
            roster.is_empty(),
            "the roster is written in the same transaction, so it goes with it"
        );

        // The gate is scoped to the analyze child: a research run's id is reused
        // by the cleanup row its cancelled-run handoff still has to write, so
        // that write is not refused by the run's fired signal.
        let cleanup_id = "spawn_gate_cleanup_round";
        let _cleanup_guard = crate::round_cancel::register(cleanup_id, None);
        crate::round_cancel::cancel(cleanup_id);
        spawn_job(
            conn,
            cleanup_id,
            "cleanup task",
            "spawn_gate_ws",
            "",
            "",
            crate::Role::Sanitation,
            &[],
            &SpawnChild::ResearchCleanup,
            None,
            None,
            None,
        )
        .await
        .unwrap();
        let cleanup_row = conn
            .query(
                "SELECT 1 FROM jobs WHERE id = ?1",
                crate::db::params![cleanup_id],
            )
            .await
            .unwrap();
        assert_eq!(
            cleanup_row.len(),
            1,
            "a cancelled run's cleanup row is still written"
        );
        conn.execute(
            "DELETE FROM jobs WHERE id IN (?1, ?2)",
            crate::db::params![job_id, cleanup_id],
        )
        .await
        .unwrap();
    }

    /// Insert a minimal ticket row so a [`SpawnChild::Phase`] job's `ticket_id` FK resolves.
    async fn seed_ticket(conn: &crate::db::Connection, ticket_id: &str, ws_name: &str) {
        let now = crate::db::now();
        conn.execute(
            "INSERT INTO tickets (id, title, description, workspace_name, created_at, updated_at) \
             VALUES (?1, 'title', 'desc', ?2, ?3, ?3)",
            crate::db::params![ticket_id, ws_name, now],
        )
        .await
        .unwrap();
    }

    async fn status_retry(conn: &crate::db::Connection, job_id: &str) -> (String, i64) {
        let rows = conn
            .query(
                "SELECT status, retry_count FROM jobs WHERE id = ?1",
                crate::db::params![job_id],
            )
            .await
            .unwrap();
        assert_eq!(rows.len(), 1, "job row exists for {job_id}");
        (
            rows[0].get::<String>(0).unwrap(),
            rows[0].get::<i64>(1).unwrap(),
        )
    }

    /// (f) Boot recovery resumes only async analyze/implement/research jobs. Sync
    /// caller-owned jobs are skipped — their caller session re-drives them — so they stay
    /// `launched` with `retry_count` untouched; the async job is check-pointed.
    ///
    /// Serial with the other `recover_from_restart` test: a concurrent boot scan rescans the
    /// shared `jobs` table and check-points this test's async analyze a second time.
    #[serial_test::serial(recover_from_restart)]
    #[tokio::test]
    async fn boot_recovery_skips_caller_owned_jobs() {
        crate::util::test::init_management_test_stores().await;
        let conn = &crate::session::store().conn;
        let ws_name = "boot_recovery_ws";
        // Binding 3: boot recovery skips (not terminalizes) a resume-eligible
        // job whose workspace is unresolvable — so the spawns need a managed
        // workspace for the async analyze to be check-pointed.
        crate::util::test::create_test_workspace("/tmp/boot_recovery_ws", ws_name).await;

        for (job_id, kind, child, caller, exec_dir) in [
            (
                "owned_analyze",
                AgentKind::Analyst,
                SpawnChild::Analyze,
                Some("pin_a"),
                None,
            ),
            (
                "owned_implement",
                AgentKind::Worker,
                SpawnChild::Implement,
                Some("pin_b"),
                None,
            ),
            (
                "null_analyze",
                AgentKind::Analyst,
                SpawnChild::Analyze,
                None,
                // A targeted round: the recorded directory must survive the boot
                // scan so the resume runs in the same directory.
                Some("/tmp/boot_recovery_target"),
            ),
        ] {
            spawn_job(
                conn,
                job_id,
                "task",
                ws_name,
                "caller",
                "telegram",
                crate::Role::Engineer,
                &[NewAgent {
                    agent_id: format!("{job_id}_agent"),
                    kind,
                    idx: Some(0),
                    task: "task".to_string(),
                }],
                &child,
                caller,
                exec_dir,
                None,
            )
            .await
            .unwrap();
        }

        // Spawn derives mode from the caller pin (sync ⇔ pin present).
        let modes: Vec<String> = conn
            .query(
                "SELECT mode FROM jobs WHERE id IN ('owned_analyze','owned_implement','null_analyze') ORDER BY id",
                (),
            )
            .await
            .unwrap()
            .iter()
            .map(|r| r.get::<String>(0).unwrap())
            .collect();
        assert_eq!(
            modes,
            ["async".to_string(), "sync".to_string(), "sync".to_string()],
            "spawn derives mode from the caller pin (sync ⇔ pin present)"
        );

        let resumable = recover_from_restart().await.unwrap();

        assert!(
            resumable.iter().any(
                |r| matches!(r, ResumableJob::Analyze { job_id, .. } if job_id == "null_analyze")
            ),
            "the async analyze is selected for boot resume"
        );
        assert!(
            resumable.iter().any(|r| matches!(
                r,
                ResumableJob::Analyze {
                    job_id,
                    exec_dir: Some(dir),
                    ..
                } if job_id == "null_analyze" && dir == "/tmp/boot_recovery_target"
            )),
            "the targeted round's recorded directory survives the boot scan"
        );
        assert!(
            !resumable.iter().any(
                |r| matches!(r, ResumableJob::Analyze { job_id, .. } if job_id == "owned_analyze")
            ),
            "the sync caller-owned analyze is not boot-resumed"
        );
        assert!(
            !resumable.iter().any(
                |r| matches!(r, ResumableJob::Implement { job_id, .. } if job_id == "owned_implement")
            ),
            "the sync caller-owned implement is not boot-resumed"
        );

        // Sync jobs stay launched with retry_count unchanged (checkpoint NOT
        // applied); the async job is check-pointed.
        for job_id in ["owned_analyze", "owned_implement"] {
            assert_eq!(
                status_retry(conn, job_id).await,
                ("launched".to_string(), 0),
                "{job_id} stays launched with retry_count unchanged"
            );
        }
        assert_eq!(
            status_retry(conn, "null_analyze").await,
            ("launched".to_string(), 1),
            "the async analyze is check-pointed (retry_count bumped)"
        );
    }

    /// Binding 3 on the boot scan: a `research_cleanup` row whose workspace is
    /// unresolvable is SKIPPED in place, not resumed: it stays `launched` with `retry_count`
    /// 0 and is absent from the resumable list.
    #[serial_test::serial(recover_from_restart)] // a concurrent boot scan would rescan the shared jobs table — see the sibling test above
    #[tokio::test]
    async fn boot_scan_leaves_unresolvable_workspace_cleanup_row_in_place() {
        crate::util::test::init_management_test_stores().await;
        let conn = &crate::session::store().conn;
        let job_id = "cleanup_missing_ws_1";
        let ws_name = "ws_boot_scan_missing_1";
        // NOT personal-prefixed, no `workspaces` row — the binding-3 skip path.
        crate::util::test::JobRowBuilder::new(
            conn,
            job_id,
            "research_cleanup",
            "sanitation",
            ws_name,
        )
        .task("cleanup prompt")
        .timestamps(crate::db::now())
        .insert()
        .await
        .unwrap();

        let resumable = recover_from_restart().await.unwrap();

        // Filter by job id: other tests' rows may legitimately appear in the
        // shared resumable list.
        let hit = resumable
            .iter()
            .any(|r| matches!(r, ResumableJob::ResearchCleanup { job_id: j, .. } if j == job_id));
        assert!(
            !hit,
            "unresolvable-workspace cleanup row is not resumed (binding-3 skip)"
        );
        assert_eq!(
            status_retry(conn, job_id).await,
            ("launched".to_string(), 0),
            "binding-3 skip leaves the cleanup row untouched (no checkpoint bump)"
        );
    }

    /// The /clear abandon path deletes ONLY the cleared session's sync jobs — async and
    /// ticket-phase jobs for the same workspace survive, and the roster cascades away.
    #[tokio::test]
    async fn clear_abandons_session_sync_jobs() {
        crate::util::test::init_management_test_stores().await;
        let conn = &crate::session::store().conn;
        let ws_name = "clear_abandon_ws";
        seed_ticket(conn, "t_clear", ws_name).await;

        for (job_id, child, caller) in [
            ("clear_sync", SpawnChild::Analyze, Some("pin_clear")),
            ("clear_async", SpawnChild::Analyze, None),
            (
                "clear_phase",
                SpawnChild::Phase {
                    phase: crate::pipeline::board::TicketPhase::Analysis,
                    ticket_id: "t_clear".to_string(),
                },
                None,
            ),
        ] {
            spawn_job(
                conn,
                job_id,
                "task",
                ws_name,
                "caller",
                "telegram",
                crate::Role::Engineer,
                &[NewAgent {
                    agent_id: format!("{job_id}_agent"),
                    kind: AgentKind::Analyst,
                    idx: Some(0),
                    task: "task".to_string(),
                }],
                &child,
                caller,
                None,
                None,
            )
            .await
            .unwrap();
        }

        let abandoned = abandon_session_jobs("pin_clear").await.unwrap();
        assert_eq!(abandoned, 1, "only the caller-owned sync job is abandoned");

        let remaining: Vec<String> = conn
            .query(
                "SELECT id FROM jobs WHERE id IN ('clear_sync','clear_async','clear_phase') ORDER BY id",
                (),
            )
            .await
            .unwrap()
            .iter()
            .map(|r| r.get::<String>(0).unwrap())
            .collect();
        assert_eq!(
            remaining,
            ["clear_async", "clear_phase"],
            "async + phase jobs survive the session abandon"
        );

        let roster: Vec<String> = conn
            .query(
                "SELECT agent_id FROM agents WHERE job_id = 'clear_sync'",
                (),
            )
            .await
            .unwrap()
            .iter()
            .map(|r| r.get::<String>(0).unwrap())
            .collect();
        assert!(roster.is_empty(), "sync job roster cascaded away");
    }

    /// Workspace deletion abandons every job for the workspace uniformly: sync, phase,
    /// research and research_cleanup rows all go, run folders are released via the run
    /// cancel, and the rosters cascade away.
    #[tokio::test]
    async fn workspace_delete_abandons_all_jobs() {
        crate::util::test::init_management_test_stores().await;
        let conn = &crate::session::store().conn;
        let ws_name = "ws_abandon_test";
        seed_ticket(conn, "t_abandon", ws_name).await;

        for (job_id, child, caller) in [
            ("abandon_sync", SpawnChild::Analyze, Some("pin_abandon")),
            (
                "abandon_phase",
                SpawnChild::Phase {
                    phase: crate::pipeline::board::TicketPhase::Analysis,
                    ticket_id: "t_abandon".to_string(),
                },
                None,
            ),
            ("abandon_research", SpawnChild::Research, None),
            ("abandon_cleanup", SpawnChild::ResearchCleanup, None),
        ] {
            spawn_job(
                conn,
                job_id,
                "task",
                ws_name,
                "caller",
                "telegram",
                crate::Role::Engineer,
                &[NewAgent {
                    agent_id: format!("{job_id}_agent"),
                    kind: AgentKind::Analyst,
                    idx: Some(0),
                    task: "task".to_string(),
                }],
                &child,
                caller,
                None,
                None,
            )
            .await
            .unwrap();
        }

        // Full integration: the WorkspaceStore built over the shared test conn runs the
        // research-run sweep fail-closed, then deletes the remaining job rows atomically with the
        // workspace row.
        let ws_store = crate::workspace::WorkspaceStore { conn: conn.clone() };
        ws_store.delete(ws_name).await.unwrap();

        let jobs = conn
            .query(
                "SELECT id FROM jobs WHERE workspace_name = ?1",
                crate::db::params![ws_name],
            )
            .await
            .unwrap();
        assert!(jobs.is_empty(), "every job row for the workspace is gone");

        let research = conn
            .query(
                "SELECT id FROM research_jobs WHERE id IN ('abandon_research','abandon_cleanup')",
                (),
            )
            .await
            .unwrap();
        assert!(
            research.is_empty(),
            "research_jobs child rows cascaded away"
        );

        let roster = conn
            .query(
                "SELECT agent_id FROM agents WHERE job_id IN ('abandon_sync','abandon_phase','abandon_research','abandon_cleanup')",
                (),
            )
            .await
            .unwrap();
        assert!(roster.is_empty(), "every seeded agent roster cascaded away");
    }
}