mahbot 0.10.3

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
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
//! Workspace storage — persisted workspace metadata and contexts.
//!
//! Also handles workspace analysis: spawning a Discovery agent to explore a new
//! workspace and produce role-specific context summaries.

use crate::Role;
use crate::Workspace;
use crate::WorkspaceStatus;
use crate::agent::role::DIAGNOSTICS_ROLE;
use crate::agent::run_default_agent;
use crate::config_db::ConfigStore;
use crate::db::{self, Value};
use crate::session::discovery_agent_id;
use crate::util::UnwrapPoison;
use anyhow::{Context, Result};
use chrono::{DateTime, Timelike, Utc};
use futures_util::future::join_all;
use std::collections::HashMap;
use std::path::Path;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use strum::IntoEnumIterator;
use tracing::warn;

crate::define_store! {
    pub static WORKSPACES: WorkspaceStore,
    expect = "workspace::WORKSPACES not initialized — call init_all_stores() first",
}

pub async fn get_by_name(name: &str) -> Result<Option<Workspace>> {
    store().get_by_name(name).await
}

// `discovery_generation` and `diagnostics_generation` are deliberately excluded from
// this list: they are read through [`WorkspaceStore::get_generation`]'s single-column
// SELECT (plus `claim_pending_for_discovery`'s `UPDATE .. RETURNING`).
crate::columns! {
    WORKSPACE_COLUMNS [WS] {
        NAME                  => "name",
        PATH                  => "path",
        STATUS                => "status",
        MAINTENANCE_ENABLED    => "maintenance",
        PAUSED                => "paused",
        MAINTAINER_LAST_RUN_AT  => "maintainer_last_run_at",
        DIAGNOSTICS           => "diagnostics",
        NOTES                  => "notes",
        LAST_ANALYZED_COMMIT   => "last_analyzed_commit",
    }
}

crate::columns! {
    EDITOR_TAB_COLUMNS [ET] {
        FILE_PATH    => "file_path",
        TAB_ORDER    => "tab_order",
        IS_ACTIVE    => "is_active",
        IS_DIRTY     => "is_dirty",
        DIRTY_CONTENT => "dirty_content",
    }
}

/// Generation counter metadata: DB column name and log label.
#[derive(Clone, Copy)]
struct GenerationColumn {
    name: &'static str,
    log_label: &'static str,
}

impl GenerationColumn {
    /// Bumped by [`WorkspaceStore::rediscover`].
    const DISCOVERY: Self = Self {
        name: "discovery_generation",
        log_label: "Discovery",
    };
    /// Bumped by [`WorkspaceStore::rediscover_diagnostics`] and [`WorkspaceStore::set_diagnostics`].
    const DIAGNOSTICS: Self = Self {
        name: "diagnostics_generation",
        log_label: "Diagnostics",
    };
}

/// Check the generation counter for `column`: return `true` if the calling
/// task is still the latest (OK to proceed), `false` if a newer run bumped
/// it while this task worked (stale — do not proceed).
async fn check_generation(
    storage: &WorkspaceStore,
    workspace_name: &str,
    generation: i64,
    column: GenerationColumn,
    label: &str,
) -> bool {
    let current_gen = storage
        .get_generation(workspace_name, column)
        .await
        .unwrap_or(generation + 1);
    if current_gen != generation {
        tracing::warn!(
            workspace_name,
            captured_gen = generation,
            current_gen,
            label = %label,
            "{} generation mismatch — skipping stale write",
            column.log_label
        );
        return false;
    }
    true
}

/// Run workspace discovery for a single role. `discovery_generation` is the counter
/// captured at spawn time: before writing, the current generation is re-read and a
/// mismatch means a newer [`WorkspaceStore::rediscover`] made this result stale, so the
/// write is skipped silently.
async fn run_workspace_discovery(
    ws: &Workspace,
    role: Role,
    discovery_generation: i64,
) -> Result<(), DiscoveryRunError> {
    run_discovery_task(
        ws,
        role.discovery_prompt(),
        discovery_generation,
        Some(role.as_str()),
    )
    .await
}

/// Run general (non-role) workspace discovery — a project overview used by
/// non-agent LLM calls. Stored as the NULL-role context row.
async fn run_general_discovery(
    ws: &Workspace,
    discovery_generation: i64,
) -> Result<(), DiscoveryRunError> {
    run_discovery_task(
        ws,
        crate::prompt::load_prompt("discovery/general.md"),
        discovery_generation,
        None,
    )
    .await
}

/// Shared discovery execution: run the Discovery agent on `prompt`, guard
/// against stale writes, then persist the result. `role` is `None` for the
/// general (non-role) context, `Some(name)` for a role-keyed context; the
/// role string also serves as the task label (`"general"` when `None`).
async fn run_discovery_task(
    ws: &Workspace,
    prompt: String,
    discovery_generation: i64,
    role: Option<&str>,
) -> Result<(), DiscoveryRunError> {
    let label = role.unwrap_or("general");
    let storage = WORKSPACES
        .get()
        .context("WORKSPACES not initialized")?
        .clone();

    tracing::info!(workspace_name = ws.name, role = %label, "Starting workspace discovery");

    let agent_id = discovery_agent_id(&ws.name, label);
    let (agent, response) = run_default_agent(
        &agent_id,
        Role::Discovery,
        ws,
        &prompt,
        false,
        None,
        None,
        None,
    )
    .await;
    let Some(response) = response else {
        return Err(discovery_no_response_error(&agent, "Discovery"));
    };

    let content = response.trim().to_string();
    if content.is_empty() {
        return Err(DiscoveryRunError::fatal(anyhow::anyhow!(
            "Empty response for '{label}'"
        )));
    }

    // Guard against stale writes: if another rediscover has been triggered
    // while this discovery ran, skip the context write.
    if !check_generation(
        &storage,
        &ws.name,
        discovery_generation,
        GenerationColumn::DISCOVERY,
        "context",
    )
    .await
    {
        return Ok(());
    }

    let result = match role {
        Some(r) => storage.set_context(&ws.name, r, &content).await,
        None => storage.set_general_context(&ws.name, &content).await,
    };
    if let Err(e) = result {
        tracing::error!(workspace_name = ws.name, role = %label, error = %e, "Failed to store context");
        return Err(DiscoveryRunError::fatal(e));
    }

    tracing::info!(workspace_name = ws.name, role = %label, "Workspace discovery for {label} completed");
    Ok(())
}

/// Run diagnostics discovery: a Discovery agent scans build files for the format, lint,
/// type-check, build and unit-test commands, and its scoped extraction yields the
/// structured result. `diagnostics_generation` guards against stale writes — a newer
/// [`WorkspaceStore::rediscover_diagnostics`] or [`WorkspaceStore::set_diagnostics`]
/// skips the write — and on failure the existing data is left untouched.
async fn run_workspace_diagnostics(
    ws: &Workspace,
    diagnostics_generation: i64,
) -> Result<(), DiscoveryRunError> {
    let storage = WORKSPACES
        .get()
        .context("WORKSPACES not initialized")?
        .clone();

    tracing::info!(workspace_name = ws.name, "Starting diagnostics discovery");

    let agent_id = discovery_agent_id(&ws.name, DIAGNOSTICS_ROLE);

    // Load the diagnostics discovery prompt directly (not a role-specific discovery prompt).
    let prompt = crate::prompt::load_prompt("discovery/diagnostics.md");

    let (agent, response) = run_default_agent(
        &agent_id,
        Role::Discovery,
        ws,
        &prompt,
        false,
        None,
        None,
        None,
    )
    .await;
    if response.is_none() {
        return Err(discovery_no_response_error(&agent, "Diagnostics discovery"));
    }

    // Keep the Agent alive after run_default_agent() for extract_verdict —
    // it needs agent.session.history() and agent.tool_specs.
    let extraction_prompt = crate::prompt::load_prompt("extraction/diagnostics.md");

    // Prefix-cache preservation: `agent.extract_verdict` uses the agent's own
    // parameters (model, reasoning_effort, tools, provider routing) with no
    // response_format override — the extraction request shares the Discovery
    // agent-loop prefix, only the extraction prompt is new. Retry exhaustion
    // (RetryExhausted) surfaces the scoped loop's failure trail.
    let cmds: crate::DiagnosticsCommands = agent
        .extract_verdict(&extraction_prompt, None, None)
        .await
        .map_err(|e| DiscoveryRunError::classified(&agent, anyhow::Error::from(e)))?;

    // Guard against stale writes.
    if !check_generation(
        &storage,
        &ws.name,
        diagnostics_generation,
        GenerationColumn::DIAGNOSTICS,
        DIAGNOSTICS_ROLE,
    )
    .await
    {
        return Ok(());
    }

    storage.set_diagnostics(&ws.name, &cmds).await?;

    tracing::info!(
        workspace_name = ws.name,
        format = ?cmds.format,
        lint = ?cmds.lint,
        build = ?cmds.build,
        unit_test = ?cmds.unit_test,
        "Diagnostics discovery completed"
    );
    Ok(())
}

/// Apply the final status and pause state after a discovery run completes, once all role
/// discoveries and diagnostics have finished. Separate so tests can check the
/// paused-behaviour invariants without running real agents.
///
/// `AllOk` sets `ready` and unpauses — rediscovery is the documented unpause path, and
/// the poll step holds every claim while the workspace is not ready, so queued work is
/// picked up on the next cycle. `Fatal` sets `failed` (terminal, manual Re-analyze as
/// before) and leaves `paused`; `Transient` sets `pending` and arms the pickup cooldown,
/// leaving the analysis pause armed. Panics never reach here — they abort the spawned
/// task and boot reclassification recovers the row (see [`spawn_panic_guarded`]). Every
/// write is skipped when a newer [`WorkspaceStore::rediscover`] bumped the generation
/// while discovery was in flight.
///
/// Known limitation: the unpause does not check who set the pause, so a failure or
/// operator pause that landed mid-discovery is cleared with it — the stopped round
/// replays once, fails again and freezes the workspace on its own `set_paused`. Bounded,
/// not a loop, and the nightly loop skips paused workspaces.
async fn finalize_discovery(
    storage: &WorkspaceStore,
    ws_name: &str,
    ws_path: &str,
    discovery_generation: i64,
    outcome: DiscoveryOutcome,
    errors: &[String],
) {
    // Final guard: if a newer rediscover was triggered while this task ran,
    // all three write sites (contexts, diagnostics, status) have already been
    // individually guarded.  This check catches the status write.
    if !check_generation(
        storage,
        ws_name,
        discovery_generation,
        GenerationColumn::DISCOVERY,
        "final status",
    )
    .await
    {
        return;
    }

    match outcome {
        DiscoveryOutcome::AllOk => {
            // Success — any prior provider-failure cooldown is obsolete.
            clear_pending_pickup_cooldown(ws_name);

            // Capture the current git HEAD commit hash for nightly re-analysis detection.
            // If the git command fails (not a git repo, no commits, or other error),
            // store NULL — this is not an error for the discovery itself.
            let commit_hash = crate::git::commands::run_git_head(std::path::Path::new(ws_path))
                .await
                .ok();

            if let Err(e) = storage
                .exec_update_with_updated_at(
                    "status = ?, paused = 0, last_analyzed_commit = ?",
                    vec![
                        Value::from(WorkspaceStatus::Ready.to_string()),
                        Value::from(commit_hash.as_deref()),
                    ],
                    ws_name,
                )
                .await
            {
                tracing::warn!(
                    workspace = ws_name,
                    error = %e,
                    "Failed to update workspace status after discovery",
                );
            }

            tracing::info!(workspace = ws_name, "Workspace pipeline resumed");
            tracing::info!(
                workspace_name = ws_name,
                "Workspace analysis complete — all roles ready"
            );
        }
        DiscoveryOutcome::Fatal => {
            let msg = errors.join("; ");
            // Terminal — the workspace leaves the pending-pickup cycle; drop any
            // cooldown armed by an earlier provider-class failure.
            clear_pending_pickup_cooldown(ws_name);
            if let Err(e) = storage.set_status(ws_name, &WorkspaceStatus::Failed).await {
                // A failed write strands the workspace in `analyzing` until boot
                // recovery — log so it is not silent.
                tracing::warn!(
                    workspace = ws_name,
                    error = %e,
                    "Failed to mark workspace Failed after fatal discovery failure"
                );
            }
            tracing::warn!(workspace_name = ws_name, error = %msg, "Workspace analysis failed");
        }
        DiscoveryOutcome::Transient => {
            // Every failure was provider-class: return to pending and let the pickup
            // step retry after the cooldown. The cooldown is armed BEFORE the status
            // write: while the row is still `analyzing` nothing can claim it, so no poll
            // round sees `pending` with no cooldown armed and spawns a duplicate run.
            record_pending_pickup_cooldown(ws_name);
            if let Err(e) = storage.set_status(ws_name, &WorkspaceStatus::Pending).await {
                // A failed write strands the workspace in `analyzing` with the
                // cooldown armed until boot recovery — log so it is not silent.
                tracing::warn!(
                    workspace = ws_name,
                    error = %e,
                    "Failed to return workspace to Pending after provider-class failure"
                );
            }
            tracing::warn!(
                workspace_name = ws_name,
                error = %errors.join("; "),
                "Workspace analysis stalled on provider failure — pending pickup retry after cooldown"
            );
        }
    }
}

/// Two-bucket classification of a discovery failure. `Transient` is provider-class (auth
/// 401/403, quota, transport/5xx, shutdown/cancel): the workspace returns to Pending and
/// the pickup step retries it after an in-memory cooldown. `Fatal` is genuine (internal
/// runtime errors, parse failures): the workspace goes Failed, terminal. Panics never
/// reach this classifier — they strand the row in `analyzing` until boot reclassifies it
/// to `pending`.
#[derive(Debug, Clone, Copy, PartialEq)]
enum DiscoveryFailureKind {
    Transient,
    Fatal,
}

/// A discovery failure carrying its two-bucket classification.
///
/// The classification rides the error so the parallel discovery tasks in
/// [`spawn_workspace_discovery`] can aggregate mixed outcomes with a
/// "any fatal → Failed" precedence without string matching.
#[derive(Debug)]
struct DiscoveryRunError {
    kind: DiscoveryFailureKind,
    error: anyhow::Error,
}

impl DiscoveryRunError {
    fn transient(error: anyhow::Error) -> Self {
        Self {
            kind: DiscoveryFailureKind::Transient,
            error,
        }
    }

    fn fatal(error: anyhow::Error) -> Self {
        Self {
            kind: DiscoveryFailureKind::Fatal,
            error,
        }
    }

    /// Wrap an error with the two-bucket classification for a failed
    /// discovery agent run (the shared wrap used by every agent-failure
    /// site in the discovery path).
    fn classified(agent: &crate::Agent, error: anyhow::Error) -> Self {
        match classify_discovery_failure(agent, Some(&error)) {
            DiscoveryFailureKind::Transient => Self::transient(error),
            DiscoveryFailureKind::Fatal => Self::fatal(error),
        }
    }
}

impl std::fmt::Display for DiscoveryRunError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.error)
    }
}

/// Default `?` conversion: an unclassified plain error (DB failure, missing global) is a
/// genuine runtime failure. Agent-run failures must go through
/// [`DiscoveryRunError::classified`] instead — the only path yielding `transient`.
impl From<anyhow::Error> for DiscoveryRunError {
    fn from(error: anyhow::Error) -> Self {
        Self::fatal(error)
    }
}

/// Classify a failed discovery run into the two-bucket scheme, mirroring
/// [`crate::agent::failure_classification`]'s ordering: drain/shutdown/cancellation are
/// transient (the run was cut short, not a genuine failure — a cancelled discovery
/// returns to Pending rather than the historical terminal Failed). A typed
/// [`crate::retry::RetryExhausted`] class decides provider-vs-genuine; everything else is
/// fatal. Panics never reach here (see [`spawn_panic_guarded`]).
///
/// `NonRetryable` is transient because it covers auth 401/403, invalid-model and
/// tool-schema 400s — all config-fixable, so the workspace must wait in Pending for the
/// user rather than go terminal, and the escalating cooldown bounds the retry rate.
/// `Parse`/validation is fatal: the provider answered, so the defect is ours. `error` is
/// the raw error when the call site has one; the typed class `run_agent` captured takes precedence.
fn classify_discovery_failure(
    agent: &crate::Agent,
    error: Option<&anyhow::Error>,
) -> DiscoveryFailureKind {
    if crate::shutdown::is_draining()
        || crate::shutdown::shutdown_token().is_cancelled()
        || agent.is_cancelled()
    {
        return DiscoveryFailureKind::Transient;
    }
    let class = agent
        .failure_class
        .or_else(|| error.and_then(crate::agent::failure_class_from_error));
    let Some(class) = class else {
        return DiscoveryFailureKind::Fatal;
    };
    match class {
        crate::retry::FailureClass::Transport
        | crate::retry::FailureClass::TruncatedEnvelope
        | crate::retry::FailureClass::NoResponse
        | crate::retry::FailureClass::TruncatedOutput
        | crate::retry::FailureClass::NonRetryable
        | crate::retry::FailureClass::Shutdown => DiscoveryFailureKind::Transient,
        crate::retry::FailureClass::Parse
        | crate::retry::FailureClass::OutOfRangeScore
        | crate::retry::FailureClass::Membership
        | crate::retry::FailureClass::Completeness
        | crate::retry::FailureClass::ContradictionAgents
        | crate::retry::FailureClass::ValidationOther => DiscoveryFailureKind::Fatal,
    }
}

/// Aggregate outcome of a discovery run — encodes the success/fatal/transient
/// trichotomy structurally (a success implies no fatal failure), replacing a
/// pair of bools that could express invalid combinations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DiscoveryOutcome {
    /// Every sub-run succeeded.
    AllOk,
    /// At least one fatal (non-provider) failure — terminal `Failed`.
    Fatal,
    /// Only provider-class (transient) failures — return to `Pending`.
    Transient,
}

/// Fold one discovery sub-run result into the aggregate outcome shared by the role,
/// general and diagnostics sites: any error degrades `AllOk`, any fatal forces `Fatal`,
/// and the error string is recorded (with `prefix`) for the finalize message. Scrubbed
/// here, so agent failure chains never reach the finalize logs unscrubbed.
fn fold_discovery_result(
    outcome: &mut DiscoveryOutcome,
    errors: &mut Vec<String>,
    result: Result<(), DiscoveryRunError>,
    prefix: &str,
) {
    if let Err(e) = result {
        errors.push(crate::util::scrub_credentials(&format!("{prefix}{e}")));
        if e.kind == DiscoveryFailureKind::Fatal {
            *outcome = DiscoveryOutcome::Fatal;
        } else if *outcome == DiscoveryOutcome::AllOk {
            *outcome = DiscoveryOutcome::Transient;
        }
    }
}

/// The classified error for an agent run that produced no response — shared by
/// [`run_discovery_task`] and [`run_workspace_diagnostics`], which differ only in the task label.
fn discovery_no_response_error(agent: &crate::Agent, task_label: &str) -> DiscoveryRunError {
    DiscoveryRunError::classified(
        agent,
        anyhow::anyhow!(
            "{task_label} agent returned no response: {}",
            agent.failure_reason("unknown error")
        ),
    )
}

/// Base cooldown for the first provider-class discovery failure (15 min).
const PENDING_PICKUP_COOLDOWN_BASE_MINS: u64 = 15;
/// Ceiling for the escalating pickup cooldown (4 h).
const PENDING_PICKUP_COOLDOWN_MAX_MINS: u64 = 240;

/// Escalating cooldown for the `attempts`-th consecutive provider-class failure: 15 min,
/// 30 min, 1 h, 2 h, then 4 h forever. Memory-only by design: after a restart a pending
/// workspace may be retried once immediately, and escalation keeps a persistently-down
/// provider from burning the full LLM retry budget every 15 minutes forever.
fn pending_pickup_cooldown_duration(attempts: u32) -> Duration {
    let exponent = attempts.saturating_sub(1).min(4);
    let minutes = (PENDING_PICKUP_COOLDOWN_BASE_MINS * 2u64.pow(exponent))
        .min(PENDING_PICKUP_COOLDOWN_MAX_MINS);
    Duration::from_mins(minutes)
}

#[derive(Debug, Clone, Copy)]
struct PickupCooldown {
    /// Instant before which the pickup step must not claim the workspace.
    deadline: Instant,
    /// Consecutive provider-class discovery failures since the last success or manual reset —
    /// drives the escalating cooldown duration.
    attempts: u32,
}

/// In-memory cooldown map: workspace name → state. Written by [`finalize_discovery`] on
/// provider-class failure; cleared on successful discovery, manual rediscover, delete and re-add.
static PENDING_PICKUP_COOLDOWNS: OnceLock<std::sync::Mutex<HashMap<String, PickupCooldown>>> =
    OnceLock::new();

fn pending_pickup_cooldowns() -> &'static std::sync::Mutex<HashMap<String, PickupCooldown>> {
    PENDING_PICKUP_COOLDOWNS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}

/// Arm the escalating cooldown for a provider-class failure, so the pending pickup for
/// `ws_name` waits before claiming it again (see [`pending_pickup_cooldown_duration`]).
/// Success, manual rediscover, delete and re-add reset it. A transient finalize landing
/// after a concurrent delete's clear leaves a stale entry — harmless (the map is bounded
/// by workspace count) and cleared again on re-add.
fn record_pending_pickup_cooldown(ws_name: &str) {
    let mut map = pending_pickup_cooldowns().lock().unwrap_poison();
    let attempts = map.get(ws_name).map_or(0, |c| c.attempts) + 1;
    let deadline = Instant::now() + pending_pickup_cooldown_duration(attempts);
    map.insert(ws_name.to_string(), PickupCooldown { deadline, attempts });
}

/// Arm the cooldown with an explicit deadline (test hook; production callers use
/// [`record_pending_pickup_cooldown`]).
#[cfg(test)]
fn record_pending_pickup_cooldown_until(ws_name: &str, deadline: Instant) {
    let mut map = pending_pickup_cooldowns().lock().unwrap_poison();
    map.insert(
        ws_name.to_string(),
        PickupCooldown {
            deadline,
            attempts: 1,
        },
    );
}

/// Clear the cooldown for a workspace — also resets the escalation counter.
fn clear_pending_pickup_cooldown(ws_name: &str) {
    pending_pickup_cooldowns()
        .lock()
        .unwrap_poison()
        .remove(ws_name);
}

/// Whether the pickup step must wait out a cooldown before claiming `ws_name`. Expired
/// entries are deliberately retained (the map is bounded by workspace count): the
/// `attempts` escalation counter must survive expiry, or pruning here would reset the
/// escalation on every pickup cycle.
pub(crate) fn pending_pickup_cooldown_active(ws_name: &str) -> bool {
    let map = pending_pickup_cooldowns().lock().unwrap_poison();
    map.get(ws_name)
        .is_some_and(|c| Instant::now() < c.deadline)
}

/// Spawn `future` in a panic-guarded sub-task and await it, logging a workspace-level
/// error if it panics or is cancelled. Unlike the ticket-dispatch panic recovery, this
/// only logs: a non-prompt panic leaves the workspace in `analyzing`, which
/// `reclassify_analyzing_to_pending` recovers at the next startup.
async fn spawn_panic_guarded(
    ws_name: &str,
    task: &str,
    future: impl std::future::Future<Output = ()> + Send + 'static,
) {
    let inner = tokio::spawn(future);
    if let Err(e) = inner.await {
        let kind = if e.is_panic() { "panic" } else { "cancelled" };
        tracing::error!(
            workspace_name = %ws_name,
            kind = kind,
            error = %e,
            "{task} task failed",
        );
    }
}

/// Spawn a background task running per-role and general context discovery, and
/// diagnostics discovery unless `discover_diagnostics` is `false` (a re-analysis, or a
/// pickup that found existing diagnostics) — user-managed diagnostics survive.
/// `discovery_generation` is captured at spawn time and guards against stale writes.
pub fn spawn_workspace_discovery(
    ws: &Workspace,
    discovery_generation: i64,
    discover_diagnostics: bool,
) {
    let ws = ws.clone();
    tokio::spawn(async move {
        let ws_name = ws.name.clone();
        let inner_ws_name = ws_name.clone();
        let inner_ws_path = ws.path.clone();
        let inner = async move {
            // Build role discovery futures (always needed); the general (non-role) project
            // overview discovery runs alongside them.
            let role_futures: Vec<_> = Role::iter()
                .filter(|r| crate::agent::role::role_info(r).has_discovery)
                .map(|role| {
                    let ws = ws.clone();
                    async move { run_workspace_discovery(&ws, role, discovery_generation).await }
                })
                .collect();

            let (role_results, general_result, diagnostics_result) = if discover_diagnostics {
                // Read the diagnostics generation for the guard. Separate from
                // discovery_generation: both counters are independent (diagnostics is bumped by
                // set_diagnostics/rediscover_diagnostics, discovery by rediscover).
                let diag_gen = match WORKSPACES.get() {
                    Some(s) => s
                        .get_generation(&inner_ws_name, GenerationColumn::DIAGNOSTICS)
                        .await
                        .unwrap_or(0),
                    None => 0,
                };
                tokio::join!(
                    join_all(role_futures),
                    run_general_discovery(&ws, discovery_generation),
                    run_workspace_diagnostics(&ws, diag_gen),
                )
            } else {
                let (roles, general) = tokio::join!(
                    join_all(role_futures),
                    run_general_discovery(&ws, discovery_generation),
                );
                (roles, general, Ok(()))
            };

            let mut outcome = DiscoveryOutcome::AllOk;
            let mut errors: Vec<String> = Vec::new();

            for result in role_results {
                fold_discovery_result(&mut outcome, &mut errors, result, "");
            }

            // General/diagnostics failures fail the run; the failure kind decides whether the
            // workspace returns to Pending (provider-class) or goes Failed (genuine).
            fold_discovery_result(&mut outcome, &mut errors, general_result, "");
            fold_discovery_result(
                &mut outcome,
                &mut errors,
                diagnostics_result,
                "Diagnostics discovery failed: ",
            );

            let Some(storage) = WORKSPACES.get() else {
                tracing::error!("WORKSPACES not initialized during final status update");
                return;
            };

            finalize_discovery(
                storage,
                &inner_ws_name,
                &inner_ws_path,
                discovery_generation,
                outcome,
                &errors,
            )
            .await;
        };

        // Box the discovery payload: it embeds role/general/diagnostics futures and exceeds
        // the 16 KB large_futures threshold as an inline async-block.
        spawn_panic_guarded(&ws_name, "spawn_workspace_discovery", Box::pin(inner)).await;
    });
}

/// Spawn a background task running diagnostics discovery only — no per-role context
/// discovery. Used by the GUI's "Re-discover diagnostics"; `diagnostics_generation`
/// guards against stale writes via [`check_generation`].
fn spawn_diagnostics_discovery(ws: &Workspace, diagnostics_generation: i64) {
    let ws = ws.clone();
    tokio::spawn(async move {
        let ws_name = ws.name.clone();

        let inner = async move {
            if let Err(e) = run_workspace_diagnostics(&ws, diagnostics_generation).await {
                tracing::error!(
                    workspace_name = %ws.name,
                    error = %e,
                    "Diagnostics rediscovery failed",
                );
            }
        };

        spawn_panic_guarded(&ws_name, "spawn_diagnostics_discovery", inner).await;
    });
}

/// The longest workspace name [`validate_name`] admits.
pub(crate) const MAX_NAME_LEN: usize = 40;

/// Validate a workspace name: ASCII letters and underscores only, starting with a letter,
/// at most [`MAX_NAME_LEN`] characters.
fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() {
        anyhow::bail!("Workspace name must not be empty");
    }
    if name.len() > MAX_NAME_LEN {
        anyhow::bail!("Workspace name must not exceed {MAX_NAME_LEN} characters");
    }
    if !name.chars().all(|c| c.is_ascii_alphabetic() || c == '_') {
        anyhow::bail!("Workspace name must contain only ASCII letters (a-z, A-Z) and underscores");
    }
    if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
        anyhow::bail!("Workspace name must start with a letter");
    }
    Ok(())
}

/// Append the platform's separator to a managed workspace's root unless it
/// already ends with one, so the stored root reads the way it always has. A
/// drive or volume root already carries one, and that separator is what keeps it
/// absolute rather than drive-relative (`C:\`, not `C:`).
fn ensure_trailing_separator(mut path: String) -> String {
    if !path.ends_with(std::path::MAIN_SEPARATOR) {
        path.push(std::path::MAIN_SEPARATOR);
    }
    path
}

/// Canonicalize a user-provided path for workspace storage: expand `~`, resolve it
/// ([`std::fs::canonicalize`]), drop the platform's verbatim prefix
/// ([`crate::util::strip_verbatim_prefix`]) and append the trailing separator a managed
/// root is shown with. The error message is meant for the user.
fn canonicalize_workspace_path(raw: &str) -> Result<String, String> {
    let expanded = crate::util::expand_tilde(raw);

    let canonical = crate::util::with_block_in_place(|| {
        std::fs::canonicalize(&expanded).map_err(|e| {
            if expanded.exists() {
                format!("Cannot access path '{}': {e}", expanded.display())
            } else {
                format!("Path does not exist: {}", expanded.display())
            }
        })
    })?;

    if !canonical.is_dir() {
        return Err(format!("Path is not a directory: {}", canonical.display()));
    }

    Ok(ensure_trailing_separator(
        crate::util::strip_verbatim_prefix(&canonical)
            .to_string_lossy()
            .to_string(),
    ))
}

/// Synthesize a workspace from an absolute path to an existing directory, so a
/// custom-role launch can name *any* folder as its workspace. `None` unless `name` is an
/// absolute path that exists and is a directory. The name is the canonical path itself,
/// NOT the `dir-…` short key a delegation round uses: it is the durable key a launch is
/// recorded under, and [`crate::users::resolve_workspace`] accepts an absolute path, so
/// the address must be the folder itself for the launch to resolve after a restart. A
/// managed workspace with that name (or that folder — `WorkspaceStore::get_by_path`) is
/// resolved by the caller first and still wins.
#[must_use]
pub(crate) fn synthesize_from_path(name: &str) -> Option<Workspace> {
    let path = Path::new(name);
    if !path.is_absolute() {
        return None;
    }
    let (exists, is_dir) = crate::util::with_block_in_place(|| (path.exists(), path.is_dir()));
    if !exists || !is_dir {
        return None;
    }
    let canonical = crate::stored_workspace_path(path);
    let address = canonical.to_string_lossy().to_string();
    Some(Workspace::ephemeral_run(&address, &canonical))
}

fn workspace_from_row(row: &db::Row) -> anyhow::Result<Workspace> {
    Ok(Workspace {
        name: row.get(COL_WS_NAME)?,
        path: row.get(COL_WS_PATH)?,
        status: row
            .get::<String>(COL_WS_STATUS)?
            .parse::<WorkspaceStatus>()?,
        maintenance_enabled: row.get::<bool>(COL_WS_MAINTENANCE_ENABLED)?,
        paused: row.get::<bool>(COL_WS_PAUSED)?,
        maintainer_last_run_at: row.get::<Option<String>>(COL_WS_MAINTAINER_LAST_RUN_AT)?,
        diagnostics: row.get::<Option<String>>(COL_WS_DIAGNOSTICS)?,
        notes: row.get::<String>(COL_WS_NOTES)?,
        last_analyzed_commit: row.get::<Option<String>>(COL_WS_LAST_ANALYZED_COMMIT)?,
    })
}

/// Max length of workspace notes in chars (char-level truncation — never
/// byte-slice, which would panic on multi-byte characters at the boundary).
pub(crate) const MAX_WORKSPACE_NOTES_CHARS: usize = 4000;

/// Single source of truth for the notes char-cap — plain char-boundary take
/// (no ellipsis, unlike `util::truncate`), shared by DB write, prompt build,
/// and GUI editor.
pub(crate) fn truncate_workspace_notes(s: &str) -> String {
    s.chars().take(MAX_WORKSPACE_NOTES_CHARS).collect()
}

impl WorkspaceStore {
    /// UPDATE `workspaces` setting `set_clause` plus `updated_at = now` for one named
    /// row. Returns the affected-row count, so a caller can refuse `0` (no such
    /// workspace) instead of reporting a write that never happened — see
    /// [`Self::set_paused`].
    async fn exec_update_with_updated_at(
        &self,
        set_clause: &str,
        set_params: Vec<db::Value>,
        name: &str,
    ) -> Result<u64> {
        let sql = format!("UPDATE workspaces SET {set_clause}, updated_at = ? WHERE name = ?");
        let mut params = set_params;
        params.push(Value::from(db::now()));
        params.push(Value::from(name));
        Ok(self.conn.execute(&sql, params).await?)
    }

    /// Insert a new workspace with status `pending` (paused=1); the discovery spawn is
    /// deferred to the management poll's pickup step, so a first-run "workspace added
    /// before the key" no longer flips to Failed seconds later. Manual Re-analyze and
    /// the nightly rediscovery path are unaffected.
    pub async fn add(&self, name: &str, path: &str) -> Result<Workspace> {
        validate_name(name)?;

        // Canonicalize and validate the path so bad paths never enter the system.
        let path = canonicalize_workspace_path(path).map_err(|e| anyhow::anyhow!("{e}"))?;
        let now = db::now();
        let pending = WorkspaceStatus::Pending.to_string();
        let ws = self
            .conn
            .execute_one(
                &format!(
                    "INSERT INTO workspaces (name, path, status, created_at, updated_at, paused) \
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6) RETURNING {WORKSPACE_COLUMNS}"
                ),
                db::params![name, path, pending, now.clone(), now.clone(), 1],
                workspace_from_row,
            )
            .await?;
        // No discovery spawn here: the pickup step claims the pending
        // workspace once the provider is configured. discovery_generation
        // defaults to 0 in the schema — the pickup reads the live value.
        // Clear any stale cooldown from a previously-deleted same-name row.
        clear_pending_pickup_cooldown(name);
        // The folder becomes a repository so the pipeline can commit its work. An existing
        // repository is left alone, a failed init never fails the add, and the init runs after
        // the INSERT (a rejected add must not touch the folder) but before the index below, so
        // the engine is built with the repository already in place.
        crate::git::commands::init_repo_if_absent(std::path::Path::new(&ws.path)).await;
        if let Err(e) =
            crate::workspace_index::get_or_init_engine(name, std::path::Path::new(&ws.path))
        {
            tracing::warn!(workspace_name = name, error = %e, "Failed to init search engine on workspace add");
        }
        Ok(ws)
    }

    /// List all workspaces ordered by name.
    pub async fn list(&self) -> Result<Vec<Workspace>> {
        self.conn
            .query_map_strict_cached(
                &format!("SELECT {WORKSPACE_COLUMNS} FROM workspaces ORDER BY name"),
                db::params![],
                workspace_from_row,
            )
            .await
    }

    pub async fn get_by_name(&self, name: &str) -> Result<Option<Workspace>> {
        self.conn
            .query_optional_cached(
                &format!("SELECT {WORKSPACE_COLUMNS} FROM workspaces WHERE name = ?1"),
                db::params![name],
                workspace_from_row,
            )
            .await
    }

    /// The managed workspace whose folder is `path` — a caller may name a workspace by
    /// path instead of name ([`crate::users::resolve_workspace`]). Rows store the
    /// canonical path with a trailing separator, so the candidate is normalized the same way.
    pub async fn get_by_path(&self, path: &str) -> Result<Option<Workspace>> {
        let canonical = ensure_trailing_separator(
            crate::stored_workspace_path(std::path::Path::new(path))
                .to_string_lossy()
                .to_string(),
        );
        self.conn
            .query_optional_cached(
                &format!("SELECT {WORKSPACE_COLUMNS} FROM workspaces WHERE path = ?1"),
                db::params![canonical],
                workspace_from_row,
            )
            .await
    }

    /// Delete a workspace by name. Context rows are cascaded automatically. The
    /// admin's `users.selected_workspace` is resolved against the surviving
    /// projects: onto [`crate::users::fallback_workspace_name`]'s pick — the one
    /// start-up makes too — or onto the personal workspace (NULL) when none
    /// survives; an empty or dangling value is repaired the same way, since those
    /// are not steady states either (start-up repairs both too). Guest selections
    /// naming the deleted workspace are cleared: a guest always resolves to their
    /// personal workspace.
    ///
    /// The workspace's research runs are cancelled and swept first (releasing run
    /// folders + archives), and the remaining job rows are deleted IN the
    /// workspace-row transaction so the jobs/workspace deletion commits
    /// atomically. The associated search engine is removed from the in-memory registry.
    ///
    /// Returns the admin's active project after the deletion (`None` = the
    /// personal workspace) — read back through the same transaction, so the
    /// caller reports where the desktop stands rather than a derivation of it.
    pub async fn delete(&self, name: &str) -> Result<Option<String>> {
        // Fail-closed: boot SKIPS jobs whose workspace is unresolvable (their
        // only deletion path is this abandon), so a failed abandon followed by
        // a deleted workspace row would orphan the jobs permanently. The
        // deletion aborts instead and the caller surfaces the error.
        let swept = crate::jobs::abandon_workspace_research_runs(name).await?;
        let tx = self.conn.begin_tx().await?;
        tx.execute("DELETE FROM workspaces WHERE name = ?1", db::params![name])
            .await?;
        // Every selection naming the deleted workspace is cleared here; the admin's is
        // resolved onto the fallback below.
        tx.execute(
            "UPDATE users SET selected_workspace = NULL WHERE selected_workspace = ?1",
            db::params![name],
        )
        .await?;
        // The projects left — read through the transaction, so the deletion above is visible.
        let surviving = tx
            .query_map_strict("SELECT name FROM workspaces", db::params![], |row| {
                row.get::<String>(0)
            })
            .await?;
        let next = crate::users::fallback_workspace_name(surviving.iter().map(String::as_str));
        tx.execute(
            "UPDATE users SET selected_workspace = ?1 WHERE name = ?2 AND \
             (selected_workspace IS NULL \
              OR selected_workspace NOT IN (SELECT name FROM workspaces))",
            db::params![next, crate::users::ADMIN_USER_NAME],
        )
        .await?;
        let active_now = tx
            .query_map_strict(
                "SELECT selected_workspace FROM users WHERE name = ?1",
                db::params![crate::users::ADMIN_USER_NAME],
                |row| row.get::<Option<String>>(0),
            )
            .await?
            .into_iter()
            .next()
            .flatten();
        // Remaining job rows go with the workspace row in ONE atomic commit; CASCADE removes
        // their rosters.
        let remaining = tx
            .execute(
                "DELETE FROM jobs WHERE workspace_name = ?1",
                db::params![name],
            )
            .await?;
        tx.commit().await?;
        if swept > 0 || remaining > 0 {
            tracing::info!(
                workspace_name = name,
                swept_runs = swept,
                remaining_jobs = remaining,
                "abandoned workspace jobs"
            );
        }
        crate::workspace_index::remove_engine(name);
        clear_pending_pickup_cooldown(name);
        Ok(active_now)
    }

    pub async fn set_status(&self, name: &str, status: &WorkspaceStatus) -> Result<()> {
        self.exec_update_with_updated_at("status = ?", vec![Value::from(status.to_string())], name)
            .await
            .map(|_| ())
    }

    /// Atomically claim a pending workspace for its first discovery: `pending` →
    /// `analyzing` (with the analysis pause), returning the row's live
    /// `discovery_generation` captured in the same statement so a concurrent `rediscover`
    /// cannot race the read. `Ok(None)` when the row was no longer pending — a concurrent
    /// pickup, GUI Re-analyze or delete won the race, and the caller must not spawn.
    pub(crate) async fn claim_pending_for_discovery(&self, name: &str) -> Result<Option<i64>> {
        self.conn
            .execute_optional(
                "UPDATE workspaces SET status = ?, paused = 1, updated_at = ? \
                 WHERE name = ? AND status = ? RETURNING discovery_generation",
                db::params![
                    WorkspaceStatus::Analyzing.to_string(),
                    db::now(),
                    name,
                    WorkspaceStatus::Pending.to_string()
                ],
                |row| row.get(0),
            )
            .await
    }

    /// Boot recovery: discovery leaves no job rows, so a workspace still in `analyzing` at
    /// startup means a crashed mid-discovery run. Reclassify it to `pending` so the pickup step
    /// retries it. Returns the number reclassified.
    pub async fn reclassify_analyzing_to_pending(&self) -> Result<u64> {
        let affected = self
            .conn
            .execute(
                "UPDATE workspaces SET status = ?, updated_at = ? WHERE status = ?",
                db::params![
                    WorkspaceStatus::Pending.to_string(),
                    db::now(),
                    WorkspaceStatus::Analyzing.to_string()
                ],
            )
            .await?;
        if affected > 0 {
            tracing::info!(
                count = affected,
                "Boot recovery: reclassified stranded analyzing workspaces to pending"
            );
        }
        Ok(affected)
    }

    /// Set or clear the maintenance toggle for a workspace. A name with no row is an error
    /// rather than a silent no-op (see [`Self::set_paused`]).
    pub async fn set_maintenance_enabled(&self, name: &str, enabled: bool) -> Result<()> {
        let val: i64 = i64::from(enabled);
        // Enabling clears last_run_at so the maintainer runs on the very next poll cycle; a kept
        // interrupted session resumes regardless (resume bypasses the debounce gate).
        let set_clause = if enabled {
            "maintenance = ?, maintainer_last_run_at = NULL"
        } else {
            "maintenance = ?"
        };
        let affected = self
            .exec_update_with_updated_at(set_clause, vec![Value::from(val)], name)
            .await?;
        anyhow::ensure!(
            affected > 0,
            "No managed workspace exists under the name '{name}'."
        );
        if enabled {
            tracing::info!(workspace = name, "Maintainer enabled");
        } else {
            // Cancel any running maintainer agent for this workspace so it doesn't keep creating
            // tickets after maintenance was disabled.
            if let Some(ws) = self.get_by_name(name).await? {
                crate::agent::registry::AGENT_REGISTRY
                    .cancel_by_role_and_workspace_path(Role::Maintainer.as_str(), &ws.path);
            }
            tracing::info!(workspace = name, "Maintainer disabled");
        }
        Ok(())
    }

    /// Set or clear the pipeline pause toggle for a workspace. A name with no row is an error
    /// rather than a silent no-op: every caller reports the toggle as applied, so a pause that
    /// wrote nothing would be reported as one.
    pub async fn set_paused(&self, name: &str, paused: bool) -> Result<()> {
        let val: i64 = i64::from(paused);
        let affected = self
            .exec_update_with_updated_at("paused = ?", vec![Value::from(val)], name)
            .await?;
        anyhow::ensure!(
            affected > 0,
            "No managed workspace exists under the name '{name}'."
        );
        if paused {
            // The user/operator/failure pause — the one pause set through this method. The
            // discovery analysis-pause writes `paused` via DIRECT SQL, so it does not trigger this
            // cancel. Every pause entry point funnels through here, so the cancel is guaranteed.
            crate::agent::registry::AGENT_REGISTRY.cancel_by_workspace_pause(name);
            tracing::info!(workspace = name, "Workspace pipeline paused");
        } else {
            // Clear the cooperative pause-stop flags left on in-flight agents so a resumed
            // workspace does not freeze them at their next LLM round boundary.
            crate::agent::registry::AGENT_REGISTRY.clear_workspace_pause(name);
            tracing::info!(workspace = name, "Workspace pipeline resumed");
        }
        Ok(())
    }

    /// Pause every managed workspace — the `mahbot paused` startup mode. Each row goes
    /// through [`Self::set_paused`], so the pause is the ordinary one; rows already
    /// paused are left untouched. Returns the number of managed workspaces, all of them
    /// now paused. Personal workspaces have no row here.
    pub async fn pause_all(&self) -> Result<usize> {
        let workspaces = self.list().await?;
        for ws in &workspaces {
            if !ws.paused {
                self.set_paused(&ws.name, true).await?;
            }
        }
        Ok(workspaces.len())
    }

    /// Record a completed maintainer run by writing `maintainer_last_run_at`
    /// (plus `updated_at`). The debounce interval itself is the fixed
    /// [`Workspace::MAINTAINER_DEBOUNCE_MINS`] — the per-workspace adaptive
    /// value was retired.
    pub async fn set_maintainer_last_run_at(&self, name: &str, last_run_at: &str) -> Result<()> {
        self.exec_update_with_updated_at(
            "maintainer_last_run_at = ?",
            vec![Value::from(last_run_at)],
            name,
        )
        .await
        .map(|_| ())
    }

    /// Store the per-workspace maintainer recommendations blob (replace-only) —
    /// a JSON object {"recommendations": [...], "generated_at": RFC3339} produced
    /// by the post-run maintainer extraction. `None` clears it.
    pub(crate) async fn set_maintainer_recommendations(
        &self,
        name: &str,
        json: Option<&str>,
    ) -> Result<()> {
        self.exec_update_with_updated_at(
            "maintainer_recommendations = ?",
            vec![Value::from(json)],
            name,
        )
        .await
        .map(|_| ())
    }

    /// Read the raw maintainer recommendations JSON blob (None = absent/NULL).
    pub(crate) async fn get_maintainer_recommendations(
        &self,
        name: &str,
    ) -> Result<Option<String>> {
        Ok(self
            .conn
            .query_optional(
                "SELECT maintainer_recommendations FROM workspaces WHERE name = ?1",
                db::params![name],
                |row| row.get::<Option<String>>(0),
            )
            .await?
            .flatten())
    }

    /// Store discovered diagnostics commands for a workspace.
    ///
    /// Also bumps `diagnostics_generation` so any in-flight diagnostics
    /// discovery task will see a generation mismatch and skip its stale write
    /// (see [`check_generation`]).
    pub(crate) async fn set_diagnostics(
        &self,
        name: &str,
        commands: &crate::DiagnosticsCommands,
    ) -> Result<()> {
        let json = serde_json::to_string(commands)?;
        self.exec_update_with_updated_at(
            "diagnostics = ?, diagnostics_generation = diagnostics_generation + 1",
            vec![Value::from(json)],
            name,
        )
        .await
        .map(|_| ())
    }

    pub(crate) async fn get_diagnostics(
        &self,
        name: &str,
    ) -> Result<Option<crate::DiagnosticsCommands>> {
        // query_optional + flatten preserves the NULL-vs-missing conflation:
        // a NULL diagnostics column and a missing row both yield None.
        let json: Option<String> = self
            .conn
            .query_optional(
                "SELECT diagnostics FROM workspaces WHERE name = ?1",
                db::params![name],
                |row| row.get::<Option<String>>(0),
            )
            .await?
            .flatten();
        Ok(json.map(|json| serde_json::from_str(&json)).transpose()?)
    }

    /// Set freeform user-curated context notes for a workspace.
    ///
    /// Truncates to `MAX_WORKSPACE_NOTES_CHARS` characters as defense-in-depth
    /// against prompt bloat. Notes are appended to every agent's system prompt.
    pub async fn set_notes(&self, name: &str, notes: &str) -> Result<()> {
        let notes = truncate_workspace_notes(notes);
        self.exec_update_with_updated_at("notes = ?", vec![Value::from(notes)], name)
            .await
            .map(|_| ())
    }

    /// Clear all workspace context rows (role-keyed and the general NULL-role
    /// row) for a workspace.
    /// Called by [`Self::rediscover`] before spawning a new discovery task so that
    /// stale context entries from a previous discovery don't persist.
    async fn clear_contexts(&self, name: &str) -> Result<()> {
        self.conn
            .execute(
                "DELETE FROM workspace_contexts WHERE workspace_name = ?1",
                db::params![name],
            )
            .await?;
        Ok(())
    }

    /// Read the current generation counter for a workspace's `column`.
    ///
    /// Used by discovery tasks to check whether the counter was bumped while
    /// they ran; if it no longer matches, their writes are stale.
    async fn get_generation(&self, name: &str, column: GenerationColumn) -> Result<i64> {
        self.conn
            .query_row(
                &format!("SELECT {} FROM workspaces WHERE name = ?1", column.name),
                db::params![name],
                |row| row.get(0),
            )
            .await
            .map_err(Into::into)
    }

    /// Trigger re-analysis: status back to `analyzing`, stale per-role contexts cleared,
    /// and analysis spawned with a fresh generation counter. Unlike
    /// [`Self::rediscover_diagnostics`] this does **not** clear diagnostics — they are
    /// preserved untouched, and diagnostics discovery runs only when none exist yet (a
    /// never-analyzed `Pending` workspace re-analyzed manually would otherwise reach
    /// Ready with none). Manual Re-analyze bypasses the pending-pickup cooldown by
    /// design, so any in-memory cooldown is cleared here.
    pub async fn rediscover(&self, name: &str) -> Result<()> {
        let ws = self
            .get_by_name(name)
            .await?
            .ok_or_else(|| anyhow::anyhow!("Workspace {name} not found"))?;

        // Atomically increment the discovery generation counter so any
        // still-running discovery task from a previous rediscover will
        // see a generation mismatch and skip its writes.
        // NOTE: diagnostics is deliberately NOT cleared — user-managed
        // diagnostics survive re-analysis.
        self.exec_update_with_updated_at(
            "discovery_generation = discovery_generation + 1, status = ?, paused = 1",
            vec![Value::from(WorkspaceStatus::Analyzing.to_string())],
            name,
        )
        .await?;

        clear_pending_pickup_cooldown(name);

        // Clear stale per-role context entries so that old discovery tasks
        // that beat the generation check cannot leave partial data behind.
        self.clear_contexts(name).await?;

        let generation = self
            .get_generation(name, GenerationColumn::DISCOVERY)
            .await?;
        // Skip diagnostics discovery when diagnostics already exist so
        // user-managed diagnostics survive re-analysis; discover them on a
        // never-analyzed workspace (the same rule the pending pickup uses).
        let discover_diagnostics = ws.diagnostics.is_none();
        spawn_workspace_discovery(&ws, generation, discover_diagnostics);

        Ok(())
    }

    /// Re-discover diagnostics commands for an existing workspace (without
    /// re-running per-role context discovery).
    ///
    /// Bumps the diagnostics generation (invalidating any in-flight diagnostics
    /// discovery tasks), clears the current diagnostics, and spawns a lightweight
    /// diagnostics-only discovery task.
    ///
    /// Unlike [`Self::rediscover`], this does **not** touch workspace status,
    /// paused state, per-role contexts, or the discovery generation counter.
    pub async fn rediscover_diagnostics(&self, name: &str) -> Result<()> {
        let ws = self
            .get_by_name(name)
            .await?
            .ok_or_else(|| anyhow::anyhow!("Workspace {name} not found"))?;

        // Bump diagnostics_generation and clear diagnostics so the fresh
        // discovery starts from scratch. The generation bump also cancels
        // any in-flight diagnostics discovery tasks. Does NOT touch
        // discovery_generation — role discovery is unaffected.
        self.exec_update_with_updated_at(
            "diagnostics_generation = diagnostics_generation + 1, diagnostics = NULL",
            vec![],
            name,
        )
        .await?;

        let generation = self
            .get_generation(name, GenerationColumn::DIAGNOSTICS)
            .await?;
        spawn_diagnostics_discovery(&ws, generation);

        Ok(())
    }

    pub async fn get_context(&self, name: &str, role: &str) -> Result<Option<String>> {
        self.conn
            .query_optional(
                "SELECT content FROM workspace_contexts WHERE workspace_name = ?1 AND role = ?2",
                db::params![name, role],
                |row| row.get::<String>(0),
            )
            .await
    }

    async fn set_context(&self, name: &str, role: &str, content: &str) -> Result<()> {
        let now = db::now();
        self.conn
            .upsert_row(
                "UPDATE workspace_contexts SET content = ?1, created_at = ?2 \
                 WHERE workspace_name = ?3 AND role = ?4",
                || db::params![content, now.as_str(), name, role],
                "INSERT INTO workspace_contexts (workspace_name, role, content, created_at) VALUES (?1, ?2, ?3, ?4) \
                 ON CONFLICT(workspace_name, role) DO NOTHING",
                db::params![name, role, content, now.as_str()],
            )
            .await?;
        Ok(())
    }

    /// Get the general (non-role) workspace context, or `None` when discovery
    /// has not produced one yet.
    pub async fn get_general_context(&self, name: &str) -> Result<Option<String>> {
        self.conn
            .query_optional(
                "SELECT content FROM workspace_contexts WHERE workspace_name = ?1 AND role IS NULL",
                db::params![name],
                |row| row.get::<String>(0),
            )
            .await
    }

    /// Upsert the general (non-role) workspace context. The partial unique
    /// index guarantees at most one NULL-role row per workspace.
    async fn set_general_context(&self, name: &str, content: &str) -> Result<()> {
        let now = db::now();
        self.conn
            .upsert_row(
                "UPDATE workspace_contexts SET content = ?1, created_at = ?2 \
                 WHERE workspace_name = ?3 AND role IS NULL",
                || db::params![content, now.as_str(), name],
                "INSERT INTO workspace_contexts (workspace_name, role, content, created_at) VALUES (?1, NULL, ?2, ?3) \
                 ON CONFLICT(workspace_name) WHERE role IS NULL DO NOTHING",
                db::params![name, content, now.as_str()],
            )
            .await?;
        Ok(())
    }

    /// Save the current set of open editor tabs for a workspace. Replaces all existing records for
    /// this workspace.
    pub async fn save_editor_tabs(&self, name: &str, tabs: &[EditorTabRecord]) -> Result<()> {
        let tx = self.conn.begin_tx().await?;
        tx.execute(
            "DELETE FROM editor_tabs WHERE workspace_name = ?1",
            db::params![name],
        )
        .await?;
        for tab in tabs {
            tx.execute(
                "INSERT INTO editor_tabs (workspace_name, file_path, tab_order, is_active, is_dirty, dirty_content) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                db::params![
                    name,
                    tab.file_path.clone(),
                    i64::try_from(tab.tab_order).unwrap_or(i64::MAX),
                    i64::from(tab.is_active),
                    i64::from(tab.is_dirty),
                    tab.dirty_content.clone(),
                ],
            )
            .await?;
        }
        tx.commit().await?;
        Ok(())
    }

    pub async fn load_editor_tabs(&self, name: &str) -> Result<Vec<EditorTabRecord>> {
        let rows = self.conn
            .query_map(
                &format!("SELECT {EDITOR_TAB_COLUMNS} FROM editor_tabs WHERE workspace_name = ?1 ORDER BY tab_order"),
                db::params![name],
                |row| -> std::result::Result<EditorTabRecord, String> {
                    Ok(EditorTabRecord {
                        file_path: row
                            .get::<String>(COL_ET_FILE_PATH)
                            .map_err(|e| format!("failed to read file_path: {e}"))?,
                        tab_order: usize::try_from(
                            row.get::<i64>(COL_ET_TAB_ORDER)
                                .map_err(|e| format!("failed to read tab_order: {e}"))?,
                        )
                        .unwrap_or(0),
                        is_active: row
                            .get::<bool>(COL_ET_IS_ACTIVE)
                            .map_err(|e| format!("failed to read is_active: {e}"))?,
                        is_dirty: row
                            .get::<bool>(COL_ET_IS_DIRTY)
                            .map_err(|e| format!("failed to read is_dirty: {e}"))?,
                        dirty_content: row
                            .get::<Option<String>>(COL_ET_DIRTY_CONTENT)
                            .map_err(|e| format!("failed to read dirty_content: {e}"))?,
                    })
                },
            )
            .await?;
        let mut tabs = Vec::new();
        for row in rows {
            let tab = row.map_err(|e| anyhow::anyhow!("Failed to parse editor tab row: {e}"))?;
            if tab.file_path.is_empty() || tab.file_path.trim().is_empty() {
                // Defense-in-depth: the file_path column is NOT NULL in the
                // schema and DB errors now propagate before reaching this check,
                // but an empty string could still appear via corruption or other
                // code paths constructing EditorTabRecord. Skip rather than
                // resolve to workspace root.
                warn!(
                    workspace = %name,
                    tab_order = tab.tab_order,
                    "Skipping editor tab with empty file_path — would resolve to workspace root"
                );
                continue;
            }
            tabs.push(tab);
        }
        Ok(tabs)
    }
}

/// A single editor tab record for persistence.
#[derive(Debug, Clone)]
pub struct EditorTabRecord {
    pub file_path: String,
    pub tab_order: usize,
    pub is_active: bool,
    pub is_dirty: bool,
    /// Unsaved buffer text when `is_dirty` is true.
    pub dirty_content: Option<String>,
}

/// `config_kv` key holding the RFC 3339 UTC timestamp of the last nightly rediscovery
/// pass start. Deliberately not a `workspaces` column: rows are deleted during
/// rediscovery, so the timestamp must outlive workspace churn. It sits in the preserved
/// shared namespace, which reload does not purge.
pub(crate) const NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY: &str = "nightly_discovery_last_pass_at";

/// Returns `true` when the given local hour falls within the nightly
/// re-analysis window (2:00–3:00 AM, inclusive of 2, exclusive of 3).
fn is_nightly_check_hour(local_hour: u32) -> bool {
    (2..3).contains(&local_hour)
}

/// Whether the rolling 7-day frequency gate allows a nightly pass: no pass recorded yet
/// (`None`), an unparseable timestamp (fail-open — the pass-start write self-heals the
/// stored state), or at least 7 × 24 h of wall-clock time elapsed since the recorded
/// pass start (DST-safe, no fixed weekday). A well-formed timestamp less than 7 days old
/// blocks the pass, including a future one (clock skew), so regeneration happens at most
/// once per 7 days.
fn nightly_gate_allows(last_pass_at: Option<&str>, now: DateTime<Utc>) -> bool {
    match last_pass_at {
        None => true,
        Some(raw) => match db::parse_utc_timestamp(raw) {
            Ok(last) => now.signed_duration_since(last) >= chrono::Duration::days(7),
            Err(e) => {
                warn!(
                    nightly_discovery_last_pass_at = %raw,
                    error = %e,
                    "Failed to parse nightly discovery last-pass timestamp, letting through"
                );
                true
            }
        },
    }
}

/// Evaluate the 7-day gate and, when the pass is allowed, record the pass start in
/// `config_kv` BEFORE any workspace processing: a pass that starts counts even if it
/// finds nothing or is interrupted. A read failure (missing store, read error,
/// unparseable value) fails open and the write self-heals the state; a pass-start write
/// failure fails closed, so the at-most-once-per-7-days invariant holds.
async fn nightly_gate_should_run(config_store: Option<&ConfigStore>) -> bool {
    // Fail-open on read.
    let last_pass_at = if let Some(store) = config_store {
        match store.get_kv(NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY).await {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "Nightly check: failed to read last-pass timestamp — running pass ungated"
                );
                None
            }
        }
    } else {
        tracing::warn!("Nightly check: CONFIG_STORE not initialized — running pass ungated");
        None
    };

    if !nightly_gate_allows(last_pass_at.as_deref(), Utc::now()) {
        tracing::debug!("Nightly check: last pass is less than 7 days old — skipping this night");
        return false;
    }

    // Record the pass start. Fail-closed: skip the pass when the timestamp
    // cannot be recorded.
    if let Some(store) = config_store {
        let started_at = db::now();
        if let Err(e) = store
            .set_kv(NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY, &started_at)
            .await
        {
            tracing::warn!(
                error = %e,
                "Nightly check: failed to record pass start — skipping this pass"
            );
            return false;
        }
    }

    true
}

/// Returns `true` when rediscovery should be triggered because the
/// workspace has new git commits relative to its stored analysis state.
fn has_new_commits(last_analyzed_commit: Option<&str>, current_hash: &str) -> bool {
    match last_analyzed_commit {
        Some(stored) => stored != current_hash,
        None => true,
    }
}

/// Run the nightly re-analysis loop: wake every 30 minutes and, inside the 2:00–3:00 AM
/// local window, run one discovery pass — each Ready workspace whose HEAD differs from
/// the stored analysis commit is rediscovered. The pass is gated to at most one per 7
/// days (see [`nightly_gate_should_run`]); missed windows do not accumulate.
///
/// Workspaces are processed sequentially, so each discovery completes before the next is
/// checked. Edge cases: an empty pass still counts (the timestamp is written first, so an
/// unpause right after waits for the next eligible night — manual Re-analyze stays
/// available); a non-git workspace or one whose path is gone is skipped with a warning,
/// and since `last_analyzed_commit` stays NULL there is no re-discovery loop; a batch
/// that starts before 3:00 is finished, as the window is checked once per wake cycle.
pub async fn run_nightly_check_loop() {
    let interval = Duration::from_mins(30);
    let shutdown = crate::shutdown::shutdown_token();

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

        if !is_nightly_check_hour(chrono::Local::now().hour()) {
            continue;
        }

        // Rolling frequency gate: at most one pass per 7 days, measured from
        // pass start. Fail-open on read (missing store / read error /
        // unparseable value), fail-closed on the pass-start write — see
        // [`nightly_gate_should_run`].
        if !nightly_gate_should_run(crate::config_db::CONFIG_STORE.get()).await {
            continue;
        }

        let store = if let Some(s) = WORKSPACES.get() {
            s.clone()
        } else {
            tracing::warn!("Nightly check: WORKSPACES not initialized");
            continue;
        };

        let workspaces = match store.list().await {
            Ok(list) => list,
            Err(e) => {
                tracing::warn!(error = %e, "Nightly check: failed to list workspaces");
                continue;
            }
        };

        // Process Ready workspaces sequentially to avoid LLM resource spikes.
        for ws in &workspaces {
            if shutdown.is_cancelled() {
                break;
            }

            if ws.status != WorkspaceStatus::Ready || ws.paused {
                // Paused workspaces are skipped: a pause (including an automatic
                // technical-failure pause) is only lifted via the normal unpause
                // path — nightly rediscovery must not silently resume it.
                continue;
            }

            let repo_path = std::path::Path::new(&ws.path);

            let current_hash = match crate::git::commands::run_git_head(repo_path).await {
                Ok(hash) => hash,
                Err(e) => {
                    // Non-git workspace, no commits, or git not available — skip.
                    tracing::debug!(
                        workspace = %ws.name,
                        error = %e,
                        "Nightly check: git rev-parse HEAD failed — skipping workspace",
                    );
                    continue;
                }
            };

            let should_rediscover =
                has_new_commits(ws.last_analyzed_commit.as_deref(), &current_hash);

            if !should_rediscover {
                tracing::debug!(
                    workspace = %ws.name,
                    "Nightly check: no new commits — skipping",
                );
                continue;
            }

            tracing::info!(
                workspace = %ws.name,
                "Nightly check: new commits detected — triggering rediscover",
            );

            if let Err(e) = store.rediscover(&ws.name).await {
                tracing::warn!(
                    workspace = %ws.name,
                    error = %e,
                    "Nightly check: rediscover failed",
                );
                continue;
            }

            // Wait for discovery to complete before checking the next workspace.
            // Poll status every 10 seconds with a generous timeout (4 hours).
            let deadline = std::time::Instant::now() + Duration::from_hours(4);
            loop {
                if shutdown.is_cancelled() {
                    break;
                }
                if std::time::Instant::now() >= deadline {
                    tracing::warn!(
                        workspace = %ws.name,
                        "Nightly check: discovery timed out — proceeding to next workspace",
                    );
                    break;
                }

                tokio::time::sleep(Duration::from_secs(10)).await;

                match store.get_by_name(&ws.name).await {
                    Ok(Some(current)) if current.status != WorkspaceStatus::Analyzing => {
                        break;
                    }
                    Ok(_) => {} // Still analyzing — keep polling.
                    Err(e) => {
                        tracing::warn!(
                            workspace = %ws.name,
                            error = %e,
                            "Nightly check: failed to poll workspace status",
                        );
                        break;
                    }
                }
            }
        }
    }
}

/// Create a minimal [`Workspace`] from a path for testing.
/// The name is derived from the path's file name.
#[cfg(test)]
#[must_use]
pub fn test_ws(path: impl AsRef<std::path::Path>) -> Workspace {
    Workspace::from_path(path.as_ref())
}

/// Create a minimal [`Workspace`] with an explicit path and name.
#[cfg(test)]
#[must_use]
pub fn test_ws_named(path: &str, name: &str) -> Workspace {
    Workspace {
        name: name.to_string(),
        path: path.to_string(),
        ..Default::default()
    }
}

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

    /// Open a temporary workspace store for testing.
    /// Returns (store, temp_dir). The temp_dir is kept alive for the lifetime
    /// of the store (~ the test function).
    async fn test_store() -> (WorkspaceStore, TempDir) {
        crate::open_test_store!(WorkspaceStore, "workspace")
    }

    /// Helper: insert a workspace row directly with full control over fields,
    /// bypassing `add()` (which has side-effects like initializing search
    /// engine globals).
    async fn insert_direct(
        store: &WorkspaceStore,
        name: &str,
        path: &str,
        paused: bool,
        maintenance_enabled: bool,
        discovery_generation: i64,
        diagnostics_generation: i64,
    ) -> Workspace {
        let now = crate::db::now();
        let paused_int: i64 = i64::from(paused);
        let maint_int: i64 = i64::from(maintenance_enabled);
        store
            .conn
            .execute(
                "INSERT INTO workspaces (name, path, created_at, updated_at, paused, maintenance, discovery_generation, diagnostics_generation) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                crate::db::params![name, path, now.clone(), now.clone(), paused_int, maint_int, discovery_generation, diagnostics_generation],
            )
            .await
            .expect("insert workspace");
        Workspace {
            name: name.to_string(),
            path: path.to_string(),
            status: WorkspaceStatus::Pending,
            maintenance_enabled,
            paused,
            maintainer_last_run_at: None,
            diagnostics: None,
            notes: String::new(),
            last_analyzed_commit: None,
        }
    }

    #[tokio::test]
    async fn schema_default_is_paused() {
        // Insert WITHOUT specifying paused, relying on the schema DEFAULT.
        let (store, _tmp) = test_store().await;
        let now = crate::db::now();
        store
            .conn
            .execute(
                "INSERT INTO workspaces (name, path, created_at, updated_at) \
                 VALUES (?1, ?2, ?3, ?4)",
                crate::db::params!["schema_test", "/tmp/schema_test", now.clone(), now.clone()],
            )
            .await
            .expect("insert workspace");

        let ws = store
            .get_by_name("schema_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(
            ws.paused,
            "Schema DEFAULT should produce paused = true for new rows"
        );
    }

    #[tokio::test]
    async fn set_paused_toggles_pause_state() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "toggle_test", "/tmp/toggle_test", true, false, 0, 0).await;

        store.set_paused("toggle_test", false).await.unwrap();
        let fetched = store
            .get_by_name("toggle_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(
            !fetched.paused,
            "Should be unpaused after set_paused(false)"
        );

        store.set_paused("toggle_test", true).await.unwrap();
        let fetched = store
            .get_by_name("toggle_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(fetched.paused, "Should be paused after set_paused(true)");

        // A name with no row is refused: the toggle is reported as applied by
        // every caller, so it must not silently do nothing.
        let err = store
            .set_paused("toggle_test_absent", true)
            .await
            .expect_err("an unknown workspace must be refused");
        assert!(
            err.to_string().contains("No managed workspace exists"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn pause_all_pauses_every_managed_workspace() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "all_ready", "/tmp/all_ready", false, false, 0, 0).await;
        insert_direct(&store, "all_paused", "/tmp/all_paused", true, false, 0, 0).await;

        assert_eq!(store.pause_all().await.unwrap(), 2);
        for name in ["all_ready", "all_paused"] {
            let ws = store.get_by_name(name).await.unwrap().expect("exists");
            assert!(ws.paused, "{name} must be paused");
        }
    }

    #[tokio::test]
    async fn set_maintenance_toggles_maintenance_state() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "maint_test", "/tmp/maint_test", true, false, 0, 0).await;

        store
            .set_maintenance_enabled("maint_test", true)
            .await
            .unwrap();
        let fetched = store
            .get_by_name("maint_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(
            fetched.maintenance_enabled,
            "Should have maintenance enabled after set_maintenance_enabled(true)"
        );

        store
            .set_maintenance_enabled("maint_test", false)
            .await
            .unwrap();
        let fetched = store
            .get_by_name("maint_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(
            !fetched.maintenance_enabled,
            "Should have maintenance disabled after set_maintenance_enabled(false)"
        );

        // A name with no row is refused rather than reported as a write that
        // happened — the footer toggle must not claim success for nothing.
        assert!(
            store
                .set_maintenance_enabled("no_such_ws", true)
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn set_notes_roundtrip() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "notes_test", "/tmp/notes_test", true, false, 0, 0).await;

        // Initial state should be empty string (NOT NULL DEFAULT '')
        let ws = store
            .get_by_name("notes_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(ws.notes.is_empty(), "New workspace should have empty notes");

        let test_notes = "These are important context notes for agents.";
        store
            .set_notes("notes_test", test_notes)
            .await
            .expect("set_notes");
        let ws = store
            .get_by_name("notes_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert_eq!(ws.notes, test_notes, "Notes should round-trip correctly");

        let updated_notes = "Updated notes with more context.";
        store
            .set_notes("notes_test", updated_notes)
            .await
            .expect("set_notes");
        let ws = store
            .get_by_name("notes_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert_eq!(
            ws.notes, updated_notes,
            "Notes update should round-trip correctly"
        );

        let long_notes = "x".repeat(MAX_WORKSPACE_NOTES_CHARS + 1000);
        store
            .set_notes("notes_test", &long_notes)
            .await
            .expect("set_notes");
        let ws = store
            .get_by_name("notes_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert_eq!(
            ws.notes.chars().count(),
            MAX_WORKSPACE_NOTES_CHARS,
            "Notes should be truncated to {MAX_WORKSPACE_NOTES_CHARS} chars"
        );
        assert_eq!(
            ws.notes,
            "x".repeat(MAX_WORKSPACE_NOTES_CHARS),
            "Notes content should match truncated"
        );

        let multi_byte = "é".repeat(MAX_WORKSPACE_NOTES_CHARS + 1000);
        store
            .set_notes("notes_test", &multi_byte)
            .await
            .expect("set_notes");
        let ws = store
            .get_by_name("notes_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert_eq!(
            ws.notes.chars().count(),
            MAX_WORKSPACE_NOTES_CHARS,
            "Notes should be truncated to {MAX_WORKSPACE_NOTES_CHARS} chars (multi-byte)"
        );
        assert_eq!(
            ws.notes,
            "é".repeat(MAX_WORKSPACE_NOTES_CHARS),
            "Notes content should match truncated (multi-byte, no broken chars)"
        );
    }

    #[tokio::test]
    async fn finalize_discovery_success_auto_unpauses() {
        for (suffix, generation) in [("gen0", 0), ("gen1", 1)] {
            let (store, _tmp) = test_store().await;
            insert_direct(
                &store,
                suffix,
                &format!("/tmp/{suffix}"),
                true,
                false,
                generation,
                generation,
            )
            .await;
            finalize_discovery(
                &store,
                suffix,
                &format!("/tmp/{suffix}"),
                generation,
                DiscoveryOutcome::AllOk,
                &[],
            )
            .await;

            let ws = store
                .get_by_name(suffix)
                .await
                .expect("fetch")
                .expect("exists");
            assert!(
                !ws.paused,
                "Should auto-unpause after discovery OK (gen {generation})"
            );
            assert_eq!(
                ws.status,
                WorkspaceStatus::Ready,
                "Status should be 'ready'"
            );
        }
    }

    #[tokio::test]
    async fn finalize_discovery_failure_keeps_paused() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "fail_gen0", "/tmp/fail_gen0", true, false, 0, 0).await;

        // Act: discovery failed with a genuine (non-provider) failure
        // (outcome = Fatal) — must be terminal Failed as before.
        let errors = vec!["Empty response for 'general'".to_string()];
        finalize_discovery(
            &store,
            "fail_gen0",
            "/tmp/fail_gen0",
            0,
            DiscoveryOutcome::Fatal,
            &errors,
        )
        .await;

        let ws = store
            .get_by_name("fail_gen0")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(ws.paused, "Should remain paused after discovery failure");
        assert_eq!(
            ws.status,
            WorkspaceStatus::Failed,
            "Status should be 'failed'"
        );
    }

    #[tokio::test]
    async fn finalize_discovery_provider_failure_returns_to_pending() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "prov_gen0", "/tmp/prov_gen0", true, false, 0, 0).await;

        // Act: discovery failed with provider-class failures only
        // (outcome = Transient) — must return to Pending and arm the cooldown.
        let errors = vec![
            "Diagnostics discovery failed: exhausted retry budget (last: transport): connection reset"
                .to_string(),
        ];
        finalize_discovery(
            &store,
            "prov_gen0",
            "/tmp/prov_gen0",
            0,
            DiscoveryOutcome::Transient,
            &errors,
        )
        .await;

        let ws = store
            .get_by_name("prov_gen0")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(ws.paused, "Should remain paused (analysis pause)");
        assert_eq!(
            ws.status,
            WorkspaceStatus::Pending,
            "Provider-class discovery failure should return the workspace to pending"
        );
        assert!(
            pending_pickup_cooldown_active("prov_gen0"),
            "Provider-class failure must arm the in-memory pickup cooldown"
        );
        // A successful finalize clears the cooldown.
        finalize_discovery(
            &store,
            "prov_gen0",
            "/tmp/prov_gen0",
            0,
            DiscoveryOutcome::AllOk,
            &[],
        )
        .await;
        assert!(
            !pending_pickup_cooldown_active("prov_gen0"),
            "Successful discovery must clear the pickup cooldown"
        );
    }

    #[tokio::test]
    async fn finalize_discovery_stale_generation_skips_writes() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "stale", "/tmp/stale", true, false, 0, 0).await;

        // Bump the generation behind the scenes (simulates a concurrent
        // rediscover() call).
        store
            .exec_update_with_updated_at("discovery_generation = 1", vec![], "stale")
            .await
            .expect("bump generation");

        finalize_discovery(
            &store,
            "stale",
            "/tmp/stale",
            0,
            DiscoveryOutcome::AllOk,
            &[],
        )
        .await;

        let ws = store
            .get_by_name("stale")
            .await
            .expect("fetch")
            .expect("exists");
        // The writes should have been skipped because the generation
        // no longer matches.
        assert!(
            ws.paused,
            "Should stay paused — writes skipped by generation guard"
        );
        assert_eq!(
            ws.status,
            WorkspaceStatus::Pending,
            "Status should remain unchanged — writes skipped"
        );
    }

    #[tokio::test]
    async fn rediscover_sets_paused() {
        let (store, _tmp) = test_store().await;
        insert_direct(
            &store,
            "rediscover_test",
            "/tmp/rediscover_test",
            false,
            false,
            0,
            0,
        )
        .await;
        store
            .set_status("rediscover_test", &WorkspaceStatus::Ready)
            .await
            .unwrap();

        let ws = store
            .get_by_name("rediscover_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(!ws.paused, "Precondition: workspace should start unpaused");
        assert_eq!(
            ws.status,
            WorkspaceStatus::Ready,
            "Precondition: status should be 'ready'"
        );

        store
            .rediscover("rediscover_test")
            .await
            .expect("rediscover");

        let ws = store
            .get_by_name("rediscover_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(
            ws.paused,
            "rediscover() must set paused = true when transitioning to 'analyzing'"
        );
    }

    #[tokio::test]
    #[serial_test::serial(config_persist)] // swaps the process-global CONFIG
    async fn add_persists_and_returns_the_workspace_row() {
        let (store, _tmp) = test_store().await;
        let dir = TempDir::new().expect("temp dir for workspace path");

        // add() requires: search engine globals initialized + CONFIG storage
        // root set. Initialize the minimum globals (init_global is idempotent).
        crate::workspace_index::init_global();
        // Point the storage root at the shared test root. A per-test TempDir
        // would leave the global storage root pointing at a deleted directory
        // once the TempDir drops — the shared root lives for the whole
        // process and is removed at process exit.
        let _ = crate::config::CONFIG.try_set_storage_root(crate::util::test::test_root().clone());
        crate::config::CONFIG.swap(crate::config::ConfigData::STRUCT_FIELDS_DEFAULT);

        let ws = store
            .add("add_test", dir.path().to_str().unwrap())
            .await
            .expect("add workspace");

        assert!(
            ws.paused,
            "add() must return a Workspace with paused = true"
        );
        assert_eq!(
            ws.status,
            WorkspaceStatus::Pending,
            "add() must return a Workspace with status = pending — \
             discovery is deferred to the pickup step until the provider is configured"
        );
        // Pins schema defaults (add() reads them back via RETURNING).
        assert!(
            !ws.maintenance_enabled,
            "add() must return a Workspace with maintenance_enabled = false"
        );

        // Judged through the OS, not against the constructor that produced it. Only the
        // no-verbatim check needs a Windows host to fail: a verbatim root still resolves,
        // separator and all.
        assert_eq!(
            std::fs::canonicalize(&ws.path).expect("the platform must resolve the stored root"),
            std::fs::canonicalize(dir.path()).expect("canonicalize the managed dir"),
            "the stored root must resolve to the managed directory"
        );
        assert!(
            !ws.path.contains(r"\\?\"),
            "no consumer may receive the platform's verbatim form: {:?}",
            ws.path
        );
        assert!(
            ws.path.ends_with(std::path::MAIN_SEPARATOR),
            "a managed root keeps the trailing separator it has always been \
             shown with: {:?}",
            ws.path
        );

        let fetched = store
            .get_by_name("add_test")
            .await
            .expect("fetch")
            .expect("exists");
        assert!(
            fetched.paused,
            "Persisted workspace must have paused = true"
        );
        assert_eq!(
            fetched.status,
            WorkspaceStatus::Pending,
            "Persisted workspace must have status = pending"
        );
    }

    /// Adding a folder makes it a repository with nothing committed in it, and adding a folder
    /// that already is a repository leaves that repository exactly as it was.
    #[tokio::test]
    #[serial_test::serial(config_persist)] // swaps the process-global CONFIG
    async fn add_initialises_a_repository_only_when_the_folder_has_none() {
        let (store, _tmp) = test_store().await;
        crate::workspace_index::init_global();
        let _ = crate::config::CONFIG.try_set_storage_root(crate::util::test::test_root().clone());
        crate::config::CONFIG.swap(crate::config::ConfigData::STRUCT_FIELDS_DEFAULT);

        // A folder without a repository: `git init` writes `.git` and commits nothing.
        let fresh = TempDir::new().expect("temp dir for workspace path");
        store
            .add("add_git_fresh", fresh.path().to_str().unwrap())
            .await
            .expect("add workspace");
        let entries: Vec<_> = std::fs::read_dir(fresh.path())
            .expect("read the added folder")
            .map(|entry| entry.expect("entry").file_name())
            .collect();
        assert_eq!(
            entries,
            [std::ffi::OsString::from(".git")],
            "`git init` must be all the add creates in the folder"
        );
        assert!(
            crate::git::commands::run_git_command(fresh.path(), &["rev-parse", "HEAD"])
                .await
                .is_err(),
            "the initialised repository must have no commit"
        );

        // A folder that already is a repository: untouched — same HEAD, nothing re-initialised.
        let (_repo, repo_path) = crate::util::test::init_temp_repo();
        let head_before = crate::git::commands::run_git_command(&repo_path, &["rev-parse", "HEAD"])
            .await
            .expect("read HEAD before the add");
        store
            .add("add_git_existing", repo_path.to_str().unwrap())
            .await
            .expect("add existing repository");
        let head_after = crate::git::commands::run_git_command(&repo_path, &["rev-parse", "HEAD"])
            .await
            .expect("read HEAD after the add");
        assert_eq!(
            head_before, head_after,
            "an existing repository must be left exactly as it was"
        );
    }

    #[tokio::test]
    async fn claim_pending_for_discovery_is_atomic_and_returns_live_generation() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "pickup", "/tmp/pickup", true, false, 3, 0).await;

        let generation = store
            .claim_pending_for_discovery("pickup")
            .await
            .expect("claim")
            .expect("pending row should be claimable");
        assert_eq!(generation, 3, "must return the live discovery_generation");

        let ws = store
            .get_by_name("pickup")
            .await
            .expect("fetch")
            .expect("exists");
        assert_eq!(
            ws.status,
            WorkspaceStatus::Analyzing,
            "claim must transition pending → analyzing"
        );
        assert!(ws.paused, "claim must set the analysis pause");

        // A second claim on the same row is a no-op (atomicity guard).
        let second = store
            .claim_pending_for_discovery("pickup")
            .await
            .expect("claim");
        assert!(
            second.is_none(),
            "a non-pending row must not be claimable twice"
        );
    }

    #[tokio::test]
    async fn reclassify_analyzing_to_pending_recovers_stranded_workspaces() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "stranded1", "/tmp/stranded1", true, false, 0, 0).await;
        insert_direct(&store, "stranded2", "/tmp/stranded2", true, false, 0, 0).await;
        insert_direct(&store, "fine", "/tmp/fine", false, false, 0, 0).await;
        store
            .set_status("stranded1", &WorkspaceStatus::Analyzing)
            .await
            .unwrap();
        store
            .set_status("stranded2", &WorkspaceStatus::Analyzing)
            .await
            .unwrap();
        store
            .set_status("fine", &WorkspaceStatus::Ready)
            .await
            .unwrap();

        let affected = store
            .reclassify_analyzing_to_pending()
            .await
            .expect("reclassify");
        assert_eq!(affected, 2, "only analyzing workspaces are reclassified");

        for name in ["stranded1", "stranded2"] {
            let ws = store
                .get_by_name(name)
                .await
                .expect("fetch")
                .expect("exists");
            assert_eq!(
                ws.status,
                WorkspaceStatus::Pending,
                "stranded analyzing workspace must become pending at boot"
            );
        }
        let fine = store
            .get_by_name("fine")
            .await
            .expect("fetch")
            .expect("exists");
        assert_eq!(
            fine.status,
            WorkspaceStatus::Ready,
            "non-analyzing workspaces are untouched"
        );
    }

    /// Build an agent with a preset typed failure class (simulating a failed
    /// run_agent) and classify it.
    fn classify_with(class: Option<crate::retry::FailureClass>) -> DiscoveryFailureKind {
        let ws = test_ws("/tmp/classify_ws");
        let mut agent = crate::Agent::new(
            "classify-test".into(),
            crate::Role::Discovery,
            &ws,
            None,
            String::new(),
            String::new(),
            false,
            None,
            None,
            None,
        );
        agent.failure_class = class;
        classify_discovery_failure(&agent, None)
    }

    #[test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    fn discovery_failure_taxonomy_maps_provider_and_genuine_classes() {
        // classify_discovery_failure consults the process-global drain flag;
        // serialize against the drain-flag writers so a concurrent drain-flag
        // test cannot flip `Fatal` assertions to `Transient` mid-loop (see
        // `failure_classification_recognizes_drain` for the convention).
        // Provider-class → Transient (workspace returns to Pending).
        for class in [
            crate::retry::FailureClass::Transport,
            crate::retry::FailureClass::TruncatedEnvelope,
            crate::retry::FailureClass::NoResponse,
            crate::retry::FailureClass::TruncatedOutput,
            crate::retry::FailureClass::NonRetryable, // auth / quota / invalid model
            crate::retry::FailureClass::Shutdown,
        ] {
            assert_eq!(
                classify_with(Some(class)),
                DiscoveryFailureKind::Transient,
                "{class:?} must be provider-class (Transient)"
            );
        }

        // Genuine failures → Fatal (workspace goes Failed).
        for class in [
            crate::retry::FailureClass::Parse,
            crate::retry::FailureClass::OutOfRangeScore,
            crate::retry::FailureClass::Membership,
            crate::retry::FailureClass::Completeness,
            crate::retry::FailureClass::ContradictionAgents,
            crate::retry::FailureClass::ValidationOther,
        ] {
            assert_eq!(
                classify_with(Some(class)),
                DiscoveryFailureKind::Fatal,
                "{class:?} must be a genuine failure (Fatal)"
            );
        }

        // No typed class (runtime errors, panics) → Fatal.
        assert_eq!(
            classify_with(None),
            DiscoveryFailureKind::Fatal,
            "unclassified runtime failures must be Fatal"
        );
    }

    /// The pickup cooldown's whole lifecycle on its in-memory map: armed, it
    /// gates the pickup; an expired deadline does not; `clear` disarms it; the
    /// duration doubles per consecutive failure up to the 4 h cap, and the
    /// escalation counter increments with each record and is reset by `clear`.
    #[test]
    fn pending_pickup_cooldown_arms_escalates_expires_and_resets() {
        clear_pending_pickup_cooldown("cooldown_ws");
        assert!(
            !pending_pickup_cooldown_active("cooldown_ws"),
            "no cooldown by default"
        );

        record_pending_pickup_cooldown_until(
            "cooldown_ws",
            Instant::now() + Duration::from_mins(1),
        );
        assert!(
            pending_pickup_cooldown_active("cooldown_ws"),
            "armed cooldown must gate the pickup"
        );

        clear_pending_pickup_cooldown("cooldown_ws");
        assert!(
            !pending_pickup_cooldown_active("cooldown_ws"),
            "clear must disarm the cooldown"
        );

        // Expiry: a past deadline no longer gates the pickup.
        let past = Instant::now()
            .checked_sub(Duration::from_mins(1))
            .expect("instant subtraction cannot underflow in a test");
        record_pending_pickup_cooldown_until("cooldown_ws", past);
        assert!(
            !pending_pickup_cooldown_active("cooldown_ws"),
            "an expired cooldown must not gate the pickup"
        );
        clear_pending_pickup_cooldown("cooldown_ws");

        // The cooldown duration doubles per consecutive failure, capped at 4h.
        assert_eq!(pending_pickup_cooldown_duration(1), Duration::from_mins(15));
        assert_eq!(pending_pickup_cooldown_duration(2), Duration::from_mins(30));
        assert_eq!(pending_pickup_cooldown_duration(3), Duration::from_hours(1));
        assert_eq!(pending_pickup_cooldown_duration(4), Duration::from_hours(2));
        assert_eq!(
            pending_pickup_cooldown_duration(5),
            Duration::from_hours(4),
            "escalation caps at 4 h"
        );
        assert_eq!(
            pending_pickup_cooldown_duration(99),
            Duration::from_hours(4),
            "escalation never exceeds the 4 h cap"
        );

        // Consecutive production records increment the stored attempt count
        // (the escalation driver); clear resets it.
        clear_pending_pickup_cooldown("escalate_ws");
        record_pending_pickup_cooldown("escalate_ws");
        record_pending_pickup_cooldown("escalate_ws");
        let map = pending_pickup_cooldowns().lock().unwrap_poison();
        let entry = map
            .get("escalate_ws")
            .expect("cooldown entry after two failures");
        assert_eq!(entry.attempts, 2, "two failures → attempt count 2");
        let remaining = entry.deadline.saturating_duration_since(Instant::now());
        assert!(
            remaining >= Duration::from_mins(25),
            "second failure must arm a ~30 min cooldown (got {remaining:?})"
        );
        drop(map);
        clear_pending_pickup_cooldown("escalate_ws");
        assert!(
            !pending_pickup_cooldown_active("escalate_ws"),
            "clear must reset the cooldown"
        );
    }

    #[tokio::test]
    async fn rediscover_diagnostics_clears_and_bumps() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "redia_test", "/tmp/redia_test", false, false, 0, 0).await;

        let cmds = crate::DiagnosticsCommands {
            build: Some("cargo build".into()),
            ..Default::default()
        };
        store
            .set_diagnostics("redia_test", &cmds)
            .await
            .expect("set_diagnostics");
        assert!(
            store
                .get_diagnostics("redia_test")
                .await
                .expect("get_diagnostics")
                .is_some()
        );

        let diag_gen_before = store
            .get_generation("redia_test", GenerationColumn::DIAGNOSTICS)
            .await
            .expect("get_generation");
        assert_eq!(diag_gen_before, 1, "Should be 1 after set_diagnostics");

        store
            .rediscover_diagnostics("redia_test")
            .await
            .expect("rediscover_diagnostics");

        assert!(
            store
                .get_diagnostics("redia_test")
                .await
                .expect("get_diagnostics")
                .is_none(),
            "rediscover_diagnostics should clear diagnostics"
        );

        let diag_gen_after = store
            .get_generation("redia_test", GenerationColumn::DIAGNOSTICS)
            .await
            .expect("get_generation");
        assert_eq!(
            diag_gen_after, 2,
            "rediscover_diagnostics should bump diagnostics_generation to 2"
        );

        let discovery_gen_val = store
            .get_generation("redia_test", GenerationColumn::DISCOVERY)
            .await
            .expect("get_generation");
        assert_eq!(
            discovery_gen_val, 0,
            "rediscover_diagnostics should NOT affect discovery_generation"
        );
    }

    #[tokio::test]
    async fn general_context_roundtrip_single_row_per_workspace() {
        let (store, _tmp) = test_store().await;
        insert_direct(&store, "gctx", "/tmp/gctx", true, false, 0, 0).await;

        assert_eq!(store.get_general_context("gctx").await.unwrap(), None);

        store
            .set_general_context("gctx", "overview v1")
            .await
            .unwrap();
        store
            .set_general_context("gctx", "overview v2")
            .await
            .unwrap();
        assert_eq!(
            store.get_general_context("gctx").await.unwrap().as_deref(),
            Some("overview v2")
        );

        // Partial unique index: a second NULL-role row must be rejected.
        let err = store
            .conn
            .execute(
                "INSERT INTO workspace_contexts (workspace_name, role, content, created_at) \
                 VALUES (?1, NULL, 'dup', ?2)",
                crate::db::params!["gctx", crate::db::now()],
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("UNIQUE"), "got: {err}");

        // Role-keyed rows stay distinct from the NULL-role row.
        store.set_context("gctx", "Manager", "mgr").await.unwrap();
        assert_eq!(
            store.get_general_context("gctx").await.unwrap().as_deref(),
            Some("overview v2")
        );
        assert_eq!(
            store
                .get_context("gctx", "Manager")
                .await
                .unwrap()
                .as_deref(),
            Some("mgr")
        );

        // A second workspace has its own NULL-role row.
        insert_direct(&store, "gctx2", "/tmp/gctx2", true, false, 0, 0).await;
        store
            .set_general_context("gctx2", "other overview")
            .await
            .unwrap();
        assert_eq!(
            store.get_general_context("gctx2").await.unwrap().as_deref(),
            Some("other overview")
        );
    }

    #[test]
    fn nightly_gate_allows_table() {
        // Hold `now` constant across all rows so elapsed-duration
        // computations stay deterministic.
        let now = Utc::now();
        let exact_7d = (now - chrono::Duration::days(7)).to_rfc3339();
        let one_sec_short =
            (now - chrono::Duration::days(7) + chrono::Duration::seconds(1)).to_rfc3339();
        let just_ran = now.to_rfc3339();
        let eight_days = (now - chrono::Duration::days(8)).to_rfc3339();
        let future = (now + chrono::Duration::hours(1)).to_rfc3339();

        let cases: &[(Option<&str>, bool, &str)] = &[
            (
                None,
                true,
                "No recorded pass (first night ever) must be allowed",
            ),
            (
                Some(exact_7d.as_str()),
                true,
                "Exactly 7 days elapsed must be allowed (>= 7 days)",
            ),
            (
                Some(one_sec_short.as_str()),
                false,
                "6d23h59m59s elapsed must be blocked",
            ),
            (
                Some(just_ran.as_str()),
                false,
                "A just-recorded pass must block",
            ),
            (
                Some(eight_days.as_str()),
                true,
                "8 days elapsed must be allowed",
            ),
            (
                Some(future.as_str()),
                false,
                "A future timestamp must block the pass",
            ),
            (
                Some("not-a-timestamp"),
                true,
                "An unparseable timestamp must let the pass through",
            ),
        ];
        for (last, expected, msg) in cases {
            assert_eq!(nightly_gate_allows(*last, now), *expected, "{msg}");
        }
    }

    #[tokio::test]
    async fn nightly_gate_records_pass_start_and_blocks() {
        let (store, _tmp) = crate::open_test_store!(crate::config_db::ConfigStore, "config");

        assert!(
            nightly_gate_should_run(Some(&store)).await,
            "First pass (no stored timestamp) must run",
        );
        assert!(
            store
                .get_kv(NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY)
                .await
                .unwrap()
                .is_some(),
            "Pass start must be recorded in config_kv",
        );

        // Immediately after: the recorded pass start blocks the next pass.
        assert!(
            !nightly_gate_should_run(Some(&store)).await,
            "A second pass within the same 7-day window must be blocked",
        );

        // Corrupt stored value: fail-open, then the pass-start write
        // self-heals with a fresh parseable timestamp.
        store
            .set_kv(NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY, "garbage")
            .await
            .unwrap();
        assert!(
            nightly_gate_should_run(Some(&store)).await,
            "An unparseable stored value must let the pass through",
        );
        let healed = store
            .get_kv(NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY)
            .await
            .unwrap()
            .expect("pass-start write must store a value");
        assert!(
            crate::db::parse_utc_timestamp(&healed).is_ok(),
            "pass-start write must self-heal the stored value",
        );
    }

    #[tokio::test]
    async fn delete_resolves_the_admin_selection_and_clears_guests() {
        // delete() abandons the workspace's jobs through the jobs layer, which reads the
        // shared session store — initialize all stores first. That abandon runs against
        // the GLOBAL store and is a no-op here: this test exercises the selection cleanup
        // only (see jobs::workspace_delete_abandons_all_jobs).
        crate::util::test::init_test_stores().await;
        let (store, _tmp) = test_store().await;
        // delete() removes the workspace's search engine from the global
        // registry (init_global is idempotent).
        crate::workspace_index::init_global();
        for name in ["doomed_ws", "survivor_a", "survivor_b", "survivor_c"] {
            insert_direct(&store, name, &format!("/tmp/{name}"), false, false, 0, 0).await;
        }

        // Seed users via raw SQL: two guests reference the workspace being
        // deleted, one references an unrelated workspace, one has no selection,
        // and the admin's desktop is on the workspace being deleted.
        for (name, ws) in [
            ("alice", Some("doomed_ws")),
            ("bob", Some("doomed_ws")),
            ("carol", Some("other_ws")),
            ("dave", None),
            (crate::users::ADMIN_USER_NAME, Some("doomed_ws")),
        ] {
            store
                .conn
                .execute(
                    "INSERT INTO users (name, selected_workspace) VALUES (?1, ?2)",
                    crate::db::params![name, ws],
                )
                .await
                .expect("seed user");
        }

        // The admin follows the desktop's fallback pick — the first project in
        // the footer switcher's order — not the personal folder.
        assert_eq!(
            store.delete("doomed_ws").await.expect("delete workspace"),
            Some("survivor_a".to_string())
        );

        assert!(
            store.get_by_name("doomed_ws").await.unwrap().is_none(),
            "the workspace row must be deleted"
        );

        // Guest selections referencing it are cleared (NULL = personal
        // workspace): they keep their own behaviour.
        for name in ["alice", "bob"] {
            let selected = selected_workspace(&store, name).await;
            assert_eq!(selected, None, "{name}'s selection must be cleared");
        }
        assert_eq!(
            selected_workspace(&store, crate::users::ADMIN_USER_NAME)
                .await
                .as_deref(),
            Some("survivor_a")
        );

        // Other users are untouched: an unrelated selection is kept and a
        // user with no selection stays NULL.
        assert_eq!(
            selected_workspace(&store, "carol").await.as_deref(),
            Some("other_ws")
        );
        assert_eq!(selected_workspace(&store, "dave").await, None);

        // Deleting a project the desktop is not on moves nothing.
        assert_eq!(
            store.delete("survivor_c").await.expect("delete workspace"),
            Some("survivor_a".to_string())
        );
        assert_eq!(
            selected_workspace(&store, crate::users::ADMIN_USER_NAME)
                .await
                .as_deref(),
            Some("survivor_a")
        );

        // An empty admin selection is not a steady state: the deletion repairs it
        // onto the fallback rather than leaving the desktop outside every project.
        store
            .conn
            .execute(
                "UPDATE users SET selected_workspace = NULL WHERE name = ?1",
                crate::db::params![crate::users::ADMIN_USER_NAME],
            )
            .await
            .expect("clear the admin selection");
        assert_eq!(
            store.delete("survivor_b").await.expect("delete workspace"),
            Some("survivor_a".to_string())
        );

        // The last project leaves the admin on the personal folder.
        assert_eq!(
            store.delete("survivor_a").await.expect("delete workspace"),
            None
        );
        assert_eq!(
            selected_workspace(&store, crate::users::ADMIN_USER_NAME).await,
            None
        );
    }

    /// Read a user's `selected_workspace` column (NULL ↔ `None`).
    async fn selected_workspace(store: &WorkspaceStore, name: &str) -> Option<String> {
        store
            .conn
            .query_optional(
                "SELECT selected_workspace FROM users WHERE name = ?1",
                crate::db::params![name],
                |row| row.get::<Option<String>>(0),
            )
            .await
            .expect("query user workspace")
            .flatten()
    }
}