codescout 0.15.0

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

mod write_guard;
#[allow(unused_imports)]
pub(crate) use write_guard::{acquire as acquire_write_guard, open_lock_file, WriteGuard};

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::config::project::ProjectConfig;
use crate::library::registry::LibraryRegistry;
use crate::memory::semantic_store::SemanticMemoryStore;
use crate::memory::MemoryStore;
use crate::workspace::{discover_projects, DiscoveredProject, Project, ProjectState, Workspace};

/// State of the background index-build task spawned by `index_project`.
#[derive(Default, Clone)]
pub enum IndexingState {
    #[default]
    Idle,
    Running {
        done: usize,
        total: usize,
        eta_secs: Option<u64>,
    },
    Done {
        files_indexed: usize,
        files_deleted: usize,
        detail: String,
        total_files: usize,
        total_chunks: usize,
    },
    Failed(String),
}

/// Tracks the indexing lifecycle of a single external library.
#[derive(Debug)]
pub enum LibraryIndexState {
    Idle,
    FetchingSources { command: String },
    Indexing { done: usize, total: usize },
    Done { chunks: usize, version: String },
    Failed(String),
}

#[derive(Clone)]
pub struct Agent {
    pub inner: Arc<RwLock<AgentInner>>,
    /// Tracks the background index-build task. Stored outside AgentInner
    /// so callers only need a brief std::sync lock, not an async RwLock.
    pub indexing: Arc<std::sync::Mutex<IndexingState>>,
    /// Per-session dedup for library nudge hints (e.g. "index this library").
    /// Wrapped in Arc so Agent remains Clone.
    pub nudged_libraries: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
    /// Limits concurrent embedding API calls to avoid overwhelming the embedding server.
    pub embedding_semaphore: Arc<tokio::sync::Semaphore>,
    /// Per-library indexing state (Idle / FetchingSources / Indexing / Done / Failed).
    pub library_index_states: Arc<std::sync::Mutex<HashMap<String, LibraryIndexState>>>,
    /// Abort handle for the current in-flight sync task (project reindex or
    /// library auto-index). `index(action='cancel')` takes this slot and calls
    /// `.abort()` to stop a running reindex without restarting the MCP server.
    /// Single slot — project and library sync rarely overlap; last-write-wins
    /// if they do. Per researcher MCP finding: dropping a `JoinHandle` does
    /// NOT cancel a task — only `.abort()` (or a `CancellationToken`) will.
    pub active_sync_abort: Arc<std::sync::Mutex<Option<tokio::task::AbortHandle>>>,
    /// Lazily-constructed semantic memory store (Qdrant-backed).
    /// `OnceCell` so the first caller wins; later callers share the Arc.
    /// Wrapped in `Arc` so `Agent` remains `Clone`.
    pub(crate) semantic_memory: Arc<tokio::sync::OnceCell<Arc<dyn SemanticMemoryStore>>>,
    /// Lazily-constructed dense embedder for memory operations.
    /// Parallel design to `semantic_memory` — first caller builds, others
    /// share the Arc. Swappable in tests via `set_memory_embedder_for_test`
    /// so remember/recall paths can be exercised end-to-end without a live
    /// retrieval stack.
    pub(crate) memory_embedder:
        Arc<tokio::sync::OnceCell<Arc<dyn crate::retrieval::embedder::DenseEmbedder>>>,
}

pub struct AgentInner {
    /// Registry of activated workspaces, keyed by canonical workspace root.
    /// Phase 1: holds at most one entry — `activate` clears and reinserts,
    /// mirroring the previous single-slot drop-and-replace, so behavior is
    /// unchanged. Phase 3 lifts the clear-on-activate to enable true
    /// multi-workspace residence + eviction. See
    /// docs/plans/2026-05-30-per-request-workspace-pinning.md.
    pub workspaces: HashMap<PathBuf, Workspace>,
    /// Canonical root of the workspace that unpinned calls resolve to — the
    /// per-session default (what `activate` sets). Replaces the implicit
    /// "the one workspace" identity of the old single `workspace` slot.
    pub default_workspace_root: Option<PathBuf>,
    pub project_explicitly_activated: bool,
    pub home_root: Option<PathBuf>,
    /// Last `activate()` as (root, when). Drives the concurrent-activation
    /// guard (`Agent::note_activation`): if a *different* root is activated
    /// under this shared server within a short window, the activate response
    /// carries a `concurrent_activation_warning`. See
    /// docs/issues/2026-05-30-shared-server-global-active-project-race.md
    pub last_activation: Option<(PathBuf, std::time::Instant)>,
}

impl AgentInner {
    /// The workspace that unpinned calls resolve to (the per-session default).
    /// Phase 1 this is the single live workspace; the ambient accessors below
    /// route through it. Phase 2+ adds selector-aware twins alongside.
    pub fn default_workspace(&self) -> Option<&Workspace> {
        self.workspaces.get(self.default_workspace_root.as_ref()?)
    }

    /// Mutable twin of `default_workspace`. Clones the key first to avoid a
    /// split borrow of `default_workspace_root` and `workspaces`.
    pub fn default_workspace_mut(&mut self) -> Option<&mut Workspace> {
        let root = self.default_workspace_root.clone()?;
        self.workspaces.get_mut(&root)
    }

    /// Convenience: get `&ActiveProject` from the focused project of the
    /// default workspace.
    pub fn active_project(&self) -> Option<&ActiveProject> {
        self.default_workspace()?.focused_active()?.as_active()
    }

    /// Convenience: get `&mut ActiveProject` from the focused project of the
    /// default workspace.
    pub fn active_project_mut(&mut self) -> Option<&mut ActiveProject> {
        self.default_workspace_mut()?
            .focused_active_mut()?
            .as_active_mut()
    }
    /// Assemble a `Workspace` for `root` from pre-loaded `ProjectResources`,
    /// under the caller's write lock. Reuses an already-resident project's
    /// write/file/dirty locks (so re-activation serializes correctly against
    /// in-flight writers). Pure read of `self` (home_root + workspaces) — it
    /// returns an owned `Workspace` and does not mutate the registry; the
    /// caller decides whether to clear+set-default (`activate`) or insert
    /// alongside (`ensure_resident`).
    fn build_workspace(
        &self,
        root: &Path,
        read_only: Option<bool>,
        res: ProjectResources,
    ) -> Workspace {
        let ProjectResources {
            config,
            memory,
            private_memory,
            library_registry,
            head_sha,
            discovered,
            fresh_file_lock,
        } = res;

        let is_home = self
            .home_root
            .as_ref()
            .map(|h| h.as_path() == root)
            .unwrap_or(true);
        let effective_read_only = match read_only {
            Some(false) => false,
            _ if is_home => false,
            _ => true,
        };

        // Re-activating the same root must keep the SAME write_lock, file_lock,
        // and dirty_files — otherwise an in-flight tool holding the old locks
        // does not serialize against new tools, and two writers can race.
        let existing = self.workspaces.values().find_map(|ws| {
            ws.projects.iter().find_map(|p| match &p.state {
                ProjectState::Activated(ap) if ap.root.as_path() == root => Some((
                    ap.write_lock.clone(),
                    ap.file_lock.clone(),
                    ap.dirty_files.clone(),
                )),
                _ => None,
            })
        });
        let (write_lock, file_lock, dirty_files) = existing.unwrap_or_else(|| {
            (
                Arc::new(tokio::sync::Mutex::new(())),
                fresh_file_lock,
                Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
            )
        });

        let active = ActiveProject {
            root: root.to_path_buf(),
            config,
            memory,
            private_memory,
            library_registry,
            dirty_files,
            read_only: effective_read_only,
            head_sha,
            has_git_remote: probe_has_git_remote(root),
            write_lock,
            file_lock,
            session_write_roots: Arc::new(std::sync::Mutex::new(Vec::new())),
        };

        let mut projects: Vec<Project> = Vec::new();
        let mut root_found = false;
        for dp in discovered {
            if dp.relative_root == std::path::Path::new(".") {
                root_found = true;
                projects.push(Project {
                    discovered: dp,
                    state: ProjectState::Activated(Box::new(active.clone())),
                });
            } else {
                projects.push(Project::new_dormant(dp));
            }
        }
        if !root_found {
            let root_dp = DiscoveredProject {
                id: crate::workspace::ROOT_PROJECT_ID.to_string(),
                relative_root: PathBuf::from("."),
                languages: vec![],
                manifest: None,
            };
            projects.insert(
                0,
                Project {
                    discovered: root_dp,
                    state: ProjectState::Activated(Box::new(active)),
                },
            );
        }

        Workspace::new(root.to_path_buf(), projects)
    }
}

/// Active project state.
///
/// **Field-visibility contract:** all fields are `pub(crate)` rather than
/// private to keep `Agent::with_project(|p| ...)` closures ergonomic — they
/// receive `&ActiveProject` and read fields directly. Mutation invariants are
/// not enforced by getters; they are enforced by the borrow contract:
///
/// - External callers go through `Agent::with_project`, which hands out
///   `&ActiveProject` (shared, not mutable) — assignment to any field is a
///   compile error from outside this module.
/// - In-module mutation requires `AgentInner::active_project_mut()` and is
///   limited to a small number of well-named call sites in `agent/mod.rs`
///   (e.g. `activate`, `reload_config_if_project_toml`).
/// - Cross-cutting state (`dirty_files`, `write_lock`, `file_lock`, `session_write_roots`) is
///   `Arc<Mutex<_>>` / `Arc<File>` and self-protects via interior mutability;
///   external access is routed through `Agent` accessor methods such as
///   `mark_file_dirty`, `dirty_file_count`, `dirty_files_arc`, `add_session_write_root`,
///   `session_write_roots_snapshot`.
///
/// If codescout is ever split into multiple crates, fields with cross-field
/// invariants (`read_only`, `config`, `head_sha`/`has_git_remote`) should be
/// reduced to private and exposed through accessors. Until then, the type
/// system already enforces the contract — getters would add boilerplate
/// without adding safety.

#[derive(Clone)]
pub struct ActiveProject {
    pub(crate) root: PathBuf,
    pub(crate) config: ProjectConfig,
    pub(crate) memory: MemoryStore,
    pub(crate) private_memory: MemoryStore,
    pub(crate) library_registry: LibraryRegistry,
    /// Tracks files written by tools in this session but not yet re-indexed.
    /// Wrapped in an Arc so index_project can capture it across a tokio::spawn
    /// boundary and clear it on successful completion.
    pub(crate) dirty_files: Arc<std::sync::Mutex<std::collections::HashSet<PathBuf>>>,
    /// When true, file writes are disabled regardless of security config.
    pub(crate) read_only: bool,
    /// Git HEAD SHA of the project at activation time. None for non-git projects.
    pub(crate) head_sha: Option<String>,
    /// Cached at activation: does this project have at least one git remote?
    /// Used by `current_capabilities` to gate GitHub-family tool exposure
    /// without re-opening the repo on every `list_tools` call. Refreshed on
    /// re-activation; does not track remotes added mid-session (rare enough
    /// to not justify invalidation complexity — user can re-activate).
    pub(crate) has_git_remote: bool,
    /// Async mutex serializing writes within this process.
    /// Acquired FIRST in the write-lock order (see agent::write_guard).
    pub(crate) write_lock: Arc<tokio::sync::Mutex<()>>,
    /// Shared file descriptor for the cross-process advisory lock at
    /// `.codescout/write.lock`. The flock is per-open-file-description, so a
    /// single File handle shared by every tool call in this process (via Arc)
    /// is sufficient — in-process ordering is handled by `write_lock` above.
    pub(crate) file_lock: Arc<std::fs::File>,
    /// Session-scoped directories approved for writing outside the project root.
    /// Managed by the `approve_write` tool; cleared on re-activation.
    pub(crate) session_write_roots: Arc<std::sync::Mutex<Vec<PathBuf>>>,
}

impl ActiveProject {
    /// Project name used as the namespace across stores (Qdrant `project_id`
    /// payload, sqlite-vec scoping, etc.). Comes from `project.toml`'s
    /// `[project] name = ...` field.
    pub fn project_id(&self) -> &str {
        &self.config.project.name
    }

    /// Absolute path to the project root on disk.
    pub fn root(&self) -> &Path {
        &self.root
    }
}

/// Read `workspace.toml` (if present) and return the discovery depth and exclude list.
/// Falls back to defaults (depth=3, no excludes) when the file is missing or unparseable.
fn load_discover_settings(root: &std::path::Path) -> (usize, Vec<String>) {
    let ws_path = crate::config::workspace::workspace_config_path(root);
    if let Ok(content) = std::fs::read_to_string(&ws_path) {
        if let Ok(ws) = toml::from_str::<crate::config::workspace::WorkspaceConfig>(&content) {
            return (ws.workspace.discovery_max_depth, ws.exclude_projects);
        }
    }
    (3, vec![])
}

/// Resolve the short git HEAD SHA for a directory. Returns None if not a git
/// repo or if HEAD is unborn (no commits yet).
///
/// Uses libgit2 (no subprocess): on this project's locked-down Windows VDI,
/// every `CreateProcessW` is taxed by EDR injection, and a raw `git rev-parse`
/// with no timeout could hang activation outright. `short_id()` respects
/// `core.abbrev`, matching `git rev-parse --short HEAD` semantics. Mirrors the
/// sibling `probe_has_git_remote`, which already opens a libgit2 repo.
fn resolve_head_sha(root: &Path) -> Option<String> {
    let repo = git2::Repository::open(root).ok()?;
    let head = repo.revparse_single("HEAD").ok()?;
    let short = head.short_id().ok()?;
    short.as_str().map(str::to_string).filter(|s| !s.is_empty())
}

/// Does `root` contain a git repository with at least one configured remote?
/// Used at activation time to cache `has_git_remote` on `ActiveProject`.
fn probe_has_git_remote(root: &Path) -> bool {
    git2::Repository::open(root)
        .ok()
        .and_then(|repo| repo.remotes().ok())
        .map(|remotes| !remotes.is_empty())
        .unwrap_or(false)
}
/// Lock-free I/O products needed to assemble a `Workspace` for a root.
/// Loaded by `Agent::load_project_resources` (outside any lock), then consumed
/// by `AgentInner::build_workspace` under the write lock.
struct ProjectResources {
    config: ProjectConfig,
    memory: MemoryStore,
    private_memory: MemoryStore,
    library_registry: LibraryRegistry,
    head_sha: Option<String>,
    discovered: Vec<DiscoveredProject>,
    fresh_file_lock: Arc<std::fs::File>,
}

/// Derive a `PathSecurityConfig` from an active project: its security config
/// plus library paths, with writes disabled when the project is read-only.
/// Shared by `security_config` (default) and `security_config_for` (pinned).
fn project_security_config(p: &ActiveProject) -> crate::util::path_security::PathSecurityConfig {
    let mut config = p.config.security.to_path_security_config();
    config.library_paths = p
        .library_registry
        .all()
        .iter()
        .map(|e| e.path.clone())
        .collect();
    if p.read_only {
        config.file_write_enabled = false;
    }
    config
}

// ---------------------------------------------------------------------------
// Lifecycle & activation
// ---------------------------------------------------------------------------
impl Agent {
    pub async fn new(project: Option<PathBuf>) -> Result<Self> {
        // Tests and library users that bypass main() reach here without the
        // crypto provider installed — install it idempotently before any TLS
        // (Qdrant gRPC, dense embedder HTTP) is touched.
        crate::install_default_crypto_provider();

        let (workspace, home_root) = if let Some(raw) = project {
            // Canonicalize so home_root is always an absolute path.  This prevents
            // path-form drift when activate_project(".") later canonicalizes its
            // argument and compares against home_root.
            let root = std::fs::canonicalize(&raw).unwrap_or(raw);
            let config = ProjectConfig::load_or_default(&root)?;
            let memory = MemoryStore::open(&root)?;
            let private_memory = MemoryStore::open_private(&root)?;
            let registry_path = root.join(".codescout").join("libraries.json");
            let library_registry = LibraryRegistry::load(&registry_path).unwrap_or_default();
            let home = root.clone();

            let active = ActiveProject {
                root: root.clone(),
                config,
                memory,
                private_memory,
                library_registry,
                dirty_files: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
                read_only: false,
                head_sha: resolve_head_sha(&root),
                has_git_remote: probe_has_git_remote(&root),
                write_lock: Arc::new(tokio::sync::Mutex::new(())),
                file_lock: open_lock_file(&root)
                    .with_context(|| format!("failed to open write.lock for {}", root.display()))?,
                session_write_roots: Arc::new(std::sync::Mutex::new(Vec::new())),
            };

            // Discover sub-projects; root project is always included.
            // Respect depth and exclude settings from workspace.toml if it exists.
            // Walked on a blocking thread — `ignore::WalkBuilder` + manifest
            // reads do synchronous fs I/O that must not stall the Tokio runtime.
            let (discover_depth, discover_exclude) = load_discover_settings(&root);
            let discovered = {
                let root = root.clone();
                let exclude = discover_exclude.clone();
                tokio::task::spawn_blocking(move || {
                    discover_projects(&root, discover_depth, &exclude)
                })
                .await
                .map_err(|e| anyhow::anyhow!("discover_projects task failed: {e}"))?
            };
            let mut projects: Vec<Project> = Vec::new();

            // Find if the root project was discovered (relative_root == ".")
            let mut root_found = false;
            for dp in discovered {
                if dp.relative_root == std::path::Path::new(".") {
                    root_found = true;
                    projects.push(Project {
                        discovered: dp,
                        state: ProjectState::Activated(Box::new(active.clone())),
                    });
                } else {
                    projects.push(Project::new_dormant(dp));
                }
            }

            // If root was not discovered (e.g. no manifest), synthesize it
            if !root_found {
                let root_dp = DiscoveredProject {
                    id: crate::workspace::ROOT_PROJECT_ID.to_string(),
                    relative_root: PathBuf::from("."),
                    languages: vec![],
                    manifest: None,
                };
                projects.insert(
                    0,
                    Project {
                        discovered: root_dp,
                        state: ProjectState::Activated(Box::new(active)),
                    },
                );
            }

            let ws = Workspace::new(root, projects);
            (Some(ws), Some(home))
        } else {
            (None, None)
        };

        // A project provided at startup (via --project or CWD) is treated as explicitly
        // activated — the server operator already chose the write target.
        let project_explicitly_activated = workspace.is_some();
        let default_workspace_root = workspace.as_ref().map(|ws| ws.root.clone());
        let workspaces = match workspace {
            Some(ws) => {
                let mut m = HashMap::new();
                m.insert(ws.root.clone(), ws);
                m
            }
            None => HashMap::new(),
        };

        Ok(Self {
            inner: Arc::new(RwLock::new(AgentInner {
                workspaces,
                default_workspace_root,
                project_explicitly_activated,
                home_root,
                last_activation: None,
            })),
            indexing: Arc::new(std::sync::Mutex::new(IndexingState::Idle)),
            nudged_libraries: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
            embedding_semaphore: Arc::new(tokio::sync::Semaphore::new(2)),
            library_index_states: Arc::new(std::sync::Mutex::new(HashMap::new())),
            active_sync_abort: Arc::new(std::sync::Mutex::new(None)),
            semantic_memory: Arc::new(tokio::sync::OnceCell::new()),
            memory_embedder: Arc::new(tokio::sync::OnceCell::new()),
        })
    }

    /// Activate a project by path, replacing the current workspace as the
    /// per-session default. Pinned workspaces are added via `ensure_resident`
    /// without disturbing the default.
    pub async fn activate(&self, root: PathBuf, read_only: Option<bool>) -> Result<()> {
        // Canonicalize up-front so every downstream consumer (and the registry
        // key) sees the same absolute path. Without this, activate(".") would
        // compare unequal to Agent::new's canonicalized home_root, making
        // is_home false on the first re-activation and flipping to read-only.
        let root = std::fs::canonicalize(&root).unwrap_or(root);
        let res = Self::load_project_resources(&root).await?;
        {
            let mut inner = self.inner.write().await;
            // build_workspace computes is_home / read_only and reuses an
            // existing root's locks, all under this write lock (no TOCTOU).
            let ws = inner.build_workspace(&root, read_only, res);
            if inner.home_root.is_none() {
                inner.home_root = Some(root.clone());
            }
            // Phase 1: single-entry default registry — clear + reinsert mirrors
            // the previous single-slot drop-and-replace. ensure_resident adds
            // pinned entries alongside without clearing.
            inner.workspaces.clear();
            inner.workspaces.insert(root.clone(), ws);
            inner.default_workspace_root = Some(root);
            inner.project_explicitly_activated = true;
        }
        Ok(())
    }
    /// Load all lock-free I/O for a project root (config, memory, library
    /// registry, sub-project discovery, write-lock file). Shared by `activate`
    /// and `ensure_resident`; the products are assembled into a `Workspace`
    /// under the write lock by `AgentInner::build_workspace`.
    async fn load_project_resources(root: &Path) -> Result<ProjectResources> {
        let config = ProjectConfig::load_or_default(root)?;
        let memory = MemoryStore::open(root)?;
        let private_memory = MemoryStore::open_private(root)?;
        let registry_path = root.join(".codescout").join("libraries.json");
        let library_registry = LibraryRegistry::load(&registry_path).unwrap_or_default();
        let head_sha = resolve_head_sha(root);
        let (discover_depth, discover_exclude) = load_discover_settings(root);
        let discovered = {
            let root = root.to_path_buf();
            let exclude = discover_exclude.clone();
            tokio::task::spawn_blocking(move || discover_projects(&root, discover_depth, &exclude))
                .await
                .map_err(|e| anyhow::anyhow!("discover_projects task failed: {e}"))?
        };
        let fresh_file_lock = write_guard::open_lock_file(root)
            .with_context(|| format!("failed to open write.lock for {}", root.display()))?;
        Ok(ProjectResources {
            config,
            memory,
            private_memory,
            library_registry,
            head_sha,
            discovered,
            fresh_file_lock,
        })
    }

    /// Ensure `root` is resident in the registry (load + cache on miss) WITHOUT
    /// clearing the registry or changing `default_workspace_root`. Lets a
    /// per-request pinned workspace be resolved alongside the default. Pinned,
    /// non-home workspaces default to read-only. Idempotent.
    pub async fn ensure_resident(&self, root: PathBuf, read_only: Option<bool>) -> Result<()> {
        let root = std::fs::canonicalize(&root).unwrap_or(root);
        {
            let inner = self.inner.read().await;
            if inner.workspaces.contains_key(&root) {
                return Ok(());
            }
        }
        let res = Self::load_project_resources(&root).await?;
        let mut inner = self.inner.write().await;
        // Re-check under the write lock — another caller may have inserted it
        // while we did the lock-free I/O.
        if inner.workspaces.contains_key(&root) {
            return Ok(());
        }
        let ws = inner.build_workspace(&root, read_only, res);
        inner.workspaces.insert(root, ws);
        Ok(())
    }

    /// Run a closure with a read-lock on the project resolved by an optional
    /// workspace pin. `Some(root)` → that workspace (resident-on-demand);
    /// `None` → the session default. The closure receives the workspace's
    /// focused `&ActiveProject`. Level-2 sub-project pinning within a pinned
    /// workspace is not yet wired (read tools pin at workspace granularity).
    pub async fn with_project_at<F, T>(&self, workspace_override: Option<&Path>, f: F) -> Result<T>
    where
        F: FnOnce(&ActiveProject) -> Result<T>,
    {
        if let Some(root) = workspace_override {
            self.ensure_resident(root.to_path_buf(), None).await?;
        }
        let inner = self.inner.read().await;
        let ws = match workspace_override {
            Some(root) => {
                let key = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
                inner.workspaces.get(&key).ok_or_else(|| {
                    anyhow::anyhow!("pinned workspace not resident: {}", key.display())
                })?
            }
            None => inner.default_workspace().ok_or_else(|| {
                crate::tools::RecoverableError::with_hint(
                    "No active project. Use activate_project first.",
                    "Call activate_project(\"/path/to/project\") to set the active project.",
                )
            })?,
        };
        let project = ws
            .focused_active()
            .and_then(|p| p.as_active())
            .ok_or_else(|| anyhow::anyhow!("workspace has no active focused project"))?;
        f(project)
    }

    /// Pinned twin of `project_root`: focused root of the workspace named by
    /// `workspace_override` (resident-on-demand), or the default if `None`.
    pub async fn project_root_for(&self, workspace_override: Option<&Path>) -> Option<PathBuf> {
        self.with_project_at(workspace_override, |p| Ok(p.root().to_path_buf()))
            .await
            .ok()
    }

    /// Pinned twin of `security_config`: security config of the workspace named
    /// by `workspace_override` (resident-on-demand), or defaults if `None`/none.
    pub async fn security_config_for(
        &self,
        workspace_override: Option<&Path>,
    ) -> crate::util::path_security::PathSecurityConfig {
        self.with_project_at(workspace_override, |p| Ok(project_security_config(p)))
            .await
            .unwrap_or_default()
    }
    /// Pinned twin of `require_project_root`: focused root of the workspace
    /// named by `workspace_override` (resident-on-demand), or a recoverable
    /// "no active project" error if none resolvable.
    pub async fn require_project_root_for(
        &self,
        workspace_override: Option<&Path>,
    ) -> Result<PathBuf> {
        self.with_project_at(workspace_override, |p| Ok(p.root().to_path_buf()))
            .await
    }

    /// Pinned twin of `mark_file_dirty`: marks a file dirty in the workspace
    /// named by `workspace_override` (resident-on-demand) or the session
    /// default. Silently no-ops if no project resolves, matching the ambient
    /// contract — by the time a write tool calls this it has already resolved
    /// the same pin via `require_project_root_for`, so the workspace is resident.
    pub async fn mark_file_dirty_for(&self, workspace_override: Option<&Path>, path: PathBuf) {
        let _ = self
            .with_project_at(workspace_override, |p| {
                p.dirty_files
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .insert(path);
                Ok(())
            })
            .await;
    }

    /// Pinned twin of `add_session_write_root`.
    pub async fn add_session_write_root_for(
        &self,
        workspace_override: Option<&Path>,
        path: PathBuf,
    ) {
        let _ = self
            .with_project_at(workspace_override, |p| {
                p.session_write_roots
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .push(path);
                Ok(())
            })
            .await;
    }

    /// Pinned twin of `session_write_roots_snapshot`. Empty Vec if no project resolves.
    pub async fn session_write_roots_snapshot_for(
        &self,
        workspace_override: Option<&Path>,
    ) -> Vec<PathBuf> {
        self.with_project_at(workspace_override, |p| {
            Ok(p.session_write_roots
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .clone())
        })
        .await
        .unwrap_or_default()
    }

    /// Pinned twin of `dirty_files_arc`. None if no project resolves.
    pub async fn dirty_files_arc_for(
        &self,
        workspace_override: Option<&Path>,
    ) -> Option<Arc<std::sync::Mutex<std::collections::HashSet<PathBuf>>>> {
        self.with_project_at(workspace_override, |p| Ok(p.dirty_files.clone()))
            .await
            .ok()
    }

    /// Mutable twin of `with_project_at`. Runs the closure with a `&mut
    /// ActiveProject` for the workspace named by `workspace_override`
    /// (resident-on-demand) or the session default. For write tools that mutate
    /// `ActiveProject` fields *directly* (e.g. `p.config = …`,
    /// `library_registry.register`) rather than via the `Arc<Mutex>`
    /// interior-mutability fields — those use the read `with_project_at`.
    ///
    /// Phase 4a holds the single `AgentInner` write lock for the closure's
    /// duration; the closure MUST stay non-blocking (no `.await` on a per-project
    /// lock) per `## Phase 4 — Lock-Ordering Proof`. Phase 4b moves this onto the
    /// per-`Workspace` lock.
    pub async fn with_project_at_mut<F, T>(
        &self,
        workspace_override: Option<&Path>,
        f: F,
    ) -> Result<T>
    where
        F: FnOnce(&mut ActiveProject) -> Result<T>,
    {
        if let Some(root) = workspace_override {
            self.ensure_resident(root.to_path_buf(), None).await?;
        }
        let mut inner = self.inner.write().await;
        let ws = match workspace_override {
            Some(root) => {
                let key = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
                inner.workspaces.get_mut(&key).ok_or_else(|| {
                    anyhow::anyhow!("pinned workspace not resident: {}", key.display())
                })?
            }
            None => {
                let root = inner.default_workspace_root.clone().ok_or_else(|| {
                    crate::tools::RecoverableError::with_hint(
                        "No active project. Use activate_project first.",
                        "Call activate_project(\"/path/to/project\") to set the active project.",
                    )
                })?;
                inner
                    .workspaces
                    .get_mut(&root)
                    .ok_or_else(|| anyhow::anyhow!("default workspace not resident"))?
            }
        };
        let project = ws
            .focused_active_mut()
            .and_then(|p| p.as_active_mut())
            .ok_or_else(|| anyhow::anyhow!("workspace has no active focused project"))?;
        f(project)
    }

    /// Pinned twin of `reload_config_if_project_toml`.
    pub async fn reload_config_if_project_toml_for(
        &self,
        workspace_override: Option<&Path>,
        path: &std::path::Path,
    ) {
        let _ = self
            .with_project_at_mut(workspace_override, |p| {
                let toml_path = p.root.join(".codescout").join("project.toml");
                if path == toml_path {
                    if let Ok(fresh) =
                        crate::config::project::ProjectConfig::load_or_default(&p.root)
                    {
                        p.config = fresh;
                    }
                }
                Ok(())
            })
            .await;
    }

    /// Window within which activating a *different* root counts as concurrent
    /// contention (a subagent racing the shared slot) rather than a normal
    /// sequential re-activation by one linear session.
    const CONCURRENT_ACTIVATION_WINDOW: std::time::Duration = std::time::Duration::from_secs(5);

    /// Pure decision for the concurrent-activation guard. Returns a warning when
    /// `new_root` rapidly replaces a *different* recently-activated root — the
    /// fingerprint of concurrent multi-workspace use on a single shared server
    /// (parallel subagents that each `activate` a different workspace). Same-root
    /// re-activation and slow sequential switches (outside `window`) are silent.
    /// See docs/issues/2026-05-30-shared-server-global-active-project-race.md
    fn concurrent_switch_warning(
        prev: Option<(&std::path::Path, std::time::Duration)>,
        new_root: &std::path::Path,
        window: std::time::Duration,
    ) -> Option<String> {
        match prev {
            Some((prev_root, since)) if prev_root != new_root && since < window => Some(format!(
                "active project switched from {} to {} {:?} ago — another caller \
                 (e.g. a concurrent subagent) shares this server's single \
                 active-project slot, so reads may resolve against the wrong \
                 workspace. Fix: pass workspace=<absolute path> on each tool call \
                 to pin resolution per-request instead of activating. For fully \
                 independent parallel work, separate client windows also \
                 isolate (separate processes = separate slots).",
                prev_root.display(),
                new_root.display(),
                since
            )),
            _ => None,
        }
    }

    /// Record this activation and return a warning if it rapidly replaced a
    /// *different* recently-activated root. Best-effort drift signal — it cannot
    /// prevent the race (the active project is process-global shared state), only
    /// surface it. The real fix is per-request workspace pinning; see the bug file.
    pub async fn note_activation(&self, root: &std::path::Path) -> Option<String> {
        let mut inner = self.inner.write().await;
        let prev = inner
            .last_activation
            .as_ref()
            .map(|(p, at)| (p.as_path(), at.elapsed()));
        let warning =
            Self::concurrent_switch_warning(prev, root, Self::CONCURRENT_ACTIVATION_WINDOW);
        inner.last_activation = Some((root.to_path_buf(), std::time::Instant::now()));
        warning
    }

    /// Get the active project root, or error if none is set.
    pub async fn require_project_root(&self) -> Result<PathBuf> {
        let inner = self.inner.read().await;
        inner
            .default_workspace()
            .ok_or_else(|| {
                crate::tools::RecoverableError::with_hint(
                    "No active project. Use activate_project first.",
                    "Call activate_project(\"/path/to/project\") to set the active project.",
                )
            })
            .and_then(|ws| {
                ws.focused_project_root().map_err(|_| {
                    crate::tools::RecoverableError::with_hint(
                        "No active project. Use activate_project first.",
                        "Call activate_project(\"/path/to/project\") to set the active project.",
                    )
                })
            })
            .map_err(Into::into)
    }

    /// Switch focus to a project by ID within the current workspace.
    pub async fn switch_focus(&self, project_id: &str) -> Result<()> {
        let mut inner = self.inner.write().await;
        inner
            .default_workspace_mut()
            .ok_or_else(|| anyhow::anyhow!("No active workspace"))?
            .set_focused(project_id)
    }

    /// Promote a Dormant workspace project to Activated in-place.
    /// Unlike `activate()`, this preserves the workspace topology.
    pub async fn activate_within_workspace(
        &self,
        project_id: &str,
        read_only: Option<bool>,
    ) -> Result<()> {
        // --- Phase 1: read-only pass to resolve abs_root and check early-return ---
        // Use a read lock so we don't block other readers while doing the
        // lookup.  We'll re-check under the write lock below.
        let (abs_root, home_root_snapshot) = {
            let inner = self.inner.read().await;
            let ws = inner
                .default_workspace()
                .ok_or_else(|| anyhow::anyhow!("No active workspace"))?;
            let relative_root = ws
                .projects
                .iter()
                .find(|p| p.discovered.id == project_id)
                .map(|p| p.discovered.relative_root.clone())
                .ok_or_else(|| {
                    anyhow::anyhow!("Project '{}' not found in workspace", project_id)
                })?;
            (ws.root.join(&relative_root), inner.home_root.clone())
        };

        // --- Phase 2: blocking I/O outside any lock ---
        // Determine read_only using the snapshot; the write lock below will
        // re-derive this from the live state, so a race here is harmless.
        let is_home_snapshot = home_root_snapshot
            .as_ref()
            .map(|h| *h == abs_root)
            .unwrap_or(false);
        let effective_read_only_snapshot = match read_only {
            Some(false) => false,
            _ if is_home_snapshot => false,
            _ => true,
        };
        let _ = effective_read_only_snapshot; // recomputed under write lock below

        // Open the lock file before acquiring the write lock — involves blocking
        // fs I/O (create_dir_all + OpenOptions::open) that must not run on the
        // async executor while holding a write guard.
        let file_lock = write_guard::open_lock_file(&abs_root)
            .with_context(|| format!("failed to open write.lock for {}", abs_root.display()))?;

        // --- Phase 3: write lock to mutate workspace state ---
        let mut inner = self.inner.write().await;

        // Clone home_root before taking a mutable reference into inner.workspace,
        // since RwLockWriteGuard doesn't support split field borrows.
        let home_root = inner.home_root.clone();

        let ws = inner
            .default_workspace_mut()
            .ok_or_else(|| anyhow::anyhow!("No active workspace"))?;

        // Re-resolve root under the write lock to guard against concurrent
        // activate() calls that could have replaced the workspace.
        let relative_root = ws
            .projects
            .iter()
            .find(|p| p.discovered.id == project_id)
            .map(|p| p.discovered.relative_root.clone())
            .ok_or_else(|| anyhow::anyhow!("Project '{}' not found in workspace", project_id))?;

        let abs_root = ws.root.join(&relative_root);

        // Determine read_only: explicit > home (always rw) > default (ro)
        let is_home = home_root.as_ref().map(|h| *h == abs_root).unwrap_or(false);
        let effective_read_only = match read_only {
            Some(false) => false,
            _ if is_home => false,
            _ => true,
        };

        // If already activated, just switch focus and optionally update read_only
        let already_activated = ws
            .projects
            .iter()
            .find(|p| p.discovered.id == project_id)
            .and_then(|p| p.as_active())
            .is_some();
        if already_activated {
            ws.set_focused(project_id)?;
            if let Some(ro) = read_only {
                if let Some(active) = ws.focused_active_mut().and_then(|p| p.as_active_mut()) {
                    active.read_only = ro;
                }
            }
            return Ok(());
        }

        // Load config, memory, library registry for the sub-project
        let config = ProjectConfig::load_or_default(&abs_root)?;
        let memory = MemoryStore::open(&abs_root)?;
        let private_memory = MemoryStore::open_private(&abs_root)?;
        let registry_path = abs_root.join(".codescout").join("libraries.json");
        let library_registry = LibraryRegistry::load(&registry_path).unwrap_or_default();
        let head_sha = resolve_head_sha(&abs_root);

        let active = ActiveProject {
            root: abs_root.clone(),
            config,
            memory,
            private_memory,
            library_registry,
            dirty_files: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
            read_only: effective_read_only,
            head_sha,
            has_git_remote: probe_has_git_remote(&abs_root),
            write_lock: Arc::new(tokio::sync::Mutex::new(())),
            file_lock,
            session_write_roots: Arc::new(std::sync::Mutex::new(Vec::new())),
        };

        // Promote in-place
        let project_mut = ws
            .projects
            .iter_mut()
            .find(|p| p.discovered.id == project_id)
            .expect("project_mut lookup — invariant: re-resolved from the same ws.projects slice under the write lock above; only activate_within_workspace mutates project list, and it holds this lock");
        project_mut.state = ProjectState::Activated(Box::new(active));

        // Switch focus
        ws.focused = Some(project_id.to_string());

        Ok(())
    }

    /// Resolve root: explicit project ID > file hint > focused project.
    pub async fn resolve_root(
        &self,
        project: Option<&str>,
        file_hint: Option<&std::path::Path>,
    ) -> Result<PathBuf> {
        let inner = self.inner.read().await;
        inner
            .default_workspace()
            .ok_or_else(|| anyhow::anyhow!("No active project"))?
            .resolve_root(project, file_hint)
    }
}

// ---------------------------------------------------------------------------
// Project files & status
// ---------------------------------------------------------------------------
impl Agent {
    /// Run a closure with a read-lock on the active project.
    /// Returns an error if no project is active.
    pub async fn with_project<F, T>(&self, f: F) -> Result<T>
    where
        F: FnOnce(&ActiveProject) -> Result<T>,
    {
        let inner = self.inner.read().await;
        let project = inner
            .active_project()
            .ok_or_else(|| anyhow::anyhow!("No active project. Use activate_project first."))?;
        f(project)
    }

    /// Mark a file as written-but-not-yet-indexed.
    /// Called by every write tool after modifying a source file.
    pub async fn mark_file_dirty(&self, path: PathBuf) {
        let inner = self.inner.read().await;
        if let Some(p) = inner.active_project() {
            p.dirty_files
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .insert(path);
        }
    }

    /// Append a session-approved write root for the current project.
    pub async fn add_session_write_root(&self, path: PathBuf) {
        let inner = self.inner.read().await;
        if let Some(p) = inner.active_project() {
            p.session_write_roots
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(path);
        }
    }

    /// Return a snapshot of the current session-approved write roots.
    pub async fn session_write_roots_snapshot(&self) -> Vec<PathBuf> {
        let inner = self.inner.read().await;
        match inner.active_project() {
            Some(p) => p
                .session_write_roots
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .clone(),
            None => Vec::new(),
        }
    }

    /// Number of files written in this session but not yet re-indexed.
    pub async fn dirty_file_count(&self) -> usize {
        let inner = self.inner.read().await;
        inner
            .active_project()
            .map(|p| {
                p.dirty_files
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .len()
            })
            .unwrap_or(0)
    }

    /// Drain all files marked dirty by write tools, returning them for re-indexing.
    /// Clears the set so subsequent calls return only newly-dirtied files.
    pub async fn drain_dirty_files(&self) -> Vec<PathBuf> {
        let inner = self.inner.read().await;
        inner
            .active_project()
            .map(|p| {
                let mut set = p.dirty_files.lock().unwrap_or_else(|e| e.into_inner());
                set.drain().collect()
            })
            .unwrap_or_default()
    }

    /// Clone the dirty-files Arc so index_project can capture it across a spawn boundary
    /// and clear it on successful completion.
    pub async fn dirty_files_arc(
        &self,
    ) -> Option<Arc<std::sync::Mutex<std::collections::HashSet<PathBuf>>>> {
        let inner = self.inner.read().await;
        inner.active_project().map(|p| p.dirty_files.clone())
    }

    /// Get the current project status for building server instructions.
    pub async fn project_status(&self) -> Option<crate::prompts::ProjectStatus> {
        // Phase 1: cheap clones under the read lock — no blocking I/O
        let (
            name,
            path,
            project_root,
            languages,
            memory_store,
            db_path,
            prompt_file,
            default_prompt,
        ) = {
            let inner = self.inner.read().await;
            let project = inner.active_project()?;
            let prompt_file = project.root.join(".codescout").join("system-prompt.md");
            // Inline path — replaces embed::index::project_db_path during L-01
            // step 8a. The legacy sqlite db at this location indicates the user
            // has not yet migrated to the retrieval stack; activate_project
            // surfaces a separate `legacy_semantic_index` hint when present.
            let db_path = project.root.join(".codescout/embeddings/project.db");
            Some((
                project.config.project.name.clone(),
                project.root.display().to_string(),
                project.root.clone(),
                project.config.project.languages.clone(),
                project.memory.clone(),
                db_path,
                prompt_file,
                project.config.project.system_prompt.clone(),
            ))
        }?; // lock dropped here

        // Phase 2: blocking filesystem reads off the executor
        let (memories, has_index, system_prompt, worktree) =
            tokio::task::spawn_blocking(move || {
                let memories = memory_store.list().unwrap_or_default();
                let has_index = db_path.exists();
                let system_prompt = if prompt_file.exists() {
                    std::fs::read_to_string(&prompt_file).ok()
                } else {
                    default_prompt
                };
                let worktree = crate::prompts::detect_worktree_info(&project_root);
                (memories, has_index, system_prompt, worktree)
            })
            .await
            .ok()?;

        // Phase 3: workspace summary (acquires its own read-lock)
        let workspace = self.workspace_summary().await;

        Some(crate::prompts::ProjectStatus {
            name,
            path,
            languages,
            memories,
            has_index,
            system_prompt,
            workspace,
            worktree,
        })
    }

    /// Map current `IndexingState` to a short label for external consumers
    /// (e.g. the `project://summary` MCP resource).
    pub fn index_status_label(&self) -> String {
        match &*self.indexing.lock().unwrap() {
            IndexingState::Idle => "idle".into(),
            IndexingState::Running { .. } => "indexing".into(),
            IndexingState::Done { .. } => "indexed".into(),
            IndexingState::Failed(_) => "failed".into(),
        }
    }

    /// Build workspace project summaries for multi-project repos.
    /// Returns None for single-project workspaces.
    pub async fn workspace_summary(&self) -> Option<Vec<crate::prompts::WorkspaceProjectSummary>> {
        let inner = self.inner.read().await;
        let ws = inner.default_workspace()?;
        if ws.projects.len() <= 1 {
            return None;
        }
        let ws_cfg: Option<crate::config::workspace::WorkspaceConfig> =
            std::fs::read_to_string(crate::config::workspace::workspace_config_path(&ws.root))
                .ok()
                .and_then(|s| toml::from_str(&s).ok());

        let summaries = ws
            .projects
            .iter()
            .map(|p| {
                let depends_on = ws_cfg
                    .as_ref()
                    .and_then(|cfg| cfg.projects.iter().find(|e| e.id == p.discovered.id))
                    .map(|e| e.depends_on.clone())
                    .unwrap_or_default();
                crate::prompts::WorkspaceProjectSummary {
                    id: p.discovered.id.clone(),
                    root: p.discovered.relative_root.display().to_string(),
                    languages: p.discovered.languages.clone(),
                    depends_on,
                }
            })
            .collect();
        Some(summaries)
    }

    /// If `path` is the active project's `.codescout/project.toml`, reload the
    /// in-memory config from disk. Called by `edit_file` after every successful
    /// write so that tools like `semantic_search` see the updated model immediately
    /// without requiring a session restart.
    pub async fn reload_config_if_project_toml(&self, path: &std::path::Path) {
        let mut inner = self.inner.write().await;
        if let Some(ref mut p) = inner.active_project_mut() {
            let toml_path = p.root.join(".codescout").join("project.toml");
            if path == toml_path {
                if let Ok(fresh) = crate::config::project::ProjectConfig::load_or_default(&p.root) {
                    p.config = fresh;
                }
            }
        }
    }

    /// Returns the canonical `project_id` for the session-default workspace's
    /// call-edge cache entries — the focused sub-project id, or `ROOT_PROJECT_ID`.
    /// Delegates to `call_edges_project_id_for(None)`; kept as the ambient entry
    /// point for callers that operate on the default workspace.
    pub async fn call_edges_project_id(&self) -> String {
        self.call_edges_project_id_for(None).await
    }

    /// Pinned twin of `call_edges_project_id`: the call-edge `project_id` of the
    /// workspace named by `workspace_override` (resident-on-demand), or the
    /// session default when `None`. `call_graph` (read + upsert) and
    /// `invalidate_call_edges_for` BOTH resolve `project_id` through here, so they
    /// always agree on the cache namespace under a pin.
    pub async fn call_edges_project_id_for(&self, workspace_override: Option<&Path>) -> String {
        if let Some(root) = workspace_override {
            let _ = self.ensure_resident(root.to_path_buf(), None).await;
        }
        let inner = self.inner.read().await;
        let ws = match workspace_override {
            Some(root) => {
                let key = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
                inner.workspaces.get(&key)
            }
            None => inner.default_workspace(),
        };
        ws.and_then(|ws| ws.focused.clone())
            .unwrap_or_else(|| crate::workspace::ROOT_PROJECT_ID.to_string())
    }

    /// Invalidate call-edge cache entries for `path`.
    ///
    /// Called alongside `lsp.notify_file_changed` at every write-tool call site
    /// so that call-graph queries see fresh results after a file is modified.
    /// Best-effort: opens the project DB if one exists, then deletes all cached
    /// edges whose ref-site matches `path`. Silently no-ops when:
    /// - no project is active,
    /// - the embed DB does not exist yet (pre-index state),
    /// - or the DB open / DELETE fails (non-fatal degraded mode).
    pub async fn invalidate_call_edges(&self, path: &std::path::Path) {
        let root = {
            let inner = self.inner.read().await;
            inner.active_project().map(|p| p.root.clone())
        };
        let Some(root) = root else { return };

        // Skip invalidation if the call_edges cache file doesn't exist yet —
        // first-time invalidations are no-ops, not errors.
        let cache_db = root.join(".codescout/call_edges.db");
        if !cache_db.exists() {
            return;
        }

        // Derive the canonical project_id the same way the call_graph tool does.
        let project_id = self.call_edges_project_id().await;

        // Spawn blocking so we don't hold the async executor on a sqlite open.
        let path = path.to_path_buf();
        let _ = tokio::task::spawn_blocking(move || {
            let conn = match crate::tools::symbol::call_edges::cache::open_db(&root) {
                Ok(c) => c,
                Err(_) => return,
            };
            let cache = crate::tools::symbol::call_edges::cache::EdgeCache::new(&conn, &project_id);
            let _ = cache.invalidate_file(&path);
        })
        .await;
    }

    /// Pinned twin of `invalidate_call_edges`: invalidates the call-edge cache for
    /// `path` in the workspace named by `workspace_override` (or the default).
    /// Resolves BOTH the DB root and the `project_id` namespace from the pinned
    /// workspace so it agrees with `call_graph`'s pinned upsert/read. Best-effort,
    /// same no-op conditions as the ambient twin.
    pub async fn invalidate_call_edges_for(
        &self,
        workspace_override: Option<&Path>,
        path: &std::path::Path,
    ) {
        let root = self
            .with_project_at(workspace_override, |p| Ok(p.root.clone()))
            .await
            .ok();
        let Some(root) = root else { return };

        let cache_db = root.join(".codescout/call_edges.db");
        if !cache_db.exists() {
            return;
        }

        let project_id = self.call_edges_project_id_for(workspace_override).await;
        let path = path.to_path_buf();
        let _ = tokio::task::spawn_blocking(move || {
            let conn = match crate::tools::symbol::call_edges::cache::open_db(&root) {
                Ok(c) => c,
                Err(_) => return,
            };
            let cache = crate::tools::symbol::call_edges::cache::EdgeCache::new(&conn, &project_id);
            let _ = cache.invalidate_file(&path);
        })
        .await;
    }
}

// ---------------------------------------------------------------------------
// Workspace & discovery
// ---------------------------------------------------------------------------
impl Agent {
    /// Get optional project root (None if no workspace is active).
    ///
    /// Uses the same `focused_project_root()` path as `require_project_root()` so
    /// that read tools and write tools always agree on the project root — even when
    /// the focused project is still `Dormant` (i.e. after `switch_focus` to a
    /// sub-project that hasn't been fully loaded yet).
    pub async fn project_root(&self) -> Option<PathBuf> {
        let inner = self.inner.read().await;
        inner.default_workspace()?.focused_project_root().ok()
    }

    pub async fn is_project_explicitly_activated(&self) -> bool {
        self.inner.read().await.project_explicitly_activated
    }

    /// Return the home project root (the first project activated in this session).
    pub async fn home_root(&self) -> Option<PathBuf> {
        self.inner.read().await.home_root.clone()
    }

    /// True when the active project is the home project (or both are None).
    pub async fn is_home(&self) -> bool {
        let inner = self.inner.read().await;
        match (inner.active_project(), &inner.home_root) {
            (Some(project), Some(home)) => project.root == *home,
            (None, None) => true,
            _ => false,
        }
    }

    /// Return the list of discovered projects from the active workspace.
    /// Returns an empty vec if no workspace is active.
    pub async fn discovered_projects(&self) -> Vec<crate::workspace::DiscoveredProject> {
        let inner = self.inner.read().await;
        inner
            .default_workspace()
            .map(|ws| ws.projects.iter().map(|p| p.discovered.clone()).collect())
            .unwrap_or_default()
    }

    /// Returns per-project memory topic lists for all workspace projects that have memories.
    /// Returns an empty vec for single-project activations (workspace absent or len ≤ 1).
    pub async fn workspace_project_memories(&self) -> Vec<(String, Vec<String>)> {
        let inner = self.inner.read().await;
        let ws = match inner.default_workspace() {
            Some(ws) if ws.projects.len() > 1 => ws,
            _ => return vec![],
        };
        ws.projects
            .iter()
            .filter_map(|p| {
                let dir = ws.memory_dir_for_project(&p.discovered.id);
                let topics = crate::memory::MemoryStore::from_dir(dir)
                    .ok()?
                    .list()
                    .unwrap_or_default();
                if topics.is_empty() {
                    None
                } else {
                    Some((p.discovered.id.clone(), topics))
                }
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
impl Agent {
    /// Get the security config, or defaults if no project is active.
    /// Populates `library_paths` from the active project's library registry.
    pub async fn security_config(&self) -> crate::util::path_security::PathSecurityConfig {
        let inner = self.inner.read().await;
        match inner.active_project() {
            Some(p) => project_security_config(p),
            None => crate::util::path_security::PathSecurityConfig::default(),
        }
    }

    /// Resolve the per-language `mux` override from the active project's config.
    /// Returns `None` when no project is active or no override is set for the language.
    pub async fn lsp_mux_override(&self, language: &str) -> Option<bool> {
        self.with_project(|p| Ok(p.config.lsp.langs.get(language).and_then(|o| o.mux)))
            .await
            .unwrap_or(None)
    }

    /// Get a clone of the library registry, if a project is active.
    pub async fn library_registry(&self) -> Option<LibraryRegistry> {
        self.inner
            .read()
            .await
            .active_project()
            .map(|p| p.library_registry.clone())
    }

    /// Persist the library registry to disk.
    pub async fn save_library_registry(&self) -> Result<()> {
        let inner = self.inner.read().await;
        let project = inner
            .active_project()
            .ok_or_else(|| anyhow::anyhow!("No active project"))?;
        let path = project.root.join(".codescout").join("libraries.json");
        project.library_registry.save(&path)
    }
}

// ---------------------------------------------------------------------------
// Embedding & library indexing
// ---------------------------------------------------------------------------
impl Agent {
    /// Check if we should nudge about a library. Returns true at most once per
    /// session per library, and respects the persistent `nudge_dismissed` flag.
    pub async fn should_nudge(&self, lib_name: &str) -> bool {
        // Check persistent dismissal and indexed status
        let inner = self.inner.read().await;
        if let Some(p) = inner.active_project() {
            if let Some(entry) = p.library_registry.lookup(lib_name) {
                if entry.nudge_dismissed || entry.indexed {
                    return false;
                }
            }
        }
        drop(inner);

        // Check session dedup — insert returns true if the value was NEW
        let mut nudged = self
            .nudged_libraries
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        nudged.insert(lib_name.to_string())
    }

    /// Update the indexing state for a named library.
    pub fn set_library_state(&self, name: &str, state: LibraryIndexState) {
        let mut states = self
            .library_index_states
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        states.insert(name.to_string(), state);
    }

    /// Spawn a background library indexing task if auto_index is enabled and library is not yet indexed.
    pub async fn maybe_auto_index_library(&self, lib_name: &str) {
        let (should_index, _root, entry_path) = {
            let inner = self.inner.read().await;
            let Some(p) = inner.active_project() else {
                return;
            };
            if !p.config.libraries.auto_index {
                return;
            }
            let Some(entry) = p.library_registry.lookup(lib_name) else {
                return;
            };
            if entry.indexed {
                return;
            }
            (true, p.root.clone(), entry.path.clone())
        };
        if !should_index {
            return;
        }

        let name = lib_name.to_string();
        let lib_project_id = format!("lib:{}", name);
        self.set_library_state(&name, LibraryIndexState::Indexing { done: 0, total: 0 });

        let self_clone = self.clone();
        let sync_abort_for_task = self.active_sync_abort.clone();
        let sync_abort_for_store = self.active_sync_abort.clone();
        let task = tokio::spawn(async move {
            tracing::info!("Auto-indexing library '{}' in background...", name);
            let result = async {
                let client = crate::retrieval::client::RetrievalClient::from_env().await?;
                let opts = crate::retrieval::sync::SyncOpts::default();
                client
                    .sync_project(&lib_project_id, &entry_path, opts)
                    .await
            }
            .await;
            match result {
                Ok(_report) => {
                    let mut inner = self_clone.inner.write().await;
                    if let Some(p) = inner.active_project_mut() {
                        if let Some(entry) = p.library_registry.lookup_mut(&name) {
                            entry.indexed = true;
                        }
                        let reg_path = p.root.join(".codescout/libraries.json");
                        let _ = p.library_registry.save(&reg_path);
                    }
                    drop(inner);
                    self_clone.set_library_state(
                        &name,
                        LibraryIndexState::Done {
                            chunks: 0,
                            version: String::new(),
                        },
                    );
                }
                Err(e) => {
                    self_clone.set_library_state(&name, LibraryIndexState::Failed(e.to_string()));
                }
            }
            // Clear the abort handle slot — task is done, nothing to cancel.
            *sync_abort_for_task
                .lock()
                .unwrap_or_else(|e| e.into_inner()) = None;
        });
        *sync_abort_for_store
            .lock()
            .unwrap_or_else(|e| e.into_inner()) = Some(task.abort_handle());
    }

    /// Return a human-readable summary string for each tracked library.
    pub fn library_states_summary(&self) -> HashMap<String, String> {
        let states = self
            .library_index_states
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        states
            .iter()
            .map(|(k, v)| {
                let status = match v {
                    LibraryIndexState::Idle => "idle".to_string(),
                    LibraryIndexState::FetchingSources { command } => {
                        format!("fetching_sources: {}", command)
                    }
                    LibraryIndexState::Indexing { done, total } => {
                        format!("indexing: {}/{}", done, total)
                    }
                    LibraryIndexState::Done { chunks, version } => {
                        format!("done: {} chunks (v{})", chunks, version)
                    }
                    LibraryIndexState::Failed(msg) => format!("failed: {}", msg),
                };
                (k.clone(), status)
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Semantic memory store (Qdrant)
// ---------------------------------------------------------------------------
impl Agent {
    /// Lazily construct (or return cached) the semantic memory store.
    ///
    /// Backend is selected by `CODESCOUT_VECTOR_BACKEND`: Qdrant (server stack,
    /// one network probe + `memories` collection bootstrap) or in-process
    /// sqlite-vec (lite stack, no daemon). Subsequent calls return the cached
    /// `Arc` without further I/O.
    ///
    /// In tests, pre-populate via `set_semantic_memory_store_for_test` to bypass
    /// the env-driven construction path.
    pub async fn semantic_memory_store(&self) -> anyhow::Result<Arc<dyn SemanticMemoryStore>> {
        use crate::retrieval::code_store::VectorBackend;
        self.semantic_memory
            .get_or_try_init(|| async {
                match VectorBackend::resolve() {
                    VectorBackend::SqliteVec => {
                        let store =
                            crate::memory::sqlite_semantic_store::SqliteVecSemanticMemoryStore::from_env()?;
                        anyhow::Ok(Arc::new(store) as Arc<dyn SemanticMemoryStore>)
                    }
                    #[cfg(feature = "server-stack")]
                    VectorBackend::Qdrant => {
                        let config = crate::retrieval::config::RetrievalConfig::from_env()?;
                        let qdrant =
                            crate::retrieval::qdrant::QdrantWrap::connect(&config.qdrant_url).await?;
                        let collection = config.collection("memories");
                        let dim = config.model_dim as u64;
                        let store = crate::memory::semantic_store::QdrantSemanticMemoryStore::new(
                            qdrant, collection, dim,
                        )
                        .await?;
                        anyhow::Ok(Arc::new(store) as Arc<dyn SemanticMemoryStore>)
                    }
                    #[cfg(not(feature = "server-stack"))]
                    VectorBackend::Qdrant => anyhow::bail!(
                        "CODESCOUT_VECTOR_BACKEND=qdrant requires the `server-stack` build \
                         feature. Rebuild with `--features server-stack`, or use the lean lite \
                         stack with CODESCOUT_VECTOR_BACKEND=sqlite-vec."
                    ),
                }
            })
            .await
            .cloned()
    }

    /// Test seam: pre-populate the OnceCell with a stub store so tests don't
    /// hit the network. Fails (silently) if already initialized — call before
    /// any production code path triggers `semantic_memory_store()`.
    #[cfg(test)]
    pub fn set_semantic_memory_store_for_test(
        &self,
        store: Arc<dyn SemanticMemoryStore>,
    ) -> std::result::Result<(), tokio::sync::SetError<Arc<dyn SemanticMemoryStore>>> {
        self.semantic_memory.set(store)
    }

    /// Lazily construct (or return cached) the dense embedder for memory ops.
    ///
    /// First call performs `RetrievalClient::from_env()` (one network probe)
    /// and wraps the resulting `EmbedderHttp` in [`HttpDenseEmbedder`].
    /// Subsequent calls share the cached `Arc`.
    ///
    /// In tests, pre-populate via [`Agent::set_memory_embedder_for_test`] to
    /// bypass the env-driven construction path.
    pub async fn memory_embedder(
        &self,
    ) -> anyhow::Result<Arc<dyn crate::retrieval::embedder::DenseEmbedder>> {
        self.memory_embedder
            .get_or_try_init(|| async {
                let client = crate::retrieval::client::RetrievalClient::from_env().await?;
                let emb = crate::retrieval::embedder::HttpDenseEmbedder::new(client.embedder);
                anyhow::Ok(Arc::new(emb) as Arc<dyn crate::retrieval::embedder::DenseEmbedder>)
            })
            .await
            .cloned()
    }

    /// Test seam: pre-populate the embedder cell so tool calls bypass
    /// `RetrievalClient::from_env`. Must be called before the first
    /// `memory_embedder()` invocation; later calls return [`SetError`].
    #[cfg(test)]
    pub fn set_memory_embedder_for_test(
        &self,
        embedder: Arc<dyn crate::retrieval::embedder::DenseEmbedder>,
    ) -> std::result::Result<
        (),
        tokio::sync::SetError<Arc<dyn crate::retrieval::embedder::DenseEmbedder>>,
    > {
        self.memory_embedder.set(embedder)
    }
}

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

    /// Canonicalize a path. On macOS this resolves the `/var` → `/private/var`
    /// symlink that `tempfile::tempdir` returns un-canonicalized but production
    /// code paths canonicalize via `std::fs::canonicalize`.
    fn canonical(p: &std::path::Path) -> std::path::PathBuf {
        std::fs::canonicalize(p).expect("path canonicalizes")
    }

    #[tokio::test]
    async fn new_without_project() {
        let agent = Agent::new(None).await.unwrap();
        assert!(agent.require_project_root().await.is_err());
        assert!(agent.project_status().await.is_none());
    }

    #[tokio::test]
    async fn new_with_valid_project() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let root = agent.require_project_root().await.unwrap();
        assert_eq!(root, canonical(dir.path()));
    }

    #[tokio::test]
    async fn activate_sets_project() {
        let agent = Agent::new(None).await.unwrap();
        assert!(agent.require_project_root().await.is_err());

        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();

        let root = agent.require_project_root().await.unwrap();
        assert_eq!(root, canonical(dir.path()));
    }

    #[tokio::test]
    async fn activate_replaces_previous_project() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();

        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();
        assert_eq!(
            agent.require_project_root().await.unwrap(),
            canonical(dir1.path())
        );

        agent
            .activate(dir2.path().to_path_buf(), None)
            .await
            .unwrap();
        assert_eq!(
            agent.require_project_root().await.unwrap(),
            canonical(dir2.path())
        );
    }
    #[tokio::test]
    async fn activate_registers_default_workspace_by_canonical_root() {
        // Pins the Phase-1 registry invariant: after activate(root), the default
        // resolves to that canonical root, the registry is keyed by it, and the
        // focused project's root matches. The resolution invariant is durable
        // through Phase 3 (multi-residence); only the single-entry assertion is
        // Phase-1-specific (clear + reinsert on activate).
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let root = canonical(dir.path());

        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();

        {
            let inner = agent.inner.read().await;
            assert_eq!(
                inner.default_workspace_root.as_deref(),
                Some(root.as_path()),
                "default_workspace_root must be the canonical activated root"
            );
            assert!(
                inner.workspaces.contains_key(&root),
                "registry must be keyed by the canonical root"
            );
            assert_eq!(
                inner.workspaces.len(),
                1,
                "Phase 1: single-entry registry (clear + reinsert on activate)"
            );
        }

        // The focused project resolves through the default workspace to the root.
        let p_root = agent
            .with_project(|p| Ok(p.root().to_path_buf()))
            .await
            .unwrap();
        assert_eq!(p_root, root);

        // Re-activating the same root keeps the single-entry invariant.
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        {
            let inner = agent.inner.read().await;
            assert_eq!(
                inner.workspaces.len(),
                1,
                "re-activate same root: still one entry"
            );
            assert_eq!(
                inner.default_workspace_root.as_deref(),
                Some(root.as_path())
            );
        }
    }
    #[tokio::test]
    async fn require_project_root_for_resolves_pin_over_default() {
        // Phase 3: the pinned accessors resolve workspace A even when the
        // default is B — the Level-1 resolution every migrated read tool relies
        // on, tested at the accessor seam where they all converge. Proves:
        // pin resolves A, default stays B, both become resident (multi-residence).
        let dir_a = tempdir().unwrap();
        let dir_b = tempdir().unwrap();
        std::fs::create_dir_all(dir_a.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir_b.path().join(".codescout")).unwrap();
        let root_a = canonical(dir_a.path());
        let root_b = canonical(dir_b.path());

        let agent = Agent::new(Some(dir_b.path().to_path_buf())).await.unwrap();

        // Default (unpinned) resolves B.
        assert_eq!(agent.require_project_root().await.unwrap(), root_b);

        // Pinned to A resolves A (activate-on-miss), via both _for accessors.
        assert_eq!(
            agent.require_project_root_for(Some(&root_a)).await.unwrap(),
            root_a
        );
        assert_eq!(
            agent.project_root_for(Some(&root_a)).await,
            Some(root_a.clone())
        );

        // The pin did NOT mutate the default — unpinned calls still resolve B.
        assert_eq!(agent.require_project_root().await.unwrap(), root_b);

        // A and B are both resident now (multi-residence); default is still B.
        let inner = agent.inner.read().await;
        assert!(
            inner.workspaces.contains_key(&root_a),
            "pinned workspace A must be resident"
        );
        assert!(
            inner.workspaces.contains_key(&root_b),
            "default workspace B must remain resident"
        );
        assert_eq!(
            inner.default_workspace_root.as_deref(),
            Some(root_b.as_path())
        );
    }

    #[tokio::test]
    async fn require_project_root_error_message() {
        let agent = Agent::new(None).await.unwrap();
        let err = agent.require_project_root().await.unwrap_err();
        assert!(
            err.to_string().contains("No active project"),
            "error should mention no active project: {}",
            err
        );
    }
    #[test]
    fn concurrent_switch_warning_flags_rapid_foreign_switch() {
        use std::time::Duration;
        let a = std::path::Path::new("/tmp/cc-wt-a");
        let b = std::path::Path::new("/tmp/cc-wt-b");
        let window = Duration::from_secs(5);

        // First activation (no prior) → silent.
        assert!(Agent::concurrent_switch_warning(None, a, window).is_none());

        // Rapid switch to a DIFFERENT root → warning (the subagent-race signature).
        // The message must recommend per-request pinning as the primary fix and
        // separate windows as the fallback — both are guidance contracts.
        let w = Agent::concurrent_switch_warning(Some((a, Duration::from_millis(200))), b, window);
        assert!(w.as_deref().is_some_and(|s| {
            s.contains("workspace=<absolute path>") && s.contains("separate client windows")
        }));

        // Same-root re-activation → silent (normal return-home / re-activate).
        assert!(
            Agent::concurrent_switch_warning(Some((a, Duration::from_millis(200))), a, window)
                .is_none()
        );

        // Different root but OUTSIDE the window (slow sequential switch) → silent.
        assert!(
            Agent::concurrent_switch_warning(Some((a, Duration::from_secs(60))), b, window)
                .is_none()
        );
    }

    #[tokio::test]
    async fn with_project_errors_when_none() {
        let agent = Agent::new(None).await.unwrap();
        let result = agent.with_project(|_p| Ok(42)).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn with_project_runs_closure() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();

        let name = agent
            .with_project(|p| Ok(p.config.project.name.clone()))
            .await
            .unwrap();
        // Default config uses directory name
        assert!(!name.is_empty());
    }

    #[tokio::test]
    async fn project_status_returns_none_without_project() {
        let agent = Agent::new(None).await.unwrap();
        assert!(agent.project_status().await.is_none());
    }

    #[tokio::test]
    async fn project_status_returns_some_with_project() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();

        let status = agent.project_status().await;
        assert!(status.is_some());
        let status = status.unwrap();
        assert!(!status.name.is_empty());
        let canonical_dir = canonical(dir.path());
        assert!(status.path.contains(canonical_dir.to_str().unwrap()));
    }

    #[tokio::test]
    async fn agent_is_clone_safe() {
        // Agent wraps Arc<RwLock<...>> so clones share state
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(None).await.unwrap();
        let agent2 = agent.clone();

        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        // Clone should see the activation
        let root = agent2.require_project_root().await.unwrap();
        assert_eq!(root, canonical(dir.path()));
    }

    #[tokio::test]
    async fn activate_creates_empty_library_registry() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();

        let reg = agent.library_registry().await.unwrap();
        assert!(
            reg.all().is_empty(),
            "fresh project should have empty library registry"
        );
    }

    #[tokio::test]
    async fn library_registry_none_without_project() {
        let agent = Agent::new(None).await.unwrap();
        assert!(agent.library_registry().await.is_none());
    }

    #[tokio::test]
    async fn project_status_reads_system_prompt_file() {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join(".codescout");
        std::fs::create_dir_all(&config_dir).unwrap();
        std::fs::write(
            config_dir.join("project.toml"),
            "[project]\nname = \"test\"\n",
        )
        .unwrap();
        std::fs::write(config_dir.join("system-prompt.md"), "Always use pytest.\n").unwrap();

        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        let status = agent.project_status().await.unwrap();
        assert_eq!(
            status.system_prompt.as_deref(),
            Some("Always use pytest.\n")
        );
    }

    #[tokio::test]
    async fn project_status_falls_back_to_toml_system_prompt() {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join(".codescout");
        std::fs::create_dir_all(&config_dir).unwrap();
        std::fs::write(
            config_dir.join("project.toml"),
            "[project]\nname = \"test\"\nsystem_prompt = \"From TOML\"\n",
        )
        .unwrap();

        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        let status = agent.project_status().await.unwrap();
        assert_eq!(status.system_prompt.as_deref(), Some("From TOML"));
    }

    #[tokio::test]
    async fn project_status_file_takes_precedence_over_toml() {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join(".codescout");
        std::fs::create_dir_all(&config_dir).unwrap();
        std::fs::write(
            config_dir.join("project.toml"),
            "[project]\nname = \"test\"\nsystem_prompt = \"From TOML\"\n",
        )
        .unwrap();
        std::fs::write(config_dir.join("system-prompt.md"), "From file\n").unwrap();

        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        let status = agent.project_status().await.unwrap();
        assert_eq!(status.system_prompt.as_deref(), Some("From file\n"));
    }

    #[tokio::test]
    async fn project_not_explicitly_activated_without_project() {
        let agent = Agent::new(None).await.unwrap();
        assert!(!agent.is_project_explicitly_activated().await);
    }

    #[tokio::test]
    async fn activate_sets_explicitly_activated() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        assert!(agent.is_project_explicitly_activated().await);
    }

    #[tokio::test]
    async fn new_with_project_sets_explicitly_activated() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        assert!(agent.is_project_explicitly_activated().await);
    }

    #[tokio::test]
    async fn home_root_set_from_initial_project() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        assert_eq!(agent.home_root().await, Some(canonical(dir.path())));
    }

    #[tokio::test]
    async fn home_root_none_without_project() {
        let agent = Agent::new(None).await.unwrap();
        assert_eq!(agent.home_root().await, None);
    }

    #[tokio::test]
    async fn home_root_set_on_first_activate() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        assert_eq!(agent.home_root().await, Some(canonical(dir.path())));
    }

    #[tokio::test]
    async fn home_root_not_changed_by_second_activate() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();
        agent
            .activate(dir2.path().to_path_buf(), None)
            .await
            .unwrap();
        assert_eq!(agent.home_root().await, Some(canonical(dir1.path())));
    }

    #[tokio::test]
    async fn is_home_true_when_at_home() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        assert!(agent.is_home().await);
    }

    #[tokio::test]
    async fn is_home_false_after_switching() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();
        agent
            .activate(dir2.path().to_path_buf(), None)
            .await
            .unwrap();
        assert!(!agent.is_home().await);
    }

    #[tokio::test]
    async fn is_home_true_after_returning() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();
        agent
            .activate(dir2.path().to_path_buf(), None)
            .await
            .unwrap();
        assert!(!agent.is_home().await);
        agent
            .activate(dir1.path().to_path_buf(), None)
            .await
            .unwrap();
        assert!(agent.is_home().await);
    }

    #[tokio::test]
    async fn new_with_relative_path_canonicalizes_home_root() {
        let dir = tempdir().unwrap();
        let canonical = dir.path().canonicalize().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();

        // Simulate --project with a relative path by constructing one that
        // points to the same directory.  We use the tempdir's last component
        // as a relative path from its parent.
        let parent = canonical.parent().unwrap();
        let rel = canonical.file_name().unwrap();

        // Save and restore CWD so the test doesn't affect others.
        let orig_cwd = std::env::current_dir().unwrap();
        std::env::set_current_dir(parent).unwrap();
        let agent = Agent::new(Some(PathBuf::from(rel))).await.unwrap();
        std::env::set_current_dir(&orig_cwd).unwrap();

        // home_root must be the canonical absolute path, not the relative input.
        let home = agent.home_root().await.unwrap();
        assert!(
            home.is_absolute(),
            "home_root should be absolute, got: {}",
            home.display()
        );
        assert_eq!(home, canonical);

        // is_home should be true when re-activating the same directory
        // (simulates activate_project(".") which canonicalizes).
        agent.activate(canonical.clone(), None).await.unwrap();
        assert!(
            agent.is_home().await,
            "is_home must be true after re-activating the same directory"
        );
    }

    #[tokio::test]
    async fn active_project_has_private_memory() {
        let dir = tempdir().unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        agent
            .with_project(|p| {
                p.private_memory.write("pref", "verbose")?;
                assert_eq!(p.private_memory.read("pref")?, Some("verbose".to_string()));
                // private is isolated from shared
                assert_eq!(p.memory.read("pref")?, None);
                Ok(())
            })
            .await
            .unwrap();
    }

    /// Regression test: after switch_focus to a sub-project, project_root() must
    /// return the sub-project root (same as require_project_root), not None.
    ///
    /// Uses the three-query sandwich:
    ///   1. Baseline: both methods agree on root
    ///   2. switch_focus to Dormant sub-project
    ///   3. Assert project_root() == sub-project root (not None — the bug)
    #[tokio::test]
    async fn project_root_matches_require_project_root_after_switch_focus() {
        let dir = tempdir().unwrap();
        let root = dir.path().to_path_buf();

        // Create a sub-project with a package.json so discover_projects picks it up
        let sub = root.join("packages").join("api");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(
            sub.join("package.json"),
            r#"{"name":"api","scripts":{"build":"tsc"}}"#,
        )
        .unwrap();

        let agent = Agent::new(Some(root.clone())).await.unwrap();

        // Step 1: baseline — both methods agree on root
        let pr = agent.project_root().await;
        let rpr = agent.require_project_root().await.unwrap();
        assert!(
            pr.is_some(),
            "project_root() must be Some before switch_focus"
        );
        assert_eq!(
            pr.unwrap(),
            rpr,
            "project_root() and require_project_root() must agree before switch_focus"
        );

        // Step 2: switch focus to the Dormant sub-project
        agent.switch_focus("api").await.unwrap();

        // Step 3: both methods must still agree — and return the sub-project root.
        // Before the fix, project_root() returned None here (Dormant bug).
        let pr_after = agent.project_root().await;
        let rpr_after = agent.require_project_root().await.unwrap();
        assert!(
            pr_after.is_some(),
            "project_root() must not be None after switch_focus (Dormant-project bug)"
        );
        assert_eq!(
            pr_after.unwrap(),
            rpr_after,
            "project_root() and require_project_root() must agree after switch_focus"
        );
        assert!(
            rpr_after.ends_with("packages/api"),
            "focused root must be the sub-project: {:?}",
            rpr_after
        );
    }

    #[tokio::test]
    async fn activate_non_home_defaults_to_read_only() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();

        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();
        agent
            .activate(dir2.path().to_path_buf(), None)
            .await
            .unwrap();

        let config = agent.security_config().await;
        assert!(
            !config.file_write_enabled,
            "non-home project should be read-only by default"
        );
    }

    #[tokio::test]
    async fn activate_non_home_with_read_only_false_is_writable() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();

        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();
        agent
            .activate(dir2.path().to_path_buf(), Some(false))
            .await
            .unwrap();

        let config = agent.security_config().await;
        assert!(
            config.file_write_enabled,
            "explicit read_only=false should enable writes"
        );
    }

    #[tokio::test]
    async fn activate_home_always_writable() {
        let dir1 = tempdir().unwrap();
        let dir2 = tempdir().unwrap();
        std::fs::create_dir_all(dir1.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir2.path().join(".codescout")).unwrap();

        let agent = Agent::new(Some(dir1.path().to_path_buf())).await.unwrap();

        // Switch away (read-only)
        agent
            .activate(dir2.path().to_path_buf(), None)
            .await
            .unwrap();
        assert!(!agent.security_config().await.file_write_enabled);

        // Return home
        agent
            .activate(dir1.path().to_path_buf(), None)
            .await
            .unwrap();
        assert!(
            agent.security_config().await.file_write_enabled,
            "home project should always be writable"
        );
    }

    #[tokio::test]
    async fn first_activate_is_writable() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();

        let agent = Agent::new(None).await.unwrap();
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();

        let config = agent.security_config().await;
        assert!(
            config.file_write_enabled,
            "first activated project should be writable (becomes home)"
        );
    }

    #[tokio::test]
    async fn workspace_summary_returns_projects_with_depends_on() {
        let dir = tempdir().unwrap();
        let root = dir.path().to_path_buf();

        // Create two sub-projects
        let sub_a = root.join("packages").join("api");
        let sub_b = root.join("packages").join("web");
        std::fs::create_dir_all(&sub_a).unwrap();
        std::fs::create_dir_all(&sub_b).unwrap();
        std::fs::write(
            sub_a.join("package.json"),
            r#"{"name":"api","scripts":{"build":"tsc"}}"#,
        )
        .unwrap();
        std::fs::write(
            sub_b.join("package.json"),
            r#"{"name":"web","scripts":{"build":"tsc"}}"#,
        )
        .unwrap();

        let agent = Agent::new(Some(root)).await.unwrap();
        let summary = agent.workspace_summary().await;
        assert!(
            summary.is_some(),
            "multi-project workspace should have summary"
        );
        let projects = summary.unwrap();
        assert!(projects.len() >= 2, "should have at least 2 sub-projects");
        // Each entry should have depends_on field (even if empty)
        for p in &projects {
            let _ = &p.depends_on;
        }
    }

    #[tokio::test]
    async fn workspace_summary_returns_none_for_single_project() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let summary = agent.workspace_summary().await;
        assert!(
            summary.is_none(),
            "single-project workspace should return None"
        );
    }

    #[tokio::test]
    async fn activate_within_workspace_promotes_dormant() {
        let dir = tempdir().unwrap();
        let root = dir.path().to_path_buf();

        // Create a sub-project
        let sub = root.join("packages").join("api");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(
            sub.join("package.json"),
            r#"{"name":"api","scripts":{"build":"tsc"}}"#,
        )
        .unwrap();

        let agent = Agent::new(Some(root.clone())).await.unwrap();

        // Before: sub-project is Dormant — active_project() returns None after switch_focus
        agent.switch_focus("api").await.unwrap();
        let is_dormant = {
            let inner = agent.inner.read().await;
            inner.active_project().is_none()
        };
        assert!(
            is_dormant,
            "sub-project should be Dormant before activate_within_workspace"
        );

        // Switch back to home first
        agent
            .switch_focus(crate::workspace::ROOT_PROJECT_ID)
            .await
            .unwrap();

        // Now use activate_within_workspace
        agent.activate_within_workspace("api", None).await.unwrap();

        // After: with_project works
        let name = agent
            .with_project(|p| Ok(p.config.project.name.clone()))
            .await
            .unwrap();
        assert!(
            !name.is_empty(),
            "should have loaded config for sub-project"
        );

        // Workspace topology preserved — all original projects still exist
        let project_count = {
            let inner = agent.inner.read().await;
            inner.default_workspace().unwrap().projects.len()
        };
        assert!(
            project_count >= 2,
            "workspace should still have all projects"
        );
    }

    #[tokio::test]
    async fn activate_within_workspace_unknown_id_errors() {
        let dir = tempdir().unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let result = agent.activate_within_workspace("nonexistent", None).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn activate_populates_head_sha() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        // Init a git repo so there's a HEAD to read.
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(dir.path())
            .env("GIT_AUTHOR_NAME", "Test")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .output()
            .unwrap();

        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let sha = agent
            .with_project(|p| Ok(p.head_sha.clone()))
            .await
            .unwrap();
        assert!(sha.is_some(), "head_sha should be set for a git project");
        assert!(
            sha.as_ref().unwrap().len() >= 7,
            "SHA should be at least 7 chars"
        );
    }

    #[tokio::test]
    async fn head_sha_none_for_non_git_project() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let sha = agent
            .with_project(|p| Ok(p.head_sha.clone()))
            .await
            .unwrap();
        assert!(sha.is_none(), "head_sha should be None for non-git project");
    }

    #[tokio::test]
    async fn drain_dirty_files_clears_set_and_returns_paths() {
        use std::path::PathBuf;

        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();

        let a = PathBuf::from("/proj/src/a.rs");
        let b = PathBuf::from("/proj/src/b.rs");
        agent.mark_file_dirty(a.clone()).await;
        agent.mark_file_dirty(b.clone()).await;

        let mut drained = agent.drain_dirty_files().await;
        drained.sort();
        assert_eq!(drained, vec![a, b]);

        // Set must be empty after drain
        assert!(agent.drain_dirty_files().await.is_empty());
    }
    #[tokio::test]
    async fn session_write_roots_empty_by_default() {
        let dir = tempdir().unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let roots = agent.session_write_roots_snapshot().await;
        assert!(roots.is_empty());
    }

    #[tokio::test]
    async fn add_session_write_root_visible_in_snapshot() {
        let dir = tempdir().unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let extra = dir.path().join("extra");
        agent.add_session_write_root(extra.clone()).await;
        let roots = agent.session_write_roots_snapshot().await;
        assert_eq!(roots, vec![extra]);
    }

    #[tokio::test]
    async fn session_write_roots_cleared_on_reactivation() {
        let dir = tempdir().unwrap();
        let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
        let extra = dir.path().join("extra");
        agent.add_session_write_root(extra.clone()).await;
        // Snapshot shows the root
        let roots = agent.session_write_roots_snapshot().await;
        assert!(
            !roots.is_empty(),
            "root should be visible before re-activation"
        );
        // Re-activate same project
        agent
            .activate(dir.path().to_path_buf(), None)
            .await
            .unwrap();
        // Snapshot is now empty — re-activation created a fresh ActiveProject
        let roots_after = agent.session_write_roots_snapshot().await;
        assert!(
            roots_after.is_empty(),
            "session roots must clear on re-activation"
        );
    }
}