symforge 11.3.5

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
//! Shared local daemon for project-aware and session-aware backend state.

use parking_lot::{Condvar, Mutex, RwLock};
use std::collections::{HashMap, HashSet};
use std::io;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, SystemTime};

use anyhow::Context;
use axum::extract::{Path as AxumPath, Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use rmcp::handler::server::wrapper::Parameters;
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;

use crate::domain::{
    CapabilityStatus, ControlStateDir, FreshnessStatus, ProjectCapabilities, RootBinding,
    RootCandidateSource, RootRequestMode, RootResolution, SourceAccessMode, StatePlacement,
    UnboundReason,
};
use crate::live_index::store::LiveIndex;
use crate::live_index::view::{BaseKey, CommitId, IndexBase, Targets, WorkingSet};
use crate::live_index::{self, SharedIndex};
use crate::paths;
use crate::protocol::SymForgeServer;
use crate::protocol::edit::{
    BatchEditInput, BatchInsertInput, BatchRenameInput, DeleteSymbolInput, EditWithinSymbolInput,
    InsertSymbolInput, ReplaceSymbolBodyInput,
};
use crate::protocol::read_tools::SymforgeRetrieveInput;
use crate::protocol::tools::{
    AnalyzeFileImpactInput, CheckpointNowInput, CurateKnowledgeInput, DetectImpactInput,
    DiffSymbolsInput, EditPlanInput, ExploreInput, FindDependentsInput, FindReferencesInput,
    GetFileContentInput, GetFileContextInput, GetRepoMapInput, GetSymbolContextInput,
    GetSymbolInput, HealthInput, IndexFolderInput, InspectMatchInput, InvestigationInput,
    ReviewKnowledgeInput, SearchFilesInput, SearchKnowledgeInput, SearchSymbolsInput,
    SearchTextInput, SmartQueryInput, TraceSymbolInput, ValidateFileSyntaxInput, WhatChangedInput,
    search_symbols_options_from_input, search_text_options_from_input,
};
use crate::sidecar::{SidecarState, SymbolSnapshotCache, TokenStats};
use crate::watcher::{self, WatcherInfo};

// Daemon runtime files are OS-tagged (daemon.<os>.port) so a Windows daemon and a
// WSL/Linux daemon never collide — even when SYMFORGE_HOME is deliberately pointed at
// a shared mount. Without the tag, isolation would rely only on dirs::home_dir()
// landing on different filesystems per OS, which a shared SYMFORGE_HOME defeats.
// The tag is the same compile-time std::env::consts::OS the sidecar uses, so all
// in-crate readers/writers agree by construction. Legacy un-tagged files are read as
// a fallback for one release so an upgrade does not strand a running daemon.
const LEGACY_DAEMON_PORT_FILE: &str = "daemon.port";
const LEGACY_DAEMON_PID_FILE: &str = "daemon.pid";
// Lock files are transient and never read across the upgrade boundary, so the legacy
// name is only needed by the test-only cleanup helper and the test-only assertions
// that write/read the legacy un-tagged names.
#[cfg(test)]
const LEGACY_DAEMON_START_LOCK_FILE: &str = "daemon.starting";

fn daemon_port_file_name() -> String {
    crate::paths::os_tagged_runtime_file_name("daemon", "port")
}
fn daemon_pid_file_name() -> String {
    crate::paths::os_tagged_runtime_file_name("daemon", "pid")
}
fn daemon_start_lock_file_name() -> String {
    crate::paths::os_tagged_runtime_file_name("daemon", "starting")
}
/// OS-tagged auth-token file. Sits alongside the port/pid files in `daemon_dir()`
/// and carries the bearer token the daemon requires on every authenticated
/// route. It is the connection-info channel the legit MCP front-end and hook
/// read when the operator has NOT pinned a token via env — closing the prior
/// "no token ⇒ open daemon" ambient-authority hole without breaking the
/// handshake. On Unix it is created `0o600` (owner read/write only).
fn daemon_token_file_name() -> String {
    crate::paths::os_tagged_runtime_file_name("daemon", "token")
}

/// Read a daemon runtime file under `dir`, OS-tagged name first then legacy.
fn read_daemon_runtime(dir: &std::path::Path, tagged: &str, legacy: &str) -> io::Result<String> {
    match std::fs::read_to_string(dir.join(tagged)) {
        Ok(c) => Ok(c),
        Err(e) if e.kind() == io::ErrorKind::NotFound => std::fs::read_to_string(dir.join(legacy)),
        Err(e) => Err(e),
    }
}
/// Set once this process binds AS the daemon (see `spawn_daemon_at`, where it
/// writes its own pid file). Only a bound daemon can become an orphan, so
/// [`unrecorded_daemon_pid`] stays silent for every other topology — stdio,
/// embed, and the MCP adapter front-end.
static DAEMON_BOUND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

const DAEMON_BIND_ENV: &str = "SYMFORGE_DAEMON_BIND";
const DAEMON_ALLOW_NON_LOOPBACK_ENV: &str = "SYMFORGE_DAEMON_ALLOW_NON_LOOPBACK";
/// Task 9: seconds a session may go without a heartbeat before the daemon
/// reaper closes it through the normal close path. Override with
/// `SYMFORGE_SESSION_TTL_SECS` (clamped to >= 60). The default is deliberately
/// long — a reaped session cannot be resurrected, so only clearly abandoned
/// sessions qualify.
const SESSION_TTL_ENV: &str = "SYMFORGE_SESSION_TTL_SECS";
const DEFAULT_SESSION_TTL_SECS: u64 = 86_400;
/// A session whose heartbeat is older than this is STALE. The stdio adapter
/// beats every 15 s, so 120 s is eight missed beats. Stale sessions are
/// counted apart from live ones in health, and the reaper closes a stale
/// session early when its recorded pid is also gone.
const STALE_SESSION_HEARTBEAT: Duration = Duration::from_secs(120);
/// Reaper cadence ceiling: the pid rule must notice a dead adapter within
/// about one stale window plus one tick, not one TTL quarter.
const SESSION_REAP_TICK_SECS: u64 = 60;

fn session_ttl_from_env() -> std::time::Duration {
    let secs = std::env::var(SESSION_TTL_ENV)
        .ok()
        .and_then(|value| value.trim().parse::<u64>().ok())
        .unwrap_or(DEFAULT_SESSION_TTL_SECS)
        .max(60);
    std::time::Duration::from_secs(secs)
}

/// Zombie-daemon guard: seconds without any AUTHENTICATED request before the
/// daemon shuts itself down. Detached auto-spawn defaults to 600 seconds;
/// an explicitly managed `symforge daemon` remains persistent unless this
/// variable is set. Values are clamped to at least 60 seconds; `0` disables.
const DAEMON_IDLE_SHUTDOWN_ENV: &str = "SYMFORGE_DAEMON_IDLE_SHUTDOWN_SECS";
// Snapshot-backed respawn costs milliseconds, so a short window is cheap:
// zombies die within ~10 minutes of the last client's death.
const DEFAULT_DAEMON_IDLE_SHUTDOWN_SECS: u64 = 600;

fn daemon_idle_shutdown_from_env() -> Option<std::time::Duration> {
    let value = std::env::var(DAEMON_IDLE_SHUTDOWN_ENV).ok()?;
    let secs = value
        .trim()
        .parse::<u64>()
        .unwrap_or(DEFAULT_DAEMON_IDLE_SHUTDOWN_SECS);
    (secs > 0).then(|| std::time::Duration::from_secs(secs.max(60)))
}

/// Feature 020 / L-V02: gate that turns ON background publication of P1 local-ref
/// lanes (bare local branches) when a project opens or reloads. OFF by default so
/// the current-only P0 path keeps its measured latency/memory unchanged — ref
/// lanes are strictly opt-in. Accepts `1`/`true`/`on` (case-insensitive); anything
/// else, including unset, is OFF.
const LOCAL_REF_LANES_ENV: &str = "SYMFORGE_LOCAL_REF_LANES";

fn local_ref_lanes_enabled() -> bool {
    std::env::var(LOCAL_REF_LANES_ENV)
        .ok()
        .is_some_and(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "on"
            )
        })
}

const DAEMON_AUTH_TOKEN_ENV: &str = "SYMFORGE_DAEMON_AUTH_TOKEN";
const TRACE_SYMBOL_ALIAS_DEPRECATION: &str = concat!(
    "Deprecation warning: `trace_symbol` is retired; ",
    "use `get_symbol_context` with `sections=[...]` or `find_references` instead. ",
    "Compatibility policy: keep daemon alias through v7.x; planned removal in v8.0."
);
/// D-015-012: CBM migrator ergonomics — route the CBM `detect_changes` tool
/// name to the real `detect_impact` tool so a migrating client's existing
/// tool-name references keep working.
const DETECT_CHANGES_ALIAS_DEPRECATION: &str = concat!(
    "Deprecation warning: `detect_changes` is a CBM-compatibility alias; ",
    "use `detect_impact` instead. Compatibility policy: kept for CBM migrator ",
    "ergonomics (decision-log D-015-012); no removal date set."
);

pub type SharedDaemonState = Arc<DaemonState>;

pub struct DaemonHandle {
    pub port: u16,
    pub shutdown_tx: tokio::sync::oneshot::Sender<()>,
    pub state: SharedDaemonState,
    server_task: tokio::task::JoinHandle<()>,
    /// Task 9: the daemon-owned session reaper. Holds a `Weak` on the
    /// daemon state, so it exits on its own once the daemon shuts down
    /// and the state drops; `run_daemon_until_shutdown` also aborts it
    /// explicitly so restarts/tests cannot leak the interval task.
    reaper_task: tokio::task::JoinHandle<()>,
}

#[derive(Clone)]
pub struct DaemonSessionClient {
    http_client: reqwest::Client,
    base_url: String,
    project_id: String,
    session_id: String,
    project_name: String,
    /// Task 8: roots of projects this connection successfully opened
    /// ADDITIVELY (beyond the immutable home in `project_root`). Ordered,
    /// deduplicated, shared across clones so a reconnect can reopen the
    /// whole working set and verify deterministic IDs before serving.
    opened_roots: std::sync::Arc<parking_lot::Mutex<Vec<PathBuf>>>,
    /// Locked contract: the root a default (non-`add`) `index_folder` last
    /// ACTIVATED for unqualified reads on this connection. `None` = home is
    /// active. Shared across clones so a reconnect can restore the active
    /// project after re-opening the working set.
    active_root: std::sync::Arc<parking_lot::Mutex<Option<PathBuf>>>,
    /// Serializes daemon-backed `index_folder` calls through the matching
    /// adapter ACTIVE-mirror update. Without one shared lane, two overlapping
    /// default opens can activate in daemon order B -> C but record their
    /// adapter mirrors in response order C -> B.
    activation_lane: std::sync::Arc<tokio::sync::Mutex<()>>,
    /// The connected daemon's boot epoch (from /health at connect). Written
    /// into this adapter's session descriptor so descriptor selection can
    /// reject the record after a daemon restart instead of aliasing an
    /// unrelated `session-N`.
    daemon_started_at: Option<u64>,
    auth_token: Option<String>,
    /// The process-coordination namespace that owns this daemon connection.
    /// Reconnect must reuse this exact typed owner rather than re-resolving
    /// mutable environment state.
    control_state_dir: ControlStateDir,
    /// Stored so reconnection can re-open a session at the same project root.
    project_root: Option<PathBuf>,
}

/// Single-flight gate: concurrent first opens of one project id join one cold load.
struct ColdLoadFlight {
    outcome: Mutex<Option<anyhow::Result<Arc<ProjectSlot>>>>,
    ready: Condvar,
}

impl ColdLoadFlight {
    fn new() -> Self {
        Self {
            outcome: Mutex::new(None),
            ready: Condvar::new(),
        }
    }

    fn wait(&self) -> anyhow::Result<Arc<ProjectSlot>> {
        let mut guard = self.outcome.lock();
        while guard.is_none() {
            self.ready.wait(&mut guard);
        }
        match guard.as_ref().expect("notified with outcome") {
            Ok(slot) => Ok(Arc::clone(slot)),
            Err(err) => Err(anyhow::anyhow!("{err}")),
        }
    }

    fn complete(&self, result: anyhow::Result<Arc<ProjectSlot>>) {
        let mut guard = self.outcome.lock();
        *guard = Some(result);
        self.ready.notify_all();
    }

    fn complete_if_pending(&self, result: anyhow::Result<Arc<ProjectSlot>>) {
        let mut guard = self.outcome.lock();
        if guard.is_none() {
            *guard = Some(result);
            self.ready.notify_all();
        }
    }
}

/// Ensures a cold-load leader always publishes an outcome and evicts its flight.
struct ColdLoadLeaderGuard<'a> {
    flight: &'a ColdLoadFlight,
    inflight: &'a Mutex<HashMap<String, Arc<ColdLoadFlight>>>,
    project_id: String,
}

impl Drop for ColdLoadLeaderGuard<'_> {
    fn drop(&mut self) {
        self.flight.complete_if_pending(Err(anyhow::anyhow!(
            "cold load leader unwound before publishing a project slot"
        )));
        self.inflight.lock().remove(&self.project_id);
    }
}

pub struct DaemonState {
    next_session_id: AtomicU64,
    // Registry/session guards protect only map membership and short metadata
    // updates. Project load, reload, watcher lifecycle, and git/file IO always run
    // after those guards are released. Per-session `working_set` is independent.
    /// Per-daemon base intern table (Feature 012). Equal `(canonical_root,
    /// commit)` keys MUST share ONE `Arc<IndexBase>` (SC-002): `intern_base`
    /// returns the existing Arc on a key hit and only mints a new base (drawing a
    /// generation from `base_generation_seq`) on a miss. Populated on project
    /// load/activate and seeded into per-session working sets; the cross-project
    /// read route reads those bases and `intern_base_refresh` FORCE-REPLACES the
    /// value for a key when a watched change has advanced the project's published
    /// index (B2/D12) — still one Arc per `BaseKey` (SC-002).
    /// Cache census (C4c): each value is a projection PINNED to one
    /// publication — keyed by `(canonical_root, commit)`, fenced by its
    /// minted `base_generation`, force-replaced when the published index
    /// advances, and GC'd by the strong-count orphan sweep. C5's leases
    /// take over the pinned-publication identity.
    bases: RwLock<HashMap<BaseKey, Arc<IndexBase>>>,
    /// Monotonic source of `base_generation` fence tokens, minted only when
    /// `intern_base` publishes a NEW base. Starts at 1; a shared (interned) base
    /// keeps its original generation, so this is strictly increasing across
    /// distinct published bases (the D2 fence the engine asserts on).
    base_generation_seq: AtomicU64,
    projects: RwLock<HashMap<String, Arc<ProjectSlot>>>,
    /// In-flight cold loads keyed by project id. The first opener runs
    /// `ProjectInstance::load`; concurrent first opens wait on the same gate.
    cold_load_flights: Mutex<HashMap<String, Arc<ColdLoadFlight>>>,
    sessions: RwLock<HashMap<String, SessionRecord>>,
    identity: DaemonIdentity,
    /// Boot epoch minted once per daemon process (unix seconds). Served on
    /// /health; descriptor selection rejects records from a previous boot.
    started_at_unix_secs: u64,
    /// The bearer token this daemon requires on every authenticated route.
    /// Non-optional by design: the daemon ALWAYS establishes a token at startup
    /// (env pin or freshly generated), so `authorize_daemon_request` is strictly
    /// fail-closed — there is no "no token ⇒ allow" path. Making this a `String`
    /// (not `Option`) encodes the fail-closed invariant in the type system.
    auth_token: String,
    /// Process-global coordination namespace used by daemon discovery and
    /// cross-project idempotency. None preserves the explicit fail-closed
    /// behavior when no durable control state is available.
    control_state_dir: Option<ControlStateDir>,
    /// Concurrency governor — limits parallel tool calls and enforces timeouts.
    governor: crate::sidecar::governor::RequestGovernor,
    /// Epoch millis of the last completed AUTHENTICATED request — the idle-shutdown signal.
    last_activity_at: AtomicU64,
    /// Authenticated handlers currently in flight. Idle shutdown must not cut
    /// off active writes or long indexing requests.
    active_authenticated_requests: AtomicU64,
    /// Notified by the reaper once the idle-shutdown window elapses;
    /// `run_daemon_until_shutdown` treats it like a shutdown signal.
    idle_shutdown: tokio::sync::Notify,
}

struct AuthenticatedActivityGuard {
    state: SharedDaemonState,
}

impl Drop for AuthenticatedActivityGuard {
    fn drop(&mut self) {
        self.state
            .last_activity_at
            .store(now_epoch_millis(), Ordering::Relaxed);
        self.state
            .active_authenticated_requests
            .fetch_sub(1, Ordering::Relaxed);
    }
}

/// Tracks whether a ProjectInstance has been fully activated (watcher + git temporal started).
/// Prevents two racing opens from both activating the same project.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ActivationState {
    /// Freshly constructed, no background tasks started. Safe to discard.
    Inactive,
    /// Activation in progress (watcher + git temporal being started).
    Activating,
    /// Fully active with watcher and git temporal running.
    Active,
}

struct ProjectInstance {
    project_id: String,
    canonical_root: PathBuf,
    project_name: String,
    source_access_mode: SourceAccessMode,
    state_placement: StatePlacement,
    persistence_health: Arc<RwLock<CapabilityStatus>>,
    curation_coordinator: Arc<crate::protocol::knowledge_curation::KnowledgeCurationCoordinator>,
    // C4 (Feature 020 Slice 4, D1): typed handle; the frozen publication_roots
    // census retires bare `SharedIndex` state fields.
    index: crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
    watcher_info: Arc<Mutex<WatcherInfo>>,
    watcher_task: Option<tokio::task::JoinHandle<()>>,
    stop_token: Arc<AtomicBool>,
    /// Shared with this project's background cold load, if it has one.
    background_load: Arc<BackgroundLoad>,
    token_stats: Arc<TokenStats>,
    /// Cache census (C4c): the project's symbol-snapshot cache. Never read
    /// here — flows to `SessionRuntime`/`SidecarState`, whose sole reader
    /// (the sidecar handlers) fences every hit to the current project
    /// generation via `ensure_symbol_cache_generation`. Dropped whole with
    /// the instance on eviction/retarget.
    symbol_cache: Arc<RwLock<SymbolSnapshotCache>>,
    session_ids: HashSet<String>,
    opened_at: SystemTime,
    activation_state: ActivationState,
}

struct ProjectSlot {
    metadata: RwLock<ProjectInstance>,
    /// Serializes project mutation without blocking registry lookup or reads of
    /// the currently published SharedIndex generation.
    mutation: Mutex<()>,
}

struct SessionRecord {
    session_id: String,
    /// The single active project this session resolves to (Feature 012: renamed
    /// from `project_id`). `session_runtime` resolves the one active project via
    /// this id, so single-project behavior is unchanged. Phases 2/3 will let a
    /// session hold MULTIPLE projects in `working_set` with this field naming the
    /// active/bound one; for Phase 0/1 it is the sole project, byte-for-byte the
    /// prior `project_id`.
    active_project_id: String,
    /// The immutable HOME identity (the project this session opened with).
    /// `active_project_id` may move via a default `index_folder`; this never
    /// does — reconnect verifies home identity against it, and health renders
    /// home and active distinctly.
    home_project_id: String,
    /// Per-session copy-on-write working set (Feature 012). Seeded on open with a
    /// SINGLE entry — the active project + its interned shared base + an EMPTY
    /// overlay — and grown by additive opens. The CROSS-PROJECT read route reads
    /// it (Phase 3) and LAZILY REFRESHES each targeted entry's base when the
    /// project's published index has advanced (B2/D12,
    /// `refresh_working_set_bases`); the single-active path never touches it. NO
    /// code path writes into its overlay (the no-overlay-writes invariant that
    /// keeps Principle I airtight). `Arc<RwLock>` is mandatory: `SessionRecord` is
    /// cloned on every `session_runtime` call and `WorkingSet: Clone` deep-clones
    /// overlays, so the `Arc` keeps the clone O(1) and the overlay state singular.
    /// Cache census (C4c): entries hold interned bases pinned per
    /// publication; every cross-project read lazily re-fences its targeted
    /// entry against the CURRENT published index (B2/D12) before serving,
    /// and no path writes into the overlay.
    working_set: Arc<RwLock<WorkingSet>>,
    /// Session-private protocol state, partitioned by project while shared index
    /// and project metrics remain owned by the project instance.
    servers: HashMap<String, SymForgeServer>,
    client_name: String,
    pid: Option<u32>,
    opened_at: SystemTime,
    /// Epoch millis stored atomically so heartbeats only need a read lock.
    last_seen_at: AtomicU64,
}

impl Clone for SessionRecord {
    fn clone(&self) -> Self {
        Self {
            session_id: self.session_id.clone(),
            active_project_id: self.active_project_id.clone(),
            home_project_id: self.home_project_id.clone(),
            // Share the SAME working-set lock across clones (O(1), singular state).
            working_set: Arc::clone(&self.working_set),
            servers: self.servers.clone(),
            client_name: self.client_name.clone(),
            pid: self.pid,
            opened_at: self.opened_at,
            last_seen_at: AtomicU64::new(self.last_seen_at.load(Ordering::Relaxed)),
        }
    }
}

impl SessionRecord {
    /// Convert the atomic epoch-millis value back to a [`SystemTime`].
    fn last_seen_at_time(&self) -> SystemTime {
        let millis = self.last_seen_at.load(Ordering::Relaxed);
        SystemTime::UNIX_EPOCH + Duration::from_millis(millis)
    }

    /// True when the last heartbeat is older than [`STALE_SESSION_HEARTBEAT`].
    fn is_stale(&self, now_millis: u64) -> bool {
        self.last_seen_at.load(Ordering::Relaxed)
            < now_millis.saturating_sub(STALE_SESSION_HEARTBEAT.as_millis() as u64)
    }
}

/// Current time as milliseconds since the Unix epoch.
fn now_epoch_millis() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

fn daemon_auth_token_from_env() -> Option<String> {
    std::env::var(DAEMON_AUTH_TOKEN_ENV)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

/// Read the persisted daemon auth token from the OS-tagged token file in
/// `daemon_dir()`. Returns `None` if the file is absent, empty, or unreadable.
/// This is how a front-end / hook process that did NOT spawn the daemon — and
/// therefore has no `SYMFORGE_DAEMON_AUTH_TOKEN` in its env — still learns the
/// running daemon's token and authenticates.
fn daemon_auth_token_from_file() -> Option<String> {
    let control_state_dir = process_control_state_dir().ok()?;
    daemon_auth_token_from_file_at(control_state_dir)
}

fn daemon_auth_token_from_file_at(control_state_dir: &ControlStateDir) -> Option<String> {
    let dir = daemon_dir_for(control_state_dir).ok()?;
    let contents = std::fs::read_to_string(dir.join(daemon_token_file_name())).ok()?;
    let trimmed = contents.trim().to_string();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed)
    }
}

/// Resolve the daemon auth token a CLIENT (front-end proxy, hook) must present.
///
/// Resolution order:
/// 1. `SYMFORGE_DAEMON_AUTH_TOKEN` env var — explicit operator pin / test
///    override, and what a parent that spawned the daemon shares with it.
/// 2. The persisted token file written by the daemon at startup.
///
/// Returns `None` only when neither source is available; with the fail-closed
/// daemon this means the request will be rejected, which is the safe outcome.
pub(crate) fn resolve_daemon_auth_token() -> Option<String> {
    daemon_auth_token_from_env().or_else(daemon_auth_token_from_file)
}

fn resolve_daemon_auth_token_at(control_state_dir: &ControlStateDir) -> Option<String> {
    daemon_auth_token_from_env().or_else(|| daemon_auth_token_from_file_at(control_state_dir))
}

/// Generate an unpredictable 64-hex-character daemon auth token.
///
/// Prefers the OS CSPRNG via `/dev/urandom` on Unix (a plain file read — no
/// `unsafe`, no extra dependency). When that is unavailable (Windows, or a
/// sandbox without `/dev/urandom`), it falls back to a SHA-256 digest over
/// several process-local entropy sources that a local peer cannot observe or
/// reproduce: high-resolution timestamps, the process id, a heap-allocation
/// address (ASLR), the current thread id, and a per-call atomic counter.
///
/// The token's real confidentiality barrier is the `0o600` token FILE; the
/// token only needs to be non-guessable by a local process that cannot read
/// that file. Both paths satisfy that.
fn generate_daemon_auth_token() -> String {
    #[cfg(unix)]
    {
        use std::io::Read;
        if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
            let mut buf = [0u8; 32];
            if f.read_exact(&mut buf).is_ok() {
                return crate::hash::digest_hex(&buf);
            }
        }
    }

    // Portable fallback: hash a mix of process-local, non-deterministic sources.
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut seed: Vec<u8> = Vec::with_capacity(64);
    let now_nanos = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    seed.extend_from_slice(&now_nanos.to_le_bytes());
    let mono = std::time::Instant::now();
    seed.extend_from_slice(&format!("{mono:?}").into_bytes());
    seed.extend_from_slice(&std::process::id().to_le_bytes());
    seed.extend_from_slice(&COUNTER.fetch_add(1, Ordering::Relaxed).to_le_bytes());
    // Heap-allocation address carries ASLR entropy that is not observable to a
    // peer process without the token file.
    let boxed = Box::new(0u8);
    let addr = (&*boxed as *const u8) as usize;
    seed.extend_from_slice(&addr.to_le_bytes());
    seed.extend_from_slice(format!("{:?}", std::thread::current().id()).as_bytes());

    crate::hash::digest_hex(&seed)
}

/// Establish the token the DAEMON will require: an explicit env pin if present,
/// otherwise a freshly generated random token. Always returns `Some` — the
/// daemon never starts without a token, so `authorize_daemon_request` can be
/// strictly fail-closed.
fn establish_daemon_auth_token() -> String {
    daemon_auth_token_from_env().unwrap_or_else(generate_daemon_auth_token)
}

/// Persist the daemon auth token to its OS-tagged file with owner-only
/// permissions on Unix. The token is written before the daemon starts serving
/// so a client that observes the port file can also read a valid token.
fn write_daemon_token_file_at(control_state_dir: &ControlStateDir, token: &str) -> io::Result<()> {
    let path = daemon_dir_for(control_state_dir)?.join(daemon_token_file_name());

    // On Unix, create the file with 0o600 from the start so the secret is never
    // briefly world-readable between create and chmod.
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        use std::os::unix::fs::PermissionsExt;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&path)
            .map_err(|e| {
                io::Error::new(
                    e.kind(),
                    format!("writing daemon token file at {}: {}", path.display(), e),
                )
            })?;
        file.write_all(token.as_bytes()).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("writing daemon token file at {}: {}", path.display(), e),
            )
        })?;
        // Best-effort re-assert mode in case a restrictive umask still widened it
        // (OpenOptions mode is ANDed with the complement of umask).
        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
        Ok(())
    }

    #[cfg(not(unix))]
    {
        std::fs::write(&path, token.as_bytes()).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("writing daemon token file at {}: {}", path.display(), e),
            )
        })
    }
}

fn env_var_truthy(name: &str) -> bool {
    std::env::var(name)
        .ok()
        .map(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes" | "on"
            )
        })
        .unwrap_or(false)
}

fn is_loopback_bind_host(host: &str) -> bool {
    let trimmed = host.trim().trim_start_matches('[').trim_end_matches(']');
    trimmed.eq_ignore_ascii_case("localhost")
        || trimmed
            .parse::<IpAddr>()
            .map(|ip| ip.is_loopback())
            .unwrap_or(false)
}

fn resolve_daemon_bind_host(default_host: &str) -> anyhow::Result<String> {
    let configured = std::env::var(DAEMON_BIND_ENV).unwrap_or_else(|_| default_host.to_string());
    let host = configured.trim();
    if host.is_empty() {
        anyhow::bail!("{DAEMON_BIND_ENV} must not be empty");
    }

    if is_loopback_bind_host(host) {
        return Ok(host.to_string());
    }

    if env_var_truthy(DAEMON_ALLOW_NON_LOOPBACK_ENV) {
        tracing::warn!(
            bind_host = %host,
            allow_env = DAEMON_ALLOW_NON_LOOPBACK_ENV,
            "daemon binding to a non-loopback interface after explicit operator opt-in"
        );
        Ok(host.to_string())
    } else {
        anyhow::bail!(
            "refusing non-loopback daemon bind '{host}'; set {DAEMON_ALLOW_NON_LOOPBACK_ENV}=1 to allow it explicitly"
        );
    }
}

fn daemon_socket_bind_address(host: &str) -> String {
    let host = host.trim();
    if host.contains(':') && !host.starts_with('[') {
        format!("[{host}]:0")
    } else {
        format!("{host}:0")
    }
}

fn apply_daemon_auth_header(
    request: reqwest::RequestBuilder,
    auth_token: Option<&str>,
) -> reqwest::RequestBuilder {
    if let Some(token) = auth_token {
        request.bearer_auth(token)
    } else {
        request
    }
}

/// Constant-time byte-slice equality.
///
/// Returns `false` on length mismatch and otherwise XOR-folds every byte pair
/// into an accumulator, returning `acc == 0`. There is no early return on the
/// first differing byte, so the running time depends only on the input length,
/// not on the position of the first mismatch. This denies the byte-by-byte
/// timing oracle that `==` on `&[u8]`/`&str` exposes (it short-circuits).
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut acc: u8 = 0;
    for (lhs, rhs) in a.iter().zip(b.iter()) {
        acc |= lhs ^ rhs;
    }
    acc == 0
}

fn authorize_daemon_request(
    state: &SharedDaemonState,
    headers: &HeaderMap,
) -> Result<AuthenticatedActivityGuard, StatusCode> {
    // Fail-closed: the daemon always holds a token (see `DaemonState.auth_token`),
    // so there is no unauthenticated-allow path. A local process that cannot read
    // the 0o600 token file (and has no env pin) can no longer drive the daemon.
    let expected_token = state.auth_token.as_str();

    let Some(header_value) = headers
        .get(header::AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
    else {
        return Err(StatusCode::UNAUTHORIZED);
    };

    let Some((scheme, provided_token)) = header_value.split_once(' ') else {
        return Err(StatusCode::UNAUTHORIZED);
    };

    if !scheme.eq_ignore_ascii_case("bearer") {
        return Err(StatusCode::UNAUTHORIZED);
    }

    // Compare in constant time. We hash BOTH sides to a fixed 32-byte SHA-256
    // digest first so the comparison width is constant regardless of the
    // presented token's length: this leaks neither the real token's length nor
    // the byte position of the first mismatch. A wrong/empty token still 401s,
    // preserving the fail-closed contract.
    let expected_digest = crate::hash::digest(expected_token.as_bytes());
    let provided_digest = crate::hash::digest(provided_token.as_bytes());
    if constant_time_eq(&expected_digest, &provided_digest) {
        // Idle-shutdown signal: only AUTHENTICATED traffic counts as activity,
        // so unauthenticated probes cannot keep a zombie daemon alive.
        state
            .last_activity_at
            .store(now_epoch_millis(), Ordering::Relaxed);
        state
            .active_authenticated_requests
            .fetch_add(1, Ordering::Relaxed);
        Ok(AuthenticatedActivityGuard {
            state: Arc::clone(state),
        })
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}

fn daemon_auth_error(status: StatusCode) -> (StatusCode, String) {
    (status, "daemon authentication required".to_string())
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OpenProjectRequest {
    pub project_root: String,
    pub client_name: String,
    pub pid: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct OpenProjectResponse {
    pub project_id: String,
    pub session_id: String,
    pub project_name: String,
    pub canonical_root: String,
    pub session_count: usize,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CloseSessionResponse {
    pub session_id: String,
    pub project_id: String,
    pub remaining_sessions: usize,
    pub project_removed: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct HeartbeatResponse {
    pub session_id: String,
    pub known_session: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ProjectSummary {
    pub project_id: String,
    pub project_name: String,
    pub canonical_root: String,
    pub session_count: usize,
    pub opened_at_unix_secs: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct SessionSummary {
    pub session_id: String,
    pub project_id: String,
    pub client_name: String,
    pub pid: Option<u32>,
    pub opened_at_unix_secs: u64,
    pub last_seen_at_unix_secs: u64,
    /// Heartbeat older than the stale window, measured when the list was built.
    #[serde(default)]
    pub stale: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ProjectHealth {
    pub project_id: String,
    pub project_name: String,
    pub canonical_root: String,
    pub session_count: usize,
    pub file_count: usize,
    pub symbol_count: usize,
    pub index_state: String,
    #[serde(default = "default_project_freshness")]
    pub freshness: FreshnessStatus,
    pub durability: CapabilityStatus,
    pub capabilities: ProjectCapabilities,
    pub opened_at_unix_secs: u64,
    /// Restored-snapshot verification, rendered like the `status` line, for
    /// example `Snapshot: load_source=snapshot_restore verify=running
    /// phase=reverify processed=512/16572 elapsed=40s`. `None` when the index
    /// was not restored from a snapshot.
    #[serde(default)]
    pub snapshot_verify: Option<String>,
}

fn default_project_freshness() -> FreshnessStatus {
    FreshnessStatus::Current
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct DaemonHealth {
    pub project_count: usize,
    /// Every session the daemon still tracks, heartbeating or stale.
    pub session_count: usize,
    /// Sessions whose heartbeat is older than the stale window, computed when
    /// health is queried. Heartbeating sessions are `session_count -
    /// stale_sessions`; a fresh heartbeat is evidence of life, not a process
    /// check, so a just-killed adapter counts as heartbeating until its
    /// heartbeat ages out.
    #[serde(default)]
    pub stale_sessions: usize,
    pub daemon_version: String,
    pub executable_path: String,
    #[serde(default)]
    pub auth_required: bool,
    #[serde(default)]
    pub pid: Option<u32>,
    /// Daemon boot epoch (unix seconds). Present on 10.1+ daemons; descriptors
    /// record it and selection rejects a descriptor whose epoch differs from
    /// the live daemon's — a stale record can no longer alias an unrelated
    /// `session-N` after a daemon restart (the counter resets per process).
    #[serde(default)]
    pub started_at_unix_secs: Option<u64>,
}

#[derive(Clone)]
struct SessionRuntime {
    canonical_root: PathBuf,
    project_id: String,
    session_id: String,
    index: crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
    token_stats: Arc<TokenStats>,
    /// Cache census (C4c): a clone of the project's symbol-snapshot Arc.
    /// Sole reader is the sidecar handler family behind
    /// `ensure_symbol_cache_generation` — generation-keyed, deterministic
    /// clear on mismatch, unavailability when the generation moved.
    symbol_cache: Arc<RwLock<SymbolSnapshotCache>>,
    /// Session-private, project-keyed `SymForgeServer` clone.
    server: SymForgeServer,
    /// Feature 012 (Phase 3): the session's working set, shared by `Arc` so the
    /// cross-project read route (`search_symbols`/`search_text`/`find_references`
    /// with `project`/`projects`) can read the open projects directly AND lazily
    /// refresh each targeted base when the project's published index has advanced
    /// (B2/D12, `DaemonState::refresh_working_set_bases`, called from
    /// `call_tool_handler` before the read). The single active-project path NEVER
    /// reads or refreshes this (it dispatches to `server` as before), so
    /// single-project behavior is byte-identical and frecency-neutral. No overlay
    /// is written. The active project's id for the targeting contract is
    /// `project_id` above (the default target when neither param is supplied).
    /// Cache census (C4c): same adjudication as `SessionRecord::working_set`
    /// — this is the same `Arc`, re-fenced per read via B2/D12.
    working_set: Arc<RwLock<WorkingSet>>,
    /// Session-scoped project publications used by `search_knowledge`.
    /// Capturing from this map, rather than the daemon-global project table,
    /// makes `projects=["*"]` expand only to projects open in this session.
    project_indexes:
        HashMap<String, crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct DaemonIdentity {
    version: String,
    executable_path: String,
}

impl DaemonState {
    /// Construct daemon state with an always-present auth token: the env pin if
    /// set, otherwise a freshly generated random token. Used by tests and as the
    /// in-process default. The serving path (`spawn_daemon`) instead constructs
    /// via [`DaemonState::with_token`] so the SAME token it persists to the token
    /// file is the one the state enforces.
    pub fn new() -> Self {
        Self::with_token(establish_daemon_auth_token())
    }

    /// The token this daemon enforces — used by the owner-checked shutdown
    /// cleanup to prove a runtime file still belongs to this daemon.
    fn auth_token_for_cleanup(&self) -> String {
        self.auth_token.clone()
    }

    /// Construct daemon state bound to a specific, already-established token.
    fn with_token(auth_token: String) -> Self {
        let control_state_dir = paths::process_control_state_placement()
            .directory()
            .cloned();
        Self::with_token_and_control_state(auth_token, control_state_dir)
    }

    fn with_token_at(auth_token: String, control_state_dir: ControlStateDir) -> Self {
        Self::with_token_and_control_state(auth_token, Some(control_state_dir))
    }

    fn with_token_and_control_state(
        auth_token: String,
        control_state_dir: Option<ControlStateDir>,
    ) -> Self {
        // V11 bootstrap (Feature 020 Slice 4, T030, C4b): the daemon surface
        // runs the process activation ceremony and attaches its capacity
        // owner BEFORE any request can be served through this state.
        live_index::index_lifecycle::activation::activate_surface(
            live_index::index_lifecycle::process_runtime::SurfaceKind::Daemon,
        );
        Self {
            next_session_id: AtomicU64::new(1),
            bases: RwLock::new(HashMap::new()),
            base_generation_seq: AtomicU64::new(1),
            projects: RwLock::new(HashMap::new()),
            cold_load_flights: Mutex::new(HashMap::new()),
            sessions: RwLock::new(HashMap::new()),
            identity: current_daemon_identity(),
            started_at_unix_secs: now_epoch_millis() / 1000,
            auth_token,
            control_state_dir,
            governor: crate::sidecar::governor::RequestGovernor::new(),
            last_activity_at: AtomicU64::new(now_epoch_millis()),
            active_authenticated_requests: AtomicU64::new(0),
            idle_shutdown: tokio::sync::Notify::new(),
        }
    }

    /// Intern `candidate` into the per-daemon base table, enforcing SC-002 (Feature
    /// 012, Phase 0). Returns the SHARED `Arc<IndexBase>` for the candidate's
    /// [`BaseKey`]: the existing allocation when an equal key is already present
    /// (so two consumers at the same `(root, commit)` share ONE base, verified by
    /// `Arc::ptr_eq`), otherwise the candidate re-stamped with a freshly minted
    /// monotonic `base_generation` and published.
    ///
    /// LOCK ORDER: acquires ONLY `bases` (the top of the `bases -> projects ->
    /// sessions` hierarchy) and touches no other daemon lock, so callers remain
    /// free to acquire `projects`/`sessions` afterwards without risking an
    /// inversion. Never call this while holding `projects` or `sessions`.
    fn intern_base(&self, candidate: Arc<IndexBase>) -> Arc<IndexBase> {
        let mut bases = self.bases.write();
        if let Some(existing) = bases.get(&candidate.key) {
            return Arc::clone(existing);
        }
        // Miss: re-stamp with the authoritative monotonic generation, then publish.
        // `IndexBase: Clone` is cheap (it clones the `Arc<LiveIndex>` handle, never
        // the file map), and the candidate is the sole owner here.
        let generation = self.base_generation_seq.fetch_add(1, Ordering::Relaxed);
        let mut published = (*candidate).clone();
        published.base_generation = generation;
        let published = Arc::new(published);
        bases.insert(published.key.clone(), Arc::clone(&published));
        published
    }

    /// FORCE-REPLACE the interned base for `candidate`'s [`BaseKey`] with a
    /// freshly-stamped base wrapping `candidate`'s (current) snapshot — the B2/D12
    /// refresh primitive. Unlike [`DaemonState::intern_base`], it does NOT return
    /// the cached Arc on a key hit: a watcher reindex keeps `BaseKey=(root,commit)`
    /// unchanged (no commit advance), so the plain intern would CACHE-HIT and hand
    /// back the STALE `Arc<LiveIndex>`. This always re-stamps a new monotonic
    /// `base_generation` and overwrites the map VALUE for the key, so SC-002 holds
    /// (exactly ONE `Arc<IndexBase>` per `BaseKey` after the replace — the value is
    /// replaced, never duplicated).
    ///
    /// LOCK ORDER: acquires ONLY `bases` (top of `bases -> projects -> sessions`),
    /// like `intern_base`. Never call while holding `projects`/`sessions`.
    fn intern_base_refresh(&self, candidate: Arc<IndexBase>) -> Arc<IndexBase> {
        let mut bases = self.bases.write();
        let generation = self.base_generation_seq.fetch_add(1, Ordering::Relaxed);
        let mut published = (*candidate).clone();
        published.base_generation = generation;
        let published = Arc::new(published);
        // Overwrite (not insert-if-absent): one Arc per BaseKey is preserved.
        bases.insert(published.key.clone(), Arc::clone(&published));
        published
    }

    /// Intern the base for `project_id` if the project is currently loaded
    /// (Feature 012, Phase 0). Clones the project slot under the registry lock,
    /// then builds and interns the candidate without holding the registry.
    fn intern_base_for_project(&self, project_id: &str) -> Option<Arc<IndexBase>> {
        let slot = self.projects.read().get(project_id).cloned()?;
        Some(self.intern_base(slot.base()))
    }

    /// B2/D12 freshness refresh: lazily re-intern + replace the working-set base
    /// for every TARGETED project whose interned snapshot has gone stale relative
    /// to the project's CURRENT published index, BEFORE a cross-project read.
    ///
    /// THE DEFECT it closes: a working-set entry holds an `Arc<IndexBase>` captured
    /// at open time. The watcher swaps a NEW `Arc<LiveIndex>` into the project's
    /// `ArcSwap` on every observed change, but a watcher edit does NOT change the
    /// git commit, so the `BaseKey=(root,commit)` is unchanged and the interned
    /// base is never refreshed — cross-project reads go stale after any watched
    /// change. This re-captures the current snapshot on the next cross-project read.
    ///
    /// FRESHNESS SIGNAL: `Arc::ptr_eq(&project.index.data_plane().read(), entry.base.index.data_plane())`.
    /// Every publish does `live.store(Arc::new(..))`, so a changed pointer means
    /// the published index advanced. HONEST LIMITATION: this OVER-triggers on
    /// mtime-only touches (`touch_mtime` stores a fresh `Arc<LiveIndex>` without
    /// bumping published state), so a touch that changed no symbols can still cause
    /// one spurious re-intern. That is SAFE — it re-captures an equal-or-fresher
    /// snapshot — and merely mild churn on the rare cross-project read path; it is
    /// NOT an exact signal. (Upgrade path if churn ever matters: compare a
    /// `published_state().generation` stamped into `IndexBase`; not taken now.)
    ///
    /// MISMATCH-GATED: the warm path takes NO write lock. It snapshots the targeted
    /// entries' base pointers under `working_set.read()`, clones the targeted
    /// slots under the registry, and returns early if all are fresh. Only when ≥1
    /// entry is stale does it intern fresh bases and take `working_set.write()`.
    ///
    /// LOCK ORDER (`bases -> projects -> sessions`; `working_set` is outside the
    /// hierarchy, never held across a daemon-map lock): snapshot under
    /// `working_set.read()` -> drop; clone slots under the registry -> drop;
    /// compare through per-slot metadata -> `intern_base_refresh` under
    /// `bases.write()` -> drop; finally `working_set.write()` with NO daemon-map
    /// lock held — the same intern-then-`working_set.add` sequence used elsewhere.
    ///
    /// SC-002 preserved: `intern_base_refresh` REPLACES the map value for the key
    /// (one Arc per `BaseKey`). FRECENCY-NEUTRAL: no edit-commit hook fires on this
    /// read path. `working_set.add` re-attaches a fresh empty overlay fenced to the
    /// new base, so no `StaleOverlay` skip (US1 overlays are empty).
    fn refresh_working_set_bases(&self, working_set: &Arc<RwLock<WorkingSet>>, targets: &Targets) {
        // (1) Snapshot the targeted entries' (project_id, base-index Arc) under the
        // session's own working_set read lock, then DROP it before any daemon lock.
        let targeted: Vec<(String, Arc<LiveIndex>)> = {
            let ws = working_set.read();
            ws.iter()
                .filter(|entry| targets_selects(targets, &entry.project_id))
                .map(|entry| (entry.project_id.clone(), Arc::clone(&entry.base.index)))
                .collect()
        };
        if targeted.is_empty() {
            return;
        }

        // (2) Build fresh candidate bases ONLY for entries whose interned index Arc
        // no longer matches the project's current published index (ptr_eq). Compare
        // after cloning targeted slots under one registry read. The project_id is
        // carried through because a `BaseKey` keys on `(canonical_root, commit)`,
        // NOT the working-set project id.
        let slots: HashMap<String, Arc<ProjectSlot>> = {
            let projects = self.projects.read();
            targeted
                .iter()
                .filter_map(|(project_id, _)| {
                    projects
                        .get(project_id)
                        .cloned()
                        .map(|slot| (project_id.clone(), slot))
                })
                .collect()
        };
        let stale: Vec<(String, Arc<IndexBase>)> = targeted
            .iter()
            .filter_map(|(project_id, entry_index)| {
                let slot = slots.get(project_id)?;
                let index = slot.metadata.read().index.shared();
                // `read()` yields an arc_swap Guard derefing to the current
                // `Arc<LiveIndex>`; `&current` deref-coerces to the
                // `&Arc<LiveIndex>` ptr_eq wants (as `base()` does for clone).
                // Every publish stores a fresh Arc, so an equal pointer means
                // the published index has not advanced since intern.
                let current = index.read();
                if Arc::ptr_eq(&current, entry_index) {
                    None // fresh — no re-intern
                } else {
                    // candidate wrapping the current snapshot
                    Some((project_id.clone(), slot.base()))
                }
            })
            .collect();
        if stale.is_empty() {
            return; // warm path: every targeted entry already fresh, zero writes
        }

        // (3) Force-replace each stale base in the intern table (bases.write each
        // call, dropped before the next), keeping the project_id paired with the
        // fresh shared Arc for the working-set swap.
        let fresh: Vec<(String, Arc<IndexBase>)> = stale
            .into_iter()
            .map(|(project_id, candidate)| (project_id, self.intern_base_refresh(candidate)))
            .collect();

        // (4) Swap each refreshed base into the working set under its own write
        // lock — NO daemon-map lock held here. `add` replaces the entry with a
        // fresh empty overlay re-fenced to the new base (no StaleOverlay skip).
        let mut ws = working_set.write();
        for (project_id, base) in fresh {
            // ponytail: ws.add attaches a fresh EMPTY overlay — correct because
            // overlays are always empty (the session-private overlay writer track
            // was retired 2026-06-29; see docs/superpowers/specs/
            // 2026-06-29-overlay-track-retirement-design.md). If a real overlay
            // writer is ever reintroduced, this must rebase the uncommitted deltas
            // instead, or it silently drops them on every freshness refresh.
            ws.add(project_id, base);
        }
        drop(ws); // release working_set before sweeping the bases table

        // (5) GC orphaned bases. A genuine commit-advance changes BaseKey.commit,
        // so step (3)/(4) interned the snapshot under a NEW key and replaced the
        // working-set entry — the OLD key's value is now referenced only by the
        // map (no session/working-set entry holds it). SC-002-safe eviction: under
        // `bases.write()` (the sole mutator/cloner of the map), `entry.base` is a
        // clone of the SAME map Arc, so the map value's `strong_count == 1` iff no
        // live consumer references it. Retain everything still referenced; drop the
        // orphans. No `Weak<IndexBase>` exists and no other Arc<IndexBase> holder
        // exists, so the count is exact. Commit-advance is ONE orphan source; the
        // other is the last session on a BaseKey closing (swept in close_session).
        // The no-commit watcher path force-replaces the SAME key — no orphan.
        // ponytail: full-map retain is O(bases); fine — table is tiny per daemon.
        // Add a threshold only if base count ever grows large.
        self.gc_orphaned_bases();
    }

    /// Evict orphaned interned bases — values no live consumer references anymore
    /// (the unbounded-growth defect on a long-lived multi-commit daemon).
    ///
    /// SC-002-safe eviction condition: under `bases.write()` (the SOLE mutator and
    /// cloner of the map), every `WorkingSetEntry.base` is a clone of the SAME map
    /// `Arc<IndexBase>`, so a map value's `Arc::strong_count == 1` means the map is
    /// the only owner — no session/working-set holds it. We retain everything still
    /// referenced and drop only `== 1`. No `Weak<IndexBase>` exists and no other
    /// `Arc<IndexBase>` holder exists anywhere, so the count is exact and the sweep
    /// can never evict a base a later `intern_base` would re-share (which would mint
    /// a SECOND Arc per BaseKey — the SC-002 violation this guards against).
    ///
    /// LOCK ORDER: acquires ONLY `bases` (top of `bases -> projects -> sessions`).
    /// Never call while holding `projects`/`sessions`, nor while holding a transient
    /// clone of a map value in the same scope (that would self-inflate the count).
    fn gc_orphaned_bases(&self) {
        self.bases
            .write()
            .retain(|_key, base| Arc::strong_count(base) > 1);
    }

    /// Ensure a live slot for `project_id` and join `session_id` to it, with the
    /// join recorded under the same `projects` write lock that proves the slot is
    /// the map's CURRENT entry. This closes the cleanup/reinsertion race
    /// (recovered finding #15): a slot observed via the read lock may be removed
    /// by a concurrent close before we join it — joining such a zombie (or
    /// re-inserting it) would resurrect a stopped slot. The loop retries against
    /// the authoritative entry instead; a cold load happens OUTSIDE the registry
    /// lock (a racing opener may win insertion; the inactive loser has no
    /// background work and is simply dropped).
    fn ensure_project_slot_for_session(
        &self,
        session_id: &str,
        project_id: &str,
        canonical_root: &Path,
    ) -> anyhow::Result<Arc<ProjectSlot>> {
        let slot = self.ensure_project_slot_for_session_with(session_id, project_id, || {
            ProjectInstance::load_for_session_open(canonical_root)
        })?;
        // Only a plain open retries: `index_folder` reloads inline anyway.
        slot.retry_failed_background_load();
        Ok(slot)
    }

    fn ensure_project_slot_for_binding(
        &self,
        session_id: &str,
        binding: &RootBinding,
    ) -> anyhow::Result<Arc<ProjectSlot>> {
        self.ensure_project_slot_for_session_with(session_id, &binding.root_id.0, || {
            let state_placement = crate::discovery::resolve_state_placement(binding);
            ProjectInstance::load_bound(binding, state_placement)
        })
    }

    fn ensure_project_slot_for_session_with<F>(
        &self,
        session_id: &str,
        project_id: &str,
        load_project: F,
    ) -> anyhow::Result<Arc<ProjectSlot>>
    where
        F: Fn() -> anyhow::Result<ProjectInstance>,
    {
        loop {
            let existing = self.projects.read().get(project_id).cloned();
            if let Some(slot) = existing {
                let projects = self.projects.write();
                if projects
                    .get(project_id)
                    .is_some_and(|current| Arc::ptr_eq(current, &slot))
                {
                    slot.metadata
                        .write()
                        .session_ids
                        .insert(session_id.to_string());
                    return Ok(slot);
                }
                // The map entry changed under us (concurrent cleanup or a fresh
                // reinsert); retry against the current authoritative entry.
                continue;
            }

            let (flight, is_leader) = {
                let mut inflight = self.cold_load_flights.lock();
                match inflight.entry(project_id.to_string()) {
                    std::collections::hash_map::Entry::Occupied(entry) => {
                        (Arc::clone(entry.get()), false)
                    }
                    std::collections::hash_map::Entry::Vacant(entry) => {
                        let flight = Arc::new(ColdLoadFlight::new());
                        entry.insert(Arc::clone(&flight));
                        (flight, true)
                    }
                }
            };

            if is_leader {
                let _leader_guard = ColdLoadLeaderGuard {
                    flight: &flight,
                    inflight: &self.cold_load_flights,
                    project_id: project_id.to_string(),
                };
                let result = (|| -> anyhow::Result<Arc<ProjectSlot>> {
                    let instance = load_project()?;
                    let candidate = Arc::new(ProjectSlot::new(instance));
                    let mut projects = self.projects.write();
                    let slot =
                        Arc::clone(projects.entry(project_id.to_string()).or_insert(candidate));
                    slot.metadata
                        .write()
                        .session_ids
                        .insert(session_id.to_string());
                    Ok(slot)
                })();
                flight.complete(result);
            }

            let _published = flight.wait()?;
            let projects = self.projects.write();
            match projects.get(project_id).cloned() {
                Some(current) => {
                    current
                        .metadata
                        .write()
                        .session_ids
                        .insert(session_id.to_string());
                    return Ok(current);
                }
                None => {
                    return Err(anyhow::anyhow!(
                        "session '{session_id}' closed before the opened project could be attached"
                    ));
                }
            }
        }
    }

    fn register_session_for_existing_project(
        &self,
        project_id: &str,
        request: &OpenProjectRequest,
        canonical_root: &Path,
    ) -> anyhow::Result<OpenProjectResponse> {
        let session_id = format!(
            "session-{}",
            self.next_session_id.fetch_add(1, Ordering::Relaxed)
        );
        let now = SystemTime::now();
        let slot = self.ensure_project_slot_for_session(&session_id, project_id, canonical_root)?;

        // The session id pins the winning slot before activation begins, so close
        // cannot reap it while watcher startup runs outside the registry lock.
        slot.activate();
        let (project_name, canonical_root_text, session_count) = {
            let project = slot.metadata.read();
            (
                project.project_name.clone(),
                normalized_path_string(&project.canonical_root),
                project.session_ids.len(),
            )
        };
        let server = slot.server_for_session();

        // Intern after releasing registry/metadata guards. The session id already
        // pins the slot, so it cannot vanish while git identity is resolved.
        let base = self.intern_base(slot.base());
        let mut working_set = WorkingSet::new();
        working_set.add(project_id.to_string(), base);

        let session = SessionRecord {
            session_id: session_id.clone(),
            active_project_id: project_id.to_string(),
            home_project_id: project_id.to_string(),
            working_set: Arc::new(RwLock::new(working_set)),
            servers: HashMap::from([(project_id.to_string(), server)]),
            client_name: request.client_name.clone(),
            pid: request.pid,
            opened_at: now,
            last_seen_at: AtomicU64::new(now_epoch_millis()),
        };
        self.sessions.write().insert(session_id.clone(), session);

        Ok(OpenProjectResponse {
            project_id: project_id.to_string(),
            session_id,
            project_name,
            canonical_root: canonical_root_text,
            session_count,
        })
    }

    pub fn open_project_session(
        &self,
        request: OpenProjectRequest,
    ) -> anyhow::Result<OpenProjectResponse> {
        // Session-open/reconnect metadata is automatic authority: it may bind a
        // normal client-declared root, but it can never inherit an earlier
        // session's direct protected override. Use the same raw+canonical typed
        // classifier as `index_folder` before looking up or loading a shared slot.
        let binding = match crate::discovery::resolve_root_candidate(
            Path::new(&request.project_root),
            RootCandidateSource::McpClientRoot,
            RootRequestMode::Automatic,
        ) {
            RootResolution::Bound(binding) => binding,
            RootResolution::Unbound {
                reason: UnboundReason::Refused(reason),
                ..
            } => {
                anyhow::bail!(
                    "Refused to open session for sensitive system path: {}. Use a project directory instead. ({})",
                    request.project_root,
                    reason.code()
                );
            }
            RootResolution::Unbound { .. } => {
                anyhow::bail!(
                    "Refused to open session for project root: {}. Use a project directory instead.",
                    request.project_root
                );
            }
        };
        self.register_session_for_existing_project(
            &binding.root_id.0,
            &request,
            &binding.canonical_root,
        )
    }

    pub fn heartbeat(&self, session_id: &str) -> HeartbeatResponse {
        let known_session = self
            .sessions
            .read()
            .get(session_id)
            .map(|session| {
                session
                    .last_seen_at
                    .store(now_epoch_millis(), Ordering::Relaxed);
                true
            })
            .unwrap_or(false);

        HeartbeatResponse {
            session_id: session_id.to_string(),
            known_session,
        }
    }

    pub fn close_session(&self, session_id: &str) -> Option<CloseSessionResponse> {
        // Snapshot session identity, then scan projects in a separate critical
        // section instead of relying on session.project_id, which can be
        // stale if index_folder_for_session reassigned concurrently.
        //
        // Feature 012 (Phase 2): a session may now reference MORE THAN ONE project
        // (the active one plus any additively-opened ones in its working set), so
        // closing it must detach the session from EVERY project that lists it and
        // tear down each whose `session_ids` then empties — not just the first
        // match. Leaving an additively-opened project's `session_ids` pointing at a
        // closed session would leak the project forever. The reported `project_id`
        // / `remaining_sessions` / `project_removed` describe the session's ACTIVE
        // project (its primary association), preserving the wire contract; sibling
        // additive projects are reaped silently.
        // Remove the session record FIRST so a concurrent additive open observes
        // the session as gone and undoes its own attach (recovered finding #16);
        // the membership sweep below then cannot miss a join recorded after the
        // sweep ran. The record — critically its `working_set`, which holds the
        // `Arc<IndexBase>` clones — is dropped BEFORE the GC below, or the bases
        // would never look orphaned.
        let session = self.sessions.write().remove(session_id)?;
        Some(self.finish_removed_session(session))
    }

    /// Shared post-removal cleanup for a session record that has already been
    /// claimed out of the sessions map (interactive close or reaper expiry):
    /// detach the session from EVERY project that lists it, tear down projects
    /// whose membership empties, GC orphaned bases, and report the active
    /// project's outcome.
    fn finish_removed_session(&self, session: SessionRecord) -> CloseSessionResponse {
        let session_id = session.session_id.clone();
        let active_project_id = Some(session.active_project_id.clone());
        let closed_session_id = session.session_id.clone();
        // Drop the record — critically its `working_set`, which holds the
        // `Arc<IndexBase>` clones — BEFORE the GC below, or the bases would
        // never look orphaned.
        drop(session);

        let mut active_remaining = 0usize;
        let mut active_removed = false;
        let mut active_pid_seen = false;
        let mut removed_slots = Vec::new();
        {
            let mut projects = self.projects.write();
            // All projects that list this session (active + additive siblings).
            let owning: Vec<String> = projects
                .iter()
                .filter(|(_, slot)| slot.metadata.read().session_ids.contains(&session_id))
                .map(|(id, _)| id.clone())
                .collect();

            for pid in owning {
                let is_active = active_project_id.as_deref() == Some(pid.as_str());
                let remaining = {
                    let Some(slot) = projects.get(&pid) else {
                        continue;
                    };
                    let mut project = slot.metadata.write();
                    project.session_ids.remove(&session_id);
                    project.session_ids.len()
                };
                let removed = if remaining == 0 {
                    if let Some(removed) = projects.remove(&pid) {
                        removed_slots.push(removed);
                    }
                    true
                } else {
                    false
                };
                if is_active {
                    active_pid_seen = true;
                    active_remaining = remaining;
                    active_removed = removed;
                }
            }
        }
        for slot in removed_slots {
            slot.stop();
        }

        // If this was the last session on a BaseKey, that map value is now a
        // map-only orphan — sweep it. LOCK ORDER safe: `gc_orphaned_bases`
        // takes ONLY `bases.write()`, no other map lock held.
        self.gc_orphaned_bases();

        let project_id = match (active_project_id, active_pid_seen) {
            (Some(pid), true) => pid,
            _ => "orphan".to_string(),
        };

        CloseSessionResponse {
            session_id: closed_session_id,
            project_id,
            remaining_sessions: active_remaining,
            project_removed: active_removed,
        }
    }

    /// Task 9 reaper claim: re-check the SAME last-seen observation under the
    /// sessions write lock and atomically remove the record before any shared
    /// project cleanup. A heartbeat that advanced `last_seen` (or crossed the
    /// cutoff) WINS and preserves the session; once the reaper claims it, a
    /// later heartbeat fails as unknown-session rather than resurrecting it.
    fn close_session_if_expired(
        &self,
        session_id: &str,
        observed_last_seen: u64,
        cutoff: u64,
    ) -> bool {
        let session = {
            let mut sessions = self.sessions.write();
            let Some(record) = sessions.get(session_id) else {
                return false;
            };
            let current = record.last_seen_at.load(Ordering::Relaxed);
            if current != observed_last_seen || current >= cutoff {
                return false;
            }
            sessions.remove(session_id)
        };
        let Some(session) = session else {
            return false;
        };
        let response = self.finish_removed_session(session);
        tracing::info!(
            session_id = %response.session_id,
            project_id = %response.project_id,
            "reaper closed expired session"
        );
        true
    }

    /// Task 9: sweep sessions whose heartbeat is older than `ttl`. Candidates
    /// are collected as `(session_id, observed_last_seen)` under a read lock;
    /// each claim re-validates under the write lock in
    /// `close_session_if_expired`. Returns the number of sessions reaped.
    pub fn reap_expired_sessions(&self, ttl: std::time::Duration) -> usize {
        let cutoff = now_epoch_millis().saturating_sub(ttl.as_millis() as u64);
        let candidates: Vec<(String, u64)> = self
            .sessions
            .read()
            .iter()
            .filter_map(|(id, session)| {
                let seen = session.last_seen_at.load(Ordering::Relaxed);
                (seen < cutoff).then(|| (id.clone(), seen))
            })
            .collect();
        let mut reaped = 0usize;
        for (session_id, observed) in candidates {
            if self.close_session_if_expired(&session_id, observed, cutoff) {
                reaped += 1;
            }
        }
        reaped
    }

    /// Pid rule: close sessions whose heartbeat is older than `stale_after`
    /// AND whose recorded pid no longer names a running process. The adapter
    /// closes its own session on a clean exit; a hard kill, crash, or update
    /// swap never does, and its ProjectSlot (watcher, index) would otherwise
    /// live until the TTL. Only already-stale sessions are probed, and the
    /// probe runs outside every lock; the claim re-checks `last_seen_at` under
    /// the write lock, so a late heartbeat wins. A live pid keeps its session
    /// (the TTL rule remains the backstop for pid reuse and pid-less clients).
    ///
    /// Accepted residual: a dead adapter whose pid the OS has recycled looks
    /// alive here and keeps its session until the TTL, and health cannot tell
    /// it from a suspended adapter. Better design, as a follow-up: hold a
    /// SYNCHRONIZE handle (Windows) or a pidfd (Linux, `pidfd_open`) in the
    /// `SessionRecord`, so the pid cannot be recycled and liveness is definite.
    pub fn reap_dead_pid_sessions(&self, stale_after: std::time::Duration) -> usize {
        let cutoff = now_epoch_millis().saturating_sub(stale_after.as_millis() as u64);
        let candidates: Vec<(String, u64, u32)> = self
            .sessions
            .read()
            .iter()
            .filter_map(|(id, session)| {
                let seen = session.last_seen_at.load(Ordering::Relaxed);
                let pid = session.pid?;
                (seen < cutoff).then(|| (id.clone(), seen, pid))
            })
            .collect();
        let mut reaped = 0usize;
        for (session_id, observed, pid) in candidates {
            if !crate::sidecar::port_file::process_may_be_alive(pid)
                && self.close_session_if_expired(&session_id, observed, cutoff)
            {
                reaped += 1;
            }
        }
        reaped
    }

    pub fn list_projects(&self) -> Vec<ProjectSummary> {
        let slots: Vec<Arc<ProjectSlot>> = self.projects.read().values().cloned().collect();
        let mut summaries: Vec<ProjectSummary> = slots
            .iter()
            .map(|slot| {
                let project = slot.metadata.read();
                ProjectSummary {
                    project_id: project.project_id.clone(),
                    project_name: project.project_name.clone(),
                    canonical_root: normalized_path_string(&project.canonical_root),
                    session_count: project.session_ids.len(),
                    opened_at_unix_secs: unix_seconds(project.opened_at),
                }
            })
            .collect();
        summaries.sort_by(|a, b| a.canonical_root.cmp(&b.canonical_root));
        summaries
    }

    pub fn project_health(&self, project_id: &str) -> Option<ProjectHealth> {
        let slot = self.projects.read().get(project_id).cloned()?;
        let project = slot.metadata.read();
        // T046: one capture — the freshness verdict below describes the SAME
        // publication as the counts it is printed beside, not one from a
        // separate load 50 lines later.
        let generation = project.index.data_plane().published_generation();
        let published = std::sync::Arc::clone(&generation.health);
        let durability = *project.persistence_health.read();
        let durable_mutation = match durability {
            CapabilityStatus::Available => CapabilityStatus::Available,
            CapabilityStatus::Unavailable { .. } => CapabilityStatus::Unavailable {
                reason:
                    crate::domain::CapabilityUnavailableReason::DurableMutationReplayUnavailable,
            },
        };
        let protected = project.source_access_mode == SourceAccessMode::ExplicitProtected;
        let source_mutation = if protected {
            CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::ExplicitProtectedSource,
            }
        } else {
            durable_mutation
        };
        let repository_init = if protected {
            CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::ExplicitProtectedSource,
            }
        } else {
            CapabilityStatus::Available
        };
        let team_artifact_export = if protected {
            CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::ExplicitProtectedSource,
            }
        } else if matches!(
            &project.state_placement,
            StatePlacement::ProjectLocal { .. }
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::NonProjectLocalPlacement,
            }
        };
        let repository_curation = project.curation_coordinator.capability_status(
            project.index.data_plane(),
            Some(&project.canonical_root),
            Some(&project.state_placement),
            durability,
        );

        Some(ProjectHealth {
            project_id: project.project_id.clone(),
            project_name: project.project_name.clone(),
            canonical_root: normalized_path_string(&project.canonical_root),
            session_count: project.session_ids.len(),
            file_count: published.file_count,
            symbol_count: published.symbol_count,
            index_state: published.status_label().to_string(),
            freshness: generation.freshness.as_ref().clone(),
            durability,
            capabilities: ProjectCapabilities {
                persistent_snapshots: durability,
                checkpoint: durability,
                structural_edits: source_mutation,
                repository_init,
                repository_curation,
                team_artifact_export,
            },
            opened_at_unix_secs: unix_seconds(project.opened_at),
            snapshot_verify: crate::protocol::format::snapshot_verify_status_line(
                published.load_source,
                &published.snapshot_verify_state,
            ),
        })
    }

    pub fn list_sessions(&self, project_id: &str) -> Option<Vec<SessionSummary>> {
        let session_ids: Vec<String> = {
            let slot = self.projects.read().get(project_id).cloned()?;
            let project = slot.metadata.read();
            project.session_ids.iter().cloned().collect()
        };

        let sessions = self.sessions.read();
        let now = now_epoch_millis();
        let mut summaries: Vec<SessionSummary> = session_ids
            .iter()
            .filter_map(|session_id| sessions.get(session_id))
            .map(|session| SessionSummary {
                session_id: session.session_id.clone(),
                project_id: session.active_project_id.clone(),
                client_name: session.client_name.clone(),
                pid: session.pid,
                opened_at_unix_secs: unix_seconds(session.opened_at),
                last_seen_at_unix_secs: unix_seconds(session.last_seen_at_time()),
                stale: session.is_stale(now),
            })
            .collect();
        summaries.sort_by(|a, b| a.session_id.cmp(&b.session_id));
        Some(summaries)
    }

    fn index_folder_for_session(
        &self,
        session_id: &str,
        input: IndexFolderInput,
    ) -> anyhow::Result<String> {
        let allow_protected_root = input.allow_protected_root == Some(true);
        let binding = match crate::discovery::resolve_root_candidate(
            Path::new(&input.path),
            RootCandidateSource::ExplicitIndexFolder,
            RootRequestMode::ExplicitIndexFolder {
                allow_protected_root,
            },
        ) {
            RootResolution::Bound(binding) => binding,
            RootResolution::Unbound {
                reason: UnboundReason::Refused(reason),
                ..
            } => {
                return Ok(format!(
                    "{}: Refused to index sensitive system path: {}. Use a project directory instead.",
                    reason.code(),
                    input.path
                ));
            }
            RootResolution::Unbound { .. } => {
                return Ok(format!(
                    "root_unbound: Refused to index project root: {}.",
                    input.path
                ));
            }
        };
        let target_root = &binding.canonical_root;

        // Per-session activation (locked contract): the omitted-`add` default
        // opens/refreshes `target_root` AND makes it the session's ACTIVE
        // project for unqualified reads. The compatibility spelling
        // `add=true` opens additively WITHOUT changing the active project.
        // Home — the session/descriptor identity verified across reconnects —
        // is immutable; only `active_project_id` moves, and only for THIS
        // session (no cross-session interference). The working set retains
        // every open project, so activation is non-destructive.
        //
        // The `add` spelling changes side effects (activation), so it IS part
        // of the canonical idempotency request (hashed as `activate`).
        //
        // Cross-project replay is process coordination, not state owned by the
        // session's home repository. The one resolved ControlStateDir therefore
        // observes every open before any target ProjectInstance is constructed.
        let reset_requested = crate::protocol::tools::index_folder_reset_requested();
        let activate = input.add != Some(true);
        let (idempotency, replay_response) = match input.idempotency_key.as_deref() {
            Some(raw_key) => {
                let Some(control_state) = self.control_state_dir.as_ref() else {
                    return Ok(
                        "Idempotency unavailable: durable process control state is unavailable."
                            .to_string(),
                    );
                };
                match crate::idempotency::begin_index_folder_replay(
                    control_state,
                    target_root,
                    raw_key,
                    reset_requested,
                    allow_protected_root,
                    activate,
                ) {
                    Ok(crate::idempotency::ReplayStart::FirstExecution(active)) => {
                        (Some(active), None)
                    }
                    Ok(crate::idempotency::ReplayStart::Replay(response)) => (None, Some(response)),
                    Err(error) => return Ok(crate::idempotency::format_tool_error(&error)),
                }
            }
            None => (None, None),
        };

        match self.open_project_for_session(session_id, &binding) {
            Ok(mut output) => {
                if activate && self.set_active_project(session_id, &binding.root_id.0) {
                    output.push_str(&format!(
                        "active_project={} (default index_folder: unqualified reads on this session now target this project)\n",
                        binding.root_id.0
                    ));
                }
                if let Some(response) = replay_response {
                    return Ok(response);
                }
                if let Some(idempotency) = &idempotency
                    && let Err(error) = idempotency.complete(output.clone())
                {
                    output.push_str(&format!(
                        "\nIdempotency warning: failed to store replay result: {error}"
                    ));
                }
                Ok(output)
            }
            Err(error) => {
                if let Some(response) = replay_response {
                    return Ok(crate::idempotency::format_live_postcondition_unavailable(
                        &response, &error,
                    ));
                }
                if let Some(idempotency) = &idempotency {
                    let _ = idempotency.fail(format!("Index failed: {error}"));
                }
                Err(error)
            }
        }
    }

    /// The ONE canonical daemon open path behind `index_folder`: opens/refreshes
    /// `target_root` as a working-set project WITHOUT touching
    /// `active_project_id` — the caller (`index_folder_for_session`) owns
    /// per-session activation (default spelling activates; `add=true` does not).
    ///
    /// Steps:
    /// 1. ensure + join the authoritative project slot — session membership is
    ///    recorded under the same `projects` write lock that proves the slot is
    ///    the map's current entry, so concurrent cleanup cannot remove the slot
    ///    and orphan the join;
    /// 2. activate and reload through the slot's mutation lane (same-project
    ///    reads keep serving the previously published generation);
    /// 3. persist the successfully published generation as an atomic snapshot —
    ///    a snapshot failure does NOT roll back the in-memory open, it degrades
    ///    the checkpoint receipt and leaves any prior valid snapshot in place;
    /// 4. attach the project to the session working set with a freshly interned
    ///    base (fresh EMPTY overlay — the no-overlay-writes invariant holds).
    ///
    /// LOCK ORDER (`bases -> projects -> sessions`) is preserved: the reload and
    /// checkpoint run with no registry lock held; the attach helper interns the
    /// base first, then takes `projects`/`sessions` without overlap.
    fn open_project_for_session(
        &self,
        session_id: &str,
        binding: &RootBinding,
    ) -> anyhow::Result<String> {
        let target_project_id = &binding.root_id.0;
        let target_root = &binding.canonical_root;
        let target_slot = self.ensure_project_slot_for_binding(session_id, binding)?;
        target_slot.activate();
        let (file_count, symbol_count) = target_slot.reload_for_binding(binding)?;

        let (index, source_access_mode, state_placement, persistence_health) = {
            let project = target_slot.metadata.read();
            (
                project.index.shared(),
                project.source_access_mode,
                project.state_placement.clone(),
                Arc::clone(&project.persistence_health),
            )
        };
        let gitignore_hygiene = crate::gitignore_hygiene::reconcile_project_gitignore(
            target_root,
            if source_access_mode == SourceAccessMode::ExplicitProtected {
                crate::gitignore_hygiene::GitignoreHygieneAuthority::ExplicitProtected
            } else {
                crate::gitignore_hygiene::GitignoreHygieneAuthority::ExplicitNormalBinding
            },
        );
        let (checkpoint, state_location) = match &state_placement {
            StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. } => (
                match crate::live_index::persist::checkpoint_shared_index(
                    &index,
                    target_root,
                    &state_placement,
                ) {
                    Ok(_) => {
                        *persistence_health.write() = CapabilityStatus::Available;
                        "checkpoint=written".to_string()
                    }
                    Err(error) => {
                        *persistence_health.write() = CapabilityStatus::Unavailable {
                            reason: crate::domain::CapabilityUnavailableReason::PersistentStateUnavailable,
                        };
                        format!("checkpoint=degraded: {error}")
                    }
                },
                if matches!(&state_placement, StatePlacement::ProjectLocal { .. }) {
                    "project-local"
                } else {
                    "user-local"
                },
            ),
            StatePlacement::MemoryOnly { .. } => {
                ("checkpoint=skipped(memory-only)".to_string(), "memory-only")
            }
        };

        if !self.add_project_to_session(session_id, target_project_id) {
            return Err(anyhow::anyhow!(
                "session '{session_id}' closed before the opened project could be attached"
            ));
        }

        let (project_name, root_text) = {
            let project = target_slot.metadata.read();
            (
                project.project_name.clone(),
                normalized_path_string(&project.canonical_root),
            )
        };
        Ok(format!(
            "Indexed {file_count} files, {symbol_count} symbols (added to working set).\nproject_id={target_project_id} project_name={project_name} root={root_text} source_access={source_access_mode:?} state={state_location} {checkpoint}\n{}",
            gitignore_hygiene.receipt()
        ))
    }

    /// Feature 012 (Phase 2): add an already-loaded project to a session's working
    /// set as an additional, non-active project. Returns `false` if the session or
    /// the project is unknown. The base is interned FIRST (no session lock held)
    /// to preserve the `bases -> projects -> sessions` order; a fresh EMPTY overlay
    /// is attached (no overlay write). Idempotent: re-adding refreshes the entry.
    ///
    /// Two lifecycle hardenings (recovered findings #14/#16):
    /// - a session-local server whose `SharedIndex` no longer matches the slot's
    ///   current index (the project was evicted and re-loaded since) is REPLACED,
    ///   never reused — a stale server would silently serve a dead index;
    /// - if the session closed while the attach was in flight, the membership
    ///   join is undone (and the slot reaped if that was its last session), so a
    ///   closed session cannot pin a project forever.
    fn add_project_to_session(&self, session_id: &str, project_id: &str) -> bool {
        let Some(base) = self.intern_base_for_project(project_id) else {
            return false;
        };
        let slot = {
            let projects = self.projects.read();
            let Some(slot) = projects.get(project_id) else {
                return false;
            };
            Arc::clone(slot)
        };
        let server = slot.server_for_session();
        let slot_index = slot.metadata.read().index.shared();
        slot.metadata
            .write()
            .session_ids
            .insert(session_id.to_string());
        let attached = match self.sessions.write().get_mut(session_id) {
            Some(session) => {
                let replace_server = session
                    .servers
                    .get(project_id)
                    .map(|existing| !Arc::ptr_eq(existing.index.data_plane(), &slot_index))
                    .unwrap_or(true);
                if replace_server {
                    session.servers.insert(project_id.to_string(), server);
                }
                session
                    .working_set
                    .write()
                    .add(project_id.to_string(), base);
                true
            }
            None => false,
        };
        if !attached {
            self.detach_project_membership(session_id, project_id);
        }
        attached
    }

    /// Remove `session_id` from `project_id`'s membership set, reaping the slot
    /// when that membership was its last. Used to undo an attach that raced a
    /// session close (recovered finding #16); safe to call when either side is
    /// already gone.
    fn detach_project_membership(&self, session_id: &str, project_id: &str) {
        let removed = {
            let mut projects = self.projects.write();
            let Some(slot) = projects.get(project_id).cloned() else {
                return;
            };
            let mut project = slot.metadata.write();
            project.session_ids.remove(session_id);
            let empty = project.session_ids.is_empty();
            drop(project);
            if empty {
                projects.remove(project_id)
            } else {
                None
            }
        };
        if let Some(slot) = removed {
            slot.stop();
        }
    }

    /// Feature 012 (Phase 2): set the session's ACTIVE project to one already in
    /// its working set. Returns `false` if the session is unknown or `project_id`
    /// is not an open working-set entry (cannot activate a project that is not
    /// open). Only flips `active_project_id`; the working set is untouched (the
    /// target entry already exists). No overlay is written.
    ///
    /// Production caller: `index_folder_for_session` activates on the default
    /// (non-`add`) spelling, after the open has attached the project.
    fn set_active_project(&self, session_id: &str, project_id: &str) -> bool {
        match self.sessions.write().get_mut(session_id) {
            Some(session) => {
                let is_open = session.working_set.read().get(project_id).is_some();
                if !is_open {
                    return false;
                }
                session.active_project_id = project_id.to_string();
                session
                    .last_seen_at
                    .store(now_epoch_millis(), Ordering::Relaxed);
                true
            }
            None => false,
        }
    }

    /// Feature 012 (Phase 2): remove a project from a session's working set.
    /// Refuses (returns `false`) to remove the ACTIVE project — the active slot
    /// always resolves to a live working-set entry — or when the session/entry is
    /// unknown. Also drops the session from the project's `session_ids` (and tears
    /// the project down if that was its last session, matching retarget eviction).
    //
    // ponytail: companion seam to `set_active_project`; same DEFERRED working-set
    // management tool owns its route. Tested in the daemon module; allow dead_code
    // until the tool wires it.
    #[allow(dead_code)]
    fn remove_project_from_session(&self, session_id: &str, project_id: &str) -> bool {
        // First detach from the working set, refusing the active project.
        let removed = match self.sessions.write().get_mut(session_id) {
            Some(session) => {
                if session.active_project_id == project_id {
                    return false;
                }
                let mut working_set = session.working_set.write();
                let removed = working_set.remove(project_id).is_some();
                drop(working_set);
                if removed {
                    session.servers.remove(project_id);
                }
                removed
            }
            None => false,
        };
        if !removed {
            return false;
        }
        // Detach the session from the project; tear the project down if this was
        // its last session (mirrors the retarget eviction in
        // `index_folder_for_session`).
        let evicted = {
            let mut projects = self.projects.write();
            let Some(slot) = projects.get(project_id).cloned() else {
                return true;
            };
            let mut project = slot.metadata.write();
            project.session_ids.remove(session_id);
            let empty = project.session_ids.is_empty();
            drop(project);
            if empty {
                projects.remove(project_id)
            } else {
                None
            }
        };
        if let Some(slot) = evicted {
            slot.stop();
        }
        true
    }

    fn session_runtime(&self, session_id: &str) -> Option<SessionRuntime> {
        self.runtime_for_target(session_id, None).ok()
    }

    /// Task 4 (outstanding-work hardening): the ONE shared resolver from a
    /// session plus an optional explicit `project` selector to the bound
    /// per-project runtime. Omission selects the session's ACTIVE project
    /// (home unless a default `index_folder` activated another working-set
    /// project). An explicit selector resolves an open project ID first, then
    /// a UNIQUE current `project_name` among the session's OPEN working-set
    /// projects — display text, not a persistent alias. Unknown/not-open/
    /// ambiguous selectors return deterministic candidate data and never
    /// trigger indexing or frecency.
    fn runtime_for_target(
        &self,
        session_id: &str,
        project: Option<&str>,
    ) -> Result<SessionRuntime, String> {
        // Clone the session and project slot in separate short critical
        // sections; no daemon-map locks overlap.
        let session = self
            .sessions
            .read()
            .get(session_id)
            .cloned()
            .ok_or_else(|| format!("unknown session '{session_id}'"))?;

        let target_id = match project.filter(|p| !p.trim().is_empty()) {
            None => session.active_project_id.clone(),
            Some(selector) => {
                let open_ids: Vec<String> = session
                    .working_set
                    .read()
                    .iter()
                    .map(|entry| entry.project_id.clone())
                    .collect();
                if open_ids.iter().any(|id| id == selector) {
                    selector.to_string()
                } else {
                    let mut matches: Vec<String> = Vec::new();
                    let mut candidates: Vec<String> = Vec::new();
                    {
                        let projects = self.projects.read();
                        for id in &open_ids {
                            if let Some(slot) = projects.get(id) {
                                let meta = slot.metadata.read();
                                candidates.push(format!("{} ({id})", meta.project_name));
                                if meta.project_name == selector {
                                    matches.push(id.clone());
                                }
                            }
                        }
                    }
                    candidates.sort();
                    match matches.len() {
                        1 => matches.remove(0),
                        0 => {
                            return Err(format!(
                                "project '{selector}' is not open in this session. Open \
                                 projects: [{}]. Open it first with index_folder(path=...).",
                                candidates.join(", ")
                            ));
                        }
                        _ => {
                            return Err(format!(
                                "project selector '{selector}' is ambiguous among open \
                                 projects: [{}]. Use the project id.",
                                candidates.join(", ")
                            ));
                        }
                    }
                }
            }
        };

        let slot = self
            .projects
            .read()
            .get(&target_id)
            .cloned()
            .ok_or_else(|| format!("project '{target_id}' is not loaded in the daemon"))?;
        let server = session.servers.get(&target_id).cloned().ok_or_else(|| {
            format!(
                "project '{target_id}' has no session server; reopen it with \
                 index_folder(path=...)"
            )
        })?;
        let project_meta = slot.metadata.read();
        // C4c typed acquisition: dispatch requires the project's admission
        // slot to still be the live occupancy of its key. A project the
        // eviction/retarget stop path retired refuses here — between the stop
        // and the map sweep, the maps can still resolve it, and without this
        // branch the neck would serve a retired index.
        if let Err(refusal) = project_meta.index.acquire() {
            return Err(format!(
                "project '{target_id}' has been retired from the process registry \
                 ({refusal:?}); reopen it with index_folder(path=...)"
            ));
        }
        let project_indexes = session
            .servers
            .iter()
            .map(|(id, server)| (id.clone(), server.index.clone()))
            .collect();
        Ok(SessionRuntime {
            canonical_root: project_meta.canonical_root.clone(),
            project_id: target_id.clone(),
            session_id: session.session_id.clone(),
            index: project_meta.index.clone(),
            token_stats: Arc::clone(&project_meta.token_stats),
            symbol_cache: Arc::clone(&project_meta.symbol_cache),
            server,
            working_set: Arc::clone(&session.working_set),
            project_indexes,
        })
    }

    /// Task 7: render the session's open-project inventory — one row per open
    /// project with deterministic ID, display name/root, home marker, published
    /// counts and index state, current generation, opened timestamp, and
    /// snapshot presence — plus the session's last-seen evidence. `project_name`
    /// is display text, never a persistent alias. Returns `None` for an unknown
    /// session.
    fn render_session_project_inventory(&self, session_id: &str) -> Option<String> {
        let session = self.sessions.read().get(session_id).cloned()?;
        let open_ids: Vec<String> = session
            .working_set
            .read()
            .iter()
            .map(|entry| entry.project_id.clone())
            .collect();
        let mut lines = vec!["── projects ──".to_string()];
        {
            let projects = self.projects.read();
            for id in &open_ids {
                let Some(slot) = projects.get(id) else {
                    lines.push(format!(
                        "{id} state=missing (open in working set but not loaded)"
                    ));
                    continue;
                };
                let meta = slot.metadata.read();
                let published = meta.index.data_plane().published_state();
                // Home and active are DISTINCT identities since the
                // worktree-routing fix: home is the immutable session
                // identity; active is what unqualified reads serve.
                let home = if *id == session.home_project_id {
                    " home=yes"
                } else {
                    ""
                };
                let active = if *id == session.active_project_id {
                    " active=yes"
                } else {
                    ""
                };
                let snapshot = if meta
                    .canonical_root
                    .join(".symforge")
                    .join("index.bin")
                    .is_file()
                {
                    "present"
                } else {
                    "absent"
                };
                lines.push(format!(
                    "{id}{home}{active} name={} root={} files={} symbols={} index={} generation={} opened={} snapshot={}",
                    meta.project_name,
                    normalized_path_string(&meta.canonical_root),
                    published.file_count,
                    published.symbol_count,
                    published.status_label(),
                    meta.index.data_plane().current_project_generation(),
                    unix_seconds(meta.opened_at),
                    snapshot,
                ));
            }
        }
        let (live, stale) = self.session_liveness();
        lines.push(format!(
            "daemon sessions: {live} heartbeating, {stale} stale (heartbeat > {} s)",
            STALE_SESSION_HEARTBEAT.as_secs()
        ));
        lines.push(format!(
            "session={} last_seen={} ttl_secs={}",
            session.session_id,
            unix_seconds(session.last_seen_at_time()),
            session_ttl_from_env().as_secs()
        ));
        Some(lines.join("\n"))
    }

    /// The inventory above, but only when the session holds MORE than one open
    /// project — the append-to-`health` path stays byte-compatible for the
    /// single-project sessions that existed before multi-project opens.
    fn render_session_project_inventory_if_multi(&self, session_id: &str) -> Option<String> {
        let multi = {
            let sessions = self.sessions.read();
            let session = sessions.get(session_id)?;
            session.working_set.read().len() > 1
        };
        if multi {
            self.render_session_project_inventory(session_id)
        } else {
            None
        }
    }

    /// `(heartbeating, stale)` session counts, daemon-wide, judged by
    /// heartbeat age at call time.
    fn session_liveness(&self) -> (usize, usize) {
        let now = now_epoch_millis();
        let sessions = self.sessions.read();
        let stale = sessions.values().filter(|s| s.is_stale(now)).count();
        (sessions.len() - stale, stale)
    }

    pub fn health(&self) -> DaemonHealth {
        let (live, stale) = self.session_liveness();
        DaemonHealth {
            project_count: self.projects.read().len(),
            session_count: live + stale,
            stale_sessions: stale,
            daemon_version: self.identity.version.clone(),
            executable_path: self.identity.executable_path.clone(),
            // Always true now: the daemon is fail-closed and always requires a
            // token. The field is retained for wire compatibility and so clients
            // can surface that authentication is in force.
            auth_required: true,
            pid: Some(std::process::id()),
            started_at_unix_secs: Some(self.started_at_unix_secs),
        }
    }
}

impl Default for DaemonState {
    fn default() -> Self {
        Self::new()
    }
}

impl DaemonSessionClient {
    fn new_with_auth_token(
        base_url: String,
        project_id: String,
        session_id: String,
        project_name: String,
        auth_token: Option<String>,
        control_state_dir: ControlStateDir,
    ) -> Self {
        // CRITICAL: reqwest::Client::new() has NO timeout by default.
        // Under concurrent load, if the daemon is slow, HTTP requests hang
        // indefinitely while holding read locks on daemon_lock in the proxy
        // layer. This creates a deadlock-like scenario when a reconnect
        // attempt needs a write lock but reads never release.
        //
        // 5s connect + 60s total covers heavy ops (batch_edit on large repos)
        // while ensuring stuck requests eventually fail and release locks.
        let http_client = reqwest::Client::builder()
            .connect_timeout(std::time::Duration::from_secs(5))
            .timeout(std::time::Duration::from_secs(60))
            .build()
            .expect("failed to build reqwest client with timeout — this is a critical invariant");

        Self {
            http_client,
            base_url,
            project_id,
            session_id,
            project_name,
            auth_token,
            control_state_dir,
            project_root: None,
            opened_roots: std::sync::Arc::new(parking_lot::Mutex::new(Vec::new())),
            active_root: std::sync::Arc::new(parking_lot::Mutex::new(None)),
            activation_lane: std::sync::Arc::new(tokio::sync::Mutex::new(())),
            daemon_started_at: None,
        }
    }

    fn with_project_root(mut self, root: PathBuf) -> Self {
        self.project_root = Some(root);
        self
    }

    fn with_daemon_started_at(mut self, started_at: Option<u64>) -> Self {
        self.daemon_started_at = started_at;
        self
    }

    /// The connected daemon's boot epoch, when known (10.1+ daemons).
    pub fn daemon_started_at(&self) -> Option<u64> {
        self.daemon_started_at
    }

    /// Task 8: remember a sibling root this connection opened additively so
    /// a reconnect can restore the full working set. Home is never recorded
    /// here (it lives in the immutable `project_root`). Deduplicated, order
    /// preserved.
    pub(crate) fn record_opened_root(&self, root: PathBuf) {
        if self.project_root.as_deref() == Some(root.as_path()) {
            return;
        }
        let mut roots = self.opened_roots.lock();
        if !roots.iter().any(|existing| existing == &root) {
            roots.push(root);
        }
    }

    /// Locked contract: record the root a default (non-`add`) `index_folder`
    /// just ACTIVATED for this connection, so `reconnect` can restore the
    /// active project after re-opening the working set. Recording `None`
    /// means home is active again.
    pub(crate) fn record_active_root(&self, root: PathBuf) {
        *self.active_root.lock() = Some(root);
    }

    /// One connection-scoped lane for an `index_folder` daemon round trip and
    /// the adapter mirror update that follows its successful response.
    pub(crate) fn activation_lane(&self) -> std::sync::Arc<tokio::sync::Mutex<()>> {
        std::sync::Arc::clone(&self.activation_lane)
    }

    /// The root currently ACTIVE for unqualified reads on this connection
    /// (set by a default `index_folder`), or `None` when home is active.
    pub(crate) fn activated_root(&self) -> Option<PathBuf> {
        self.active_root.lock().clone()
    }

    /// Resolve one session-scoped project selector to the canonical root that
    /// this client has already opened. Resolution mirrors the daemon contract:
    /// omission selects ACTIVE, explicit project IDs win over display names,
    /// and a display name is accepted only when it is unique in the working
    /// set. Unknown or ambiguous selectors return `None`; the daemon remains
    /// the authority that renders the eventual routing refusal.
    pub(crate) fn opened_project_for_selector(
        &self,
        selector: Option<&str>,
    ) -> Option<(String, PathBuf, bool)> {
        let active = self.active_root.lock().clone();
        let home = self.project_root.clone();
        let mut projects: Vec<(String, String, PathBuf)> = Vec::new();
        if let Some(root) = home {
            projects.push((self.project_id.clone(), self.project_name.clone(), root));
        }
        for root in self.opened_roots.lock().iter() {
            let id = project_key(root);
            if !projects.iter().any(|(existing, _, _)| existing == &id) {
                let name = root
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or_default()
                    .to_string();
                projects.push((id, name, root.clone()));
            }
        }
        if let Some(root) = active {
            let id = project_key(&root);
            if !projects.iter().any(|(existing, _, _)| existing == &id) {
                let name = root
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or_default()
                    .to_string();
                projects.push((id, name, root));
            }
        }

        let selector = selector.filter(|value| !value.trim().is_empty());
        if selector.is_none() {
            let active_id = self.active_project_id();
            return projects
                .into_iter()
                .find(|(id, _, _)| id == &active_id)
                .map(|(id, _, root)| {
                    let is_home = id == self.project_id;
                    (id, root, is_home)
                });
        }
        let selector = selector.expect("non-empty selector established above");
        if let Some((id, _, root)) = projects.iter().find(|(id, _, _)| id == selector) {
            return Some((id.clone(), root.clone(), id == &self.project_id));
        }

        let mut name_matches = projects.into_iter().filter(|(_, name, _)| name == selector);
        let matched = name_matches.next()?;
        name_matches.next().is_none().then(|| {
            let is_home = matched.0 == self.project_id;
            (matched.0, matched.2, is_home)
        })
    }

    /// The exact project ID targeted by an omitted selector on this session.
    pub(crate) fn active_project_id(&self) -> String {
        self.active_root
            .lock()
            .as_deref()
            .map(project_key)
            .unwrap_or_else(|| self.project_id.clone())
    }

    /// Local fallback is valid only while the daemon session still targets the
    /// immutable adapter HOME project.
    pub(crate) fn active_project_is_home(&self) -> bool {
        self.active_project_id() == self.project_id
    }

    #[cfg(test)]
    pub(crate) fn new_for_test(
        base_url: String,
        project_id: String,
        session_id: String,
        project_name: String,
    ) -> Self {
        let control_state_dir = process_control_state_dir()
            .expect("test daemon control state must be resolvable")
            .clone();
        Self::new_for_test_at(
            base_url,
            project_id,
            session_id,
            project_name,
            control_state_dir,
        )
    }

    #[cfg(test)]
    pub(crate) fn new_for_test_at(
        base_url: String,
        project_id: String,
        session_id: String,
        project_name: String,
        control_state_dir: ControlStateDir,
    ) -> Self {
        // The daemon is fail-closed; a proxy client must carry the token. Resolve
        // it the same way production does (env pin, then the persisted token
        // file) so test proxies authenticate against a spawned daemon.
        let auth_token = resolve_daemon_auth_token_at(&control_state_dir);
        Self::new_with_auth_token(
            base_url,
            project_id,
            session_id,
            project_name,
            auth_token,
            control_state_dir,
        )
    }

    pub fn project_name(&self) -> &str {
        &self.project_name
    }

    pub fn project_id(&self) -> &str {
        &self.project_id
    }

    pub fn session_id(&self) -> &str {
        &self.session_id
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    pub fn project_root(&self) -> Option<&Path> {
        self.project_root.as_deref()
    }

    pub(crate) fn control_state_dir(&self) -> &ControlStateDir {
        &self.control_state_dir
    }

    pub fn port(&self) -> Option<u16> {
        self.base_url
            .rsplit(':')
            .next()
            .and_then(|value| value.parse::<u16>().ok())
    }

    /// Attempt to reconnect to the daemon after a connection failure.
    ///
    /// Calls `ensure_daemon_running` (which will spawn a new daemon if needed),
    /// opens a fresh session, and returns the new client. The caller should
    /// replace their stored client with the returned one.
    pub async fn reconnect(&self) -> anyhow::Result<DaemonSessionClient> {
        let project_root = self
            .project_root
            .as_deref()
            .context("cannot reconnect: no project root stored")?;
        tracing::info!(
            "attempting daemon reconnection for project {}",
            self.project_name
        );
        let new_client = connect_or_spawn_session_at(
            project_root,
            "mcp-stdio",
            Some(std::process::id()),
            &self.control_state_dir,
        )
        .await?;
        let mut new_client = new_client.with_project_root(project_root.to_path_buf());
        new_client.activation_lane = std::sync::Arc::clone(&self.activation_lane);
        if let Err(error) = self
            .verify_reconnected_session(project_root, &new_client)
            .await
        {
            // The daemon already opened this session; do not leave it to the
            // reaper just because verification refused it.
            close_current_session(new_client, None, SESSION_CLOSE_TIMEOUT).await;
            return Err(error);
        }
        Ok(new_client)
    }

    /// The post-open half of [`Self::reconnect`]: identity checks and the
    /// working-set restore against the freshly opened session.
    async fn verify_reconnected_session(
        &self,
        project_root: &Path,
        new_client: &DaemonSessionClient,
    ) -> anyhow::Result<()> {
        // Task 8: home is immutable across reconnects — the fresh session
        // must resolve to the SAME deterministic project id, or something
        // rebound the identity underneath us. Fail closed instead of serving
        // a different project as "home".
        if let Ok(canonical_home) = canonical_project_root(project_root) {
            let expected_home = project_key(&canonical_home);
            anyhow::ensure!(
                new_client.project_id == expected_home,
                "reconnect produced a different home project id (expected {expected_home}, got {}); refusing to serve",
                new_client.project_id
            );
        }

        // Reopen every additively-opened sibling and verify each restores
        // with its deterministic id. A sibling that fails to reopen or
        // verifies to a different id fails the whole reconnect (fail closed:
        // a silently missing sibling would turn explicit reads into
        // not-open errors, and a mismatched one would serve the wrong code).
        //
        // Sibling reopens use `add:true` so they CANNOT steal per-session
        // activation — a fresh session's active project is its home, and the
        // pre-reconnect active root is restored explicitly below.
        let siblings: Vec<PathBuf> = self.opened_roots.lock().clone();
        for root in &siblings {
            let response = new_client
                .call_tool_value(
                    "index_folder",
                    serde_json::json!({ "path": root.display().to_string(), "add": true }),
                )
                .await
                .with_context(|| {
                    format!("reconnect failed to reopen sibling {}", root.display())
                })?;
            let expected = canonical_project_root(root).map(|c| project_key(&c));
            if let Ok(expected) = expected {
                anyhow::ensure!(
                    response.contains(&format!("project_id={expected}")),
                    "reconnect reopened sibling {} with an unexpected identity; refusing to serve (receipt: {response})",
                    root.display()
                );
            }
            new_client.record_opened_root(root.clone());
        }

        // Restore the pre-reconnect ACTIVE project: a fresh session's active
        // project is its home, so when the caller had activated a sibling via
        // a default `index_folder`, re-issue that default open (which now
        // activates per the locked contract). Fail closed on a receipt for a
        // different project.
        //
        // ponytail: re-running the default open re-reloads the project; a
        // dedicated set-active route would avoid the reload. Deferred until
        // reload cost matters in practice.
        let active = self.active_root.lock().clone();
        if let Some(active) = active {
            let is_home = canonical_project_root(&active)
                .ok()
                .zip(canonical_project_root(project_root).ok())
                .map(|(a, h)| a == h)
                .unwrap_or(false);
            if !is_home {
                let response = new_client
                    .call_tool_value(
                        "index_folder",
                        serde_json::json!({ "path": active.display().to_string() }),
                    )
                    .await
                    .with_context(|| {
                        format!(
                            "reconnect failed to restore active project {}",
                            active.display()
                        )
                    })?;
                if let Ok(canonical_active) = canonical_project_root(&active) {
                    let expected = project_key(&canonical_active);
                    anyhow::ensure!(
                        response.contains(&format!("project_id={expected}")),
                        "reconnect restored active project {} with an unexpected identity; refusing to serve (receipt: {response})",
                        active.display()
                    );
                }
                new_client.record_opened_root(active.clone());
                new_client.record_active_root(active);
            }
        }
        Ok(())
    }

    pub async fn call_tool_value(
        &self,
        tool_name: &str,
        params: serde_json::Value,
    ) -> anyhow::Result<String> {
        let request = self
            .http_client
            .post(format!(
                "{}/v1/sessions/{}/tools/{}",
                self.base_url, self.session_id, tool_name
            ))
            .json(&params);
        // D23: stamp the surface actually served on THIS adapter's connection so
        // the daemon renders empty-index recovery hints for the AGENT's surface,
        // not the daemon process's own env. This runs in the adapter process, so
        // `surface_profile_from_env` here IS the connection surface. Set
        // unconditionally at the proxy boundary — a stdio client cannot inject
        // this header onto the adapter→daemon hop, so the adapter value is
        // authoritative (D22 overwrite discipline; out-of-band header variant).
        let request = apply_daemon_auth_header(request, self.auth_token.as_deref()).header(
            crate::protocol::surface_probe::CONNECTION_SURFACE_HEADER,
            crate::protocol::surface_probe::surface_profile_label(
                crate::protocol::surface_probe::surface_profile_from_env(),
            ),
        );
        let response = request
            .send()
            .await
            .with_context(|| format!("calling daemon tool '{tool_name}'"))?
            .error_for_status()
            .with_context(|| format!("daemon rejected tool '{tool_name}'"))?;

        // Task 7: the daemon's selected-project receipt arrives out-of-band as
        // a response header; parse the typed evidence and record it in the
        // per-dispatch slot so the statused wrapper attaches it to `_meta`.
        // Never reconstructed from the text body.
        let project_evidence = if let Some(header) = response
            .headers()
            .get(crate::protocol::result_status::PROJECT_EVIDENCE_HEADER)
            && let Ok(evidence) = serde_json::from_slice::<
                crate::protocol::result_status::ProjectEvidence,
            >(header.as_bytes())
        {
            Some(evidence)
        } else {
            None
        };

        let body = response
            .text()
            .await
            .with_context(|| format!("reading daemon tool response for '{tool_name}'"))?;
        // A receipt and its semantic body are one observation. Publish the
        // receipt only after the body has been read successfully; otherwise a
        // truncated/failed response could leak target evidence into a local
        // fallback or a later retry in the same dispatch scope.
        if let Some(evidence) = project_evidence {
            crate::protocol::result_status::record_project_evidence(evidence);
        }
        Ok(body)
    }

    pub async fn heartbeat(&self) -> anyhow::Result<HeartbeatResponse> {
        let request = self.http_client.post(format!(
            "{}/v1/sessions/{}/heartbeat",
            self.base_url, self.session_id
        ));
        apply_daemon_auth_header(request, self.auth_token.as_deref())
            .send()
            .await
            .context("sending daemon heartbeat")?
            .error_for_status()
            .context("daemon heartbeat status")?
            .json::<HeartbeatResponse>()
            .await
            .context("daemon heartbeat body")
    }

    pub async fn close(&self) -> anyhow::Result<CloseSessionResponse> {
        let request = self
            .http_client
            .delete(format!("{}/v1/sessions/{}", self.base_url, self.session_id));
        apply_daemon_auth_header(request, self.auth_token.as_deref())
            .send()
            .await
            .context("closing daemon session")?
            .error_for_status()
            .context("daemon close status")?
            .json::<CloseSessionResponse>()
            .await
            .context("daemon close body")
    }
}

struct DaemonStartLock {
    path: PathBuf,
}

impl Drop for DaemonStartLock {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

/// How long a session open may take before the adapter gives up on the
/// daemon and falls back to a local index. The stdio front answers the
/// handshake while the open runs, so this bound protects no harness timeout;
/// it only decides when to stop waiting for the daemon. A snapshot restore of
/// a large project runs inside the open and can take minutes, and giving up
/// early would leave every such harness on its own private local index.
const DAEMON_SESSION_OPEN_TIMEOUT: Duration = Duration::from_secs(15 * 60);

/// The shared slot a daemon-proxy server keeps its CURRENT session in (a
/// reconnect swaps the client inside it).
pub(crate) type SessionSlot = Arc<tokio::sync::RwLock<DaemonSessionClient>>;

/// Upper bound on the closing request: a daemon that is already gone must not
/// hold the adapter's exit open.
const SESSION_CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);

/// Run `run`, then close the daemon session on EVERY way out of it: success,
/// an early `?` return, or the client leaving. `run` publishes the slot the
/// server keeps its current session in once that exists, so a session replaced
/// by a reconnect is the one that closes; before that, `session` is current.
/// The close is best effort and time-bounded, so a dead daemon costs at most
/// `SESSION_CLOSE_TIMEOUT` and never masks `run`'s own result.
pub(crate) async fn run_then_close_session<T>(
    session: DaemonSessionClient,
    run: impl AsyncFnOnce(&mut Option<SessionSlot>) -> anyhow::Result<T>,
) -> anyhow::Result<T> {
    let mut slot = None;
    let result = run(&mut slot).await;
    close_current_session(session, slot, SESSION_CLOSE_TIMEOUT).await;
    result
}

/// Close the current session within ONE `bound` that covers reading the slot
/// AND the request: a reconnect holds the slot's write lock for as long as the
/// daemon open takes (up to the open timeout), so an unbounded read would let
/// an adapter exiting mid-reconnect hang. Giving up is safe: the daemon reaper
/// collects whatever an unfinished reconnect leaves once this process is gone.
/// A failure or timeout is logged, never returned.
async fn close_current_session(
    session: DaemonSessionClient,
    slot: Option<SessionSlot>,
    bound: std::time::Duration,
) {
    let close = async {
        let current = match slot {
            Some(slot) => slot.read().await.clone(),
            None => session,
        };
        current.close().await
    };
    match tokio::time::timeout(bound, close).await {
        Ok(Ok(_)) => {}
        Ok(Err(error)) => tracing::warn!("closing the daemon session on exit failed: {error:#}"),
        Err(_) => tracing::warn!(
            "closing the daemon session on exit gave up after {} ms; the daemon reaper will collect it",
            bound.as_millis()
        ),
    }
}

pub async fn connect_or_spawn_session(
    project_root: &Path,
    client_name: &str,
    pid: Option<u32>,
) -> anyhow::Result<DaemonSessionClient> {
    let control_state_dir = process_control_state_dir()?;
    connect_or_spawn_session_at(project_root, client_name, pid, control_state_dir).await
}

async fn connect_or_spawn_session_at(
    project_root: &Path,
    client_name: &str,
    pid: Option<u32>,
    control_state_dir: &ControlStateDir,
) -> anyhow::Result<DaemonSessionClient> {
    // JSON carries project roots as UTF-8 strings. A lossy display string is
    // not an identity: on Unix two real roots can differ only by invalid bytes
    // that both render as U+FFFD. Refuse before daemon discovery/spawn rather
    // than opening one root remotely while retaining another for fallback.
    let canonical_project_root = project_root
        .canonicalize()
        .context("canonicalizing the project root before daemon session open")?;
    let project_root_text = canonical_project_root.to_str().ok_or_else(|| {
        anyhow::anyhow!(
            "the canonical project root is not valid UTF-8 and cannot be sent to the daemon without losing identity"
        )
    })?;
    let expected_project_id = project_key(&canonical_project_root);
    let port = ensure_daemon_running_at(control_state_dir).await?;
    let base_url = format!("http://127.0.0.1:{port}");
    let http_client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(5))
        .timeout(Duration::from_secs(60))
        .build()
        .context("building reqwest client for connect_or_spawn_session")?;
    // Resolve the token AFTER `ensure_daemon_running` so a freshly spawned
    // daemon's persisted token file is already present (it is written before the
    // port file). Env pin takes precedence; otherwise we read the token file.
    let auth_token = resolve_daemon_auth_token_at(control_state_dir);
    let open_request = http_client
        .post(format!("{base_url}/v1/sessions/open"))
        .timeout(DAEMON_SESSION_OPEN_TIMEOUT)
        .json(&OpenProjectRequest {
            project_root: project_root_text.to_string(),
            client_name: client_name.to_string(),
            pid,
        });
    let opened = apply_daemon_auth_header(open_request, auth_token.as_deref())
        .send()
        .await
        .context("opening daemon session")?
        .error_for_status()
        .context("daemon session open status")?
        .json::<OpenProjectResponse>()
        .await
        .context("daemon session open body")?;
    if opened.project_id != expected_project_id {
        // The daemon already holds this session; close it before refusing so
        // it is not left to the reaper.
        close_current_session(
            DaemonSessionClient::new_with_auth_token(
                base_url,
                opened.project_id,
                opened.session_id,
                opened.project_name,
                auth_token,
                control_state_dir.clone(),
            ),
            None,
            SESSION_CLOSE_TIMEOUT,
        )
        .await;
        anyhow::bail!(
            "daemon opened a project identity that does not match the canonical requested root"
        );
    }

    // Capture the daemon's boot epoch for descriptor epoch validation.
    // Unauthenticated /health by design; failure is non-fatal (epoch simply
    // absent, selection falls back to PID+TCP for legacy records).
    let daemon_started_at = daemon_health(port)
        .await
        .and_then(|h| h.started_at_unix_secs);

    Ok(DaemonSessionClient::new_with_auth_token(
        base_url,
        opened.project_id,
        opened.session_id,
        opened.project_name,
        auth_token,
        control_state_dir.clone(),
    )
    .with_project_root(canonical_project_root)
    .with_daemon_started_at(daemon_started_at))
}

async fn ensure_daemon_running_at(control_state_dir: &ControlStateDir) -> anyhow::Result<u16> {
    ensure_daemon_running_as(control_state_dir, &current_daemon_identity(), None).await
}

/// `symforge update`: make sure a daemon of `version`, running from the freshly
/// installed `executable`, owns the daemon records. This is the stdio client's
/// own spawn path with the NEW binary's identity, so an older recorded daemon is
/// replaced exactly as a new session would replace it. A policy that forbids
/// starting or replacing one is reported as [`InstalledDaemon::Skipped`], not as
/// an error: the new binary is not at fault.
pub(crate) async fn ensure_installed_daemon_running(
    executable: &Path,
    version: &str,
) -> anyhow::Result<InstalledDaemon> {
    ensure_installed_daemon_running_at(process_control_state_dir()?, executable, version).await
}

async fn ensure_installed_daemon_running_at(
    control_state_dir: &ControlStateDir,
    executable: &Path,
    version: &str,
) -> anyhow::Result<InstalledDaemon> {
    let identity = DaemonIdentity {
        version: version.to_string(),
        executable_path: normalized_path_string(executable),
    };
    if let Some(port) = daemon_port_if_compatible_at(control_state_dir, &identity).await? {
        return Ok(InstalledDaemon::Running {
            port,
            started: false,
        });
    }
    if daemon_autospawn_disabled() {
        return Ok(InstalledDaemon::Skipped(format!(
            "{DAEMON_AUTOSPAWN_ENV} is off"
        )));
    }
    if let Some(newer) = newer_recorded_daemon_version_at(control_state_dir, &identity).await {
        return Ok(InstalledDaemon::Skipped(format!(
            "a newer daemon ({newer}) owns this SymForge home"
        )));
    }
    let port = ensure_daemon_running_as(control_state_dir, &identity, Some(executable)).await?;
    Ok(InstalledDaemon::Running {
        port,
        started: true,
    })
}

/// What `symforge update` found or did about the daemon.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InstalledDaemon {
    /// A daemon of the new binary serves on `port`; `started` when update
    /// spawned it rather than finding it running.
    Running { port: u16, started: bool },
    /// Policy forbids starting or replacing a daemon; carries why.
    Skipped(String),
}

/// Ensure a daemon matching `identity` is running, spawning `executable`
/// (this process's own binary when `None`) if not.
async fn ensure_daemon_running_as(
    control_state_dir: &ControlStateDir,
    identity: &DaemonIdentity,
    executable: Option<&Path>,
) -> anyhow::Result<u16> {
    if let Some(port) = daemon_port_if_compatible_at(control_state_dir, identity).await? {
        tracing::debug!("daemon already running on port {port}");
        return Ok(port);
    }

    // `symforge update` leaves sessions of the previous release running. When
    // one of them loses its daemon connection it lands here with an OLDER
    // identity; replacing the newer daemon would knock every new session off it,
    // and the replacement it spawns from its own path is the new binary, which
    // never matches the old identity. Serve locally instead.
    if let Some(newer) = newer_recorded_daemon_version_at(control_state_dir, identity).await {
        anyhow::bail!(
            "a newer symforge daemon ({newer}) owns this SymForge home; this {} process will not replace it. \
             To run {} deliberately (a downgrade or a development build), end the newer daemon's process \
             first: its pid is in {}",
            identity.version,
            identity.version,
            control_state_dir
                .as_path()
                .join(daemon_pid_file_name())
                .display()
        );
    }

    // INCIDENT GUARD (2026-07-11): when auto-spawn cannot happen (test
    // build, deps/ artifact, or operator kill-switch), fail fast HERE with a
    // clear error instead of acquiring the start lock and waiting for a
    // daemon that nothing is allowed to start.
    if cfg!(test) || daemon_autospawn_disabled() {
        anyhow::bail!(
            "no running compatible daemon found and auto-spawn is disabled (test build or {DAEMON_AUTOSPAWN_ENV}); start `symforge daemon` explicitly"
        );
    }

    if let Some(lock) = try_acquire_start_lock_at(control_state_dir)? {
        if let Some(port) = daemon_port_if_compatible_at(control_state_dir, identity).await? {
            tracing::debug!("daemon became ready while acquiring lock, port {port}");
            return Ok(port);
        }
        tracing::info!("acquired start lock, spawning new daemon");
        stop_incompatible_recorded_daemon_at(control_state_dir, identity).await?;
        spawn_daemon_process(executable)?;
        // Task 9: release the lock as soon as the child is spawned — the
        // child's `guarded_daemon_start` acquires the SAME lock before
        // binding, so holding it through `wait_for_daemon_ready` would
        // deadlock parent (waiting for the child's port file) against child
        // (waiting for the lock).
        drop(lock);
        wait_for_daemon_ready_at(control_state_dir, identity).await
    } else {
        tracing::info!("start lock held by another process, waiting for daemon");
        wait_for_daemon_ready_at(control_state_dir, identity).await
    }
}

/// Outcome of [`guarded_daemon_start`].
pub enum GuardedStart {
    /// This process acquired the guard and bound the daemon.
    Started(DaemonHandle),
    /// A live compatible daemon already owns this `SYMFORGE_HOME`; its
    /// runtime record was left untouched.
    AlreadyRunning { port: u16 },
}

/// Task 9: the single safe way to BIND a daemon for the current
/// `SYMFORGE_HOME`. Acquires the start lock (bounded wait), re-checks for a
/// live compatible daemon UNDER the lock, stops an incompatible recorded
/// daemon, and only then binds in the current process — so a foreground
/// `symforge daemon` racing an auto-spawn (or another foreground start) can
/// never overwrite a live daemon's runtime record.
pub async fn guarded_daemon_start(bind_host: &str) -> anyhow::Result<GuardedStart> {
    let control_state_dir = process_control_state_dir()?;
    guarded_daemon_start_at(bind_host, control_state_dir).await
}

/// Start or reuse a daemon under an explicitly resolved control-state owner.
///
/// This is the typed-owner form used by embedders and isolated integration
/// harnesses. Process entry points should normally call [`guarded_daemon_start`].
#[doc(hidden)]
pub async fn guarded_daemon_start_at(
    bind_host: &str,
    control_state_dir: &ControlStateDir,
) -> anyhow::Result<GuardedStart> {
    let identity = current_daemon_identity();
    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(10);
    let _lock = loop {
        if let Some(port) = daemon_port_if_compatible_at(control_state_dir, &identity).await? {
            return Ok(GuardedStart::AlreadyRunning { port });
        }
        if let Some(lock) = try_acquire_start_lock_at(control_state_dir)? {
            break lock;
        }
        if tokio::time::Instant::now() >= deadline {
            anyhow::bail!(
                "timed out waiting for the symforge daemon start lock; another start is in progress"
            );
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    };
    // Re-check under the lock: a racer may have bound between our probe and
    // the acquisition.
    if let Some(port) = daemon_port_if_compatible_at(control_state_dir, &identity).await? {
        return Ok(GuardedStart::AlreadyRunning { port });
    }
    stop_incompatible_recorded_daemon_at(control_state_dir, &identity).await?;
    let handle = spawn_daemon_at(bind_host, control_state_dir).await?;
    Ok(GuardedStart::Started(handle))
}

async fn daemon_port_if_compatible_at(
    control_state_dir: &ControlStateDir,
    identity: &DaemonIdentity,
) -> anyhow::Result<Option<u16>> {
    let port = match read_daemon_port_file_at(control_state_dir) {
        Ok(port) => port,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(error) if error.kind() == io::ErrorKind::InvalidData => {
            tracing::warn!("ignoring corrupt symforge daemon port file: {error}");
            return Ok(None);
        }
        Err(error) => return Err(error).context("reading daemon port file"),
    };

    match daemon_health(port).await {
        Some(health) if daemon_health_matches(&health, identity) => Ok(Some(port)),
        Some(health) => {
            tracing::warn!(
                recorded_port = port,
                recorded_version = %health.daemon_version,
                expected_version = %identity.version,
                recorded_executable = %health.executable_path,
                expected_executable = %identity.executable_path,
                "recorded symforge daemon is incompatible with the current executable"
            );
            Ok(None)
        }
        None => Ok(None),
    }
}

/// The version of the live recorded daemon when it is NEWER than `identity`.
/// An unreadable record or an unreachable daemon is not newer.
async fn newer_recorded_daemon_version_at(
    control_state_dir: &ControlStateDir,
    identity: &DaemonIdentity,
) -> Option<String> {
    let port = read_daemon_port_file_at(control_state_dir).ok()?;
    let health = daemon_health(port).await?;
    crate::cli::version::is_newer_version(&health.daemon_version, &identity.version)
        .then_some(health.daemon_version)
}

async fn wait_for_daemon_ready_at(
    control_state_dir: &ControlStateDir,
    identity: &DaemonIdentity,
) -> anyhow::Result<u16> {
    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
    loop {
        if let Some(port) = daemon_port_if_compatible_at(control_state_dir, identity).await? {
            return Ok(port);
        }

        if tokio::time::Instant::now() >= deadline {
            anyhow::bail!("timed out waiting for symforge daemon to become ready");
        }

        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }
}

async fn daemon_health(port: u16) -> Option<DaemonHealth> {
    let client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(5))
        .timeout(Duration::from_secs(10))
        .build()
        .ok()?;
    client
        .get(format!("http://127.0.0.1:{port}/health"))
        .send()
        .await
        .ok()?
        .error_for_status()
        .ok()?
        .json::<DaemonHealth>()
        .await
        .ok()
}

async fn daemon_health_ok(port: u16) -> bool {
    daemon_health(port).await.is_some()
}

async fn stop_incompatible_recorded_daemon_at(
    control_state_dir: &ControlStateDir,
    identity: &DaemonIdentity,
) -> anyhow::Result<()> {
    let port = match read_daemon_port_file_at(control_state_dir) {
        Ok(port) => port,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) if error.kind() == io::ErrorKind::InvalidData => {
            tracing::warn!("removing corrupt symforge daemon port file: {error}");
            cleanup_daemon_runtime_files_at(control_state_dir);
            return Ok(());
        }
        Err(error) => return Err(error).context("reading daemon port file"),
    };

    let Some(health) = daemon_health(port).await else {
        cleanup_daemon_runtime_files_at(control_state_dir);
        return Ok(());
    };

    if daemon_health_matches(&health, identity) {
        return Ok(());
    }

    // Whether to clear the runtime record afterwards.
    //
    // Clearing it while the daemon is STILL ALIVE and identifiable orphans it:
    // this function returns early on a missing port file, so no later call can
    // ever reap it, and it keeps serving its own index to every client already
    // connected — invisibly, because nothing in a response says which instance
    // answered. The same reasoning is already written down for
    // `DaemonStopOutcome::StopTimedOut`, which deliberately leaves the files in
    // place.
    //
    // The default stays `true`, because a record we cannot act on is worse than
    // no record: with no pid file (and health reporting no pid) the process is
    // unidentifiable, so keeping the record makes it no more stoppable — it only
    // makes every later call re-walk the same dead end. We withhold cleanup
    // strictly for a daemon we tried to kill and failed, or deliberately
    // declined to kill; those are live, identified, and worth keeping visible.
    let mut clear_record = true;
    if let Ok(pid) = read_daemon_pid_file_at(control_state_dir) {
        if should_terminate_recorded_daemon(&health, identity, pid) {
            if let Err(error) = terminate_process(pid) {
                tracing::warn!(
                    pid,
                    "failed to terminate incompatible symforge daemon automatically: {error}"
                );
            }
            if !wait_for_daemon_unhealthy(port).await {
                clear_record = false;
                tracing::warn!(
                    pid,
                    port,
                    "incompatible symforge daemon still answering after termination; \
                     leaving its runtime records so it stays discoverable and stoppable"
                );
            }
        } else if !daemon_health_matches_recorded_pid(&health, pid) {
            clear_record = false;
            match health.pid {
                Some(health_pid) => {
                    tracing::warn!(
                        recorded_pid = pid,
                        daemon_pid = health_pid,
                        "not terminating incompatible symforge daemon because the pid file does not match health"
                    );
                }
                None => {
                    tracing::warn!(
                        recorded_pid = pid,
                        "not terminating incompatible symforge daemon because health did not report a pid"
                    );
                }
            }
        } else {
            clear_record = false;
            tracing::warn!(
                recorded_pid = pid,
                daemon_pid = ?health.pid,
                recorded_executable = %health.executable_path,
                expected_executable = %identity.executable_path,
                "not terminating incompatible symforge daemon because pid ownership/executable safety checks failed"
            );
        }
    }

    if clear_record {
        cleanup_daemon_runtime_files_at(control_state_dir);
    }
    Ok(())
}

/// Outcome of stopping the global daemon during `symforge update`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum DaemonStopOutcome {
    /// No live, recorded daemon was found.
    NotRunning,
    /// The daemon was terminated and confirmed gone.
    Stopped { pid: u32 },
    /// The daemon was signaled (incl. SIGKILL escalation) but had not exited
    /// within the wait window; its runtime files are LEFT IN PLACE so it stays
    /// discoverable and the next launch reuses it instead of spawning a duplicate.
    StopTimedOut { pid: u32 },
    /// A daemon was recorded but the ownership/executable safety gate refused to
    /// terminate it (e.g. the recorded pid was recycled by an unrelated process).
    SkippedSafety,
}

/// Stop the currently-recorded global daemon regardless of its version, for the
/// update flow: the binary is about to be replaced, so even a same-version
/// daemon must exit and let the next launch respawn the new one. Unlike
/// [`stop_incompatible_recorded_daemon_at`], this does not skip a same-identity
/// daemon — but it preserves the exact ownership/executable safety gate
/// (`should_terminate_recorded_daemon`) so an unrelated or pid-recycled process
/// is never terminated.
#[allow(unsafe_code)] // SAFETY: SIGKILL targets a pid that already passed the ownership safety gate; a dead/invalid pid only errors, no memory is touched.
pub(crate) async fn stop_running_daemon_for_update() -> anyhow::Result<DaemonStopOutcome> {
    let control_state_dir = process_control_state_dir()?;
    stop_running_daemon_for_update_at(control_state_dir).await
}

async fn stop_running_daemon_for_update_at(
    control_state_dir: &ControlStateDir,
) -> anyhow::Result<DaemonStopOutcome> {
    let port = match read_daemon_port_file_at(control_state_dir) {
        Ok(port) => port,
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            return Ok(DaemonStopOutcome::NotRunning);
        }
        Err(error) if error.kind() == io::ErrorKind::InvalidData => {
            tracing::warn!("removing corrupt symforge daemon port file during update: {error}");
            cleanup_daemon_runtime_files_at(control_state_dir);
            return Ok(DaemonStopOutcome::NotRunning);
        }
        Err(error) => return Err(error).context("reading daemon port file"),
    };

    let Some(health) = daemon_health(port).await else {
        // Recorded but unreachable — clear the stale files and report not-running.
        cleanup_daemon_runtime_files_at(control_state_dir);
        return Ok(DaemonStopOutcome::NotRunning);
    };

    let identity = current_daemon_identity();
    match read_daemon_pid_file_at(control_state_dir) {
        Ok(pid) if should_terminate_recorded_daemon(&health, &identity, pid) => {
            if let Err(error) = terminate_process(pid) {
                tracing::warn!(
                    pid,
                    "failed to terminate symforge daemon during update: {error}"
                );
            }
            wait_for_daemon_unhealthy(port).await;

            // Confirm the process is actually gone before declaring success and
            // removing its discovery files. The daemon's graceful-shutdown drain
            // (up to ~5s on Unix) can outlive terminate_process's wait window, so
            // escalate to SIGKILL and re-poll rather than orphaning a live daemon.
            if process_is_alive(pid) {
                #[cfg(unix)]
                #[allow(unsafe_code)]
                // SAFETY: sending a signal to a pid is always memory-safe; an
                // already-dead/invalid pid simply returns an error we ignore, and
                // liveness is re-confirmed by the loop below.
                unsafe {
                    libc::kill(pid as i32, libc::SIGKILL);
                }
                for _ in 0..20 {
                    if !process_is_alive(pid) {
                        break;
                    }
                    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                }
            }

            if process_is_alive(pid) {
                // Still alive: LEAVE its runtime files so it stays discoverable and
                // the next launch reuses it instead of spawning a duplicate.
                tracing::warn!(
                    pid,
                    "symforge daemon still alive after terminate during update"
                );
                Ok(DaemonStopOutcome::StopTimedOut { pid })
            } else {
                cleanup_daemon_runtime_files_at(control_state_dir);
                Ok(DaemonStopOutcome::Stopped { pid })
            }
        }
        // Safety gate refused: the daemon is alive and we will not touch it, so
        // LEAVE its runtime files in place — removing them would orphan a live,
        // discoverable daemon and cause a duplicate spawn on the next launch.
        Ok(_) => Ok(DaemonStopOutcome::SkippedSafety),
        // No readable pid file: nothing to stop; clear any stale leftovers.
        Err(_) => {
            cleanup_daemon_runtime_files_at(control_state_dir);
            Ok(DaemonStopOutcome::NotRunning)
        }
    }
}

/// Best-effort liveness check: does a process with this pid still exist?
#[allow(unsafe_code)] // SAFETY: kill(pid, 0) only probes for existence; it sends no signal and touches no memory.
fn process_is_alive(pid: u32) -> bool {
    #[cfg(windows)]
    {
        // `tasklist` lists the pid only when it exists; "No tasks" otherwise.
        // hidden_command: the daemon has no console, so a plain spawn would
        // flash a new conhost window on every periodic liveness check.
        crate::process_util::hidden_command("tasklist")
            .args(["/FI", &format!("PID eq {pid}"), "/NH", "/FO", "CSV"])
            .stdin(Stdio::null())
            .stderr(Stdio::null())
            .output()
            .map(|output| String::from_utf8_lossy(&output.stdout).contains(&pid.to_string()))
            .unwrap_or(false)
    }
    #[cfg(not(windows))]
    {
        // kill(pid, 0): Ok(0) => the process exists (or is a zombie),
        // ESRCH => it is gone.
        unsafe { libc::kill(pid as i32, 0) == 0 }
    }
}

/// One reaper sweep, TTL rule then pid rule, run on the blocking pool: closing
/// a session stops its project slot, which takes the mutation lock that a long
/// `index_folder` reload holds, and that must not park a tokio worker.
/// Returns `(ttl_reaped, dead_pid_reaped)`; a panicked sweep is logged and
/// counts as zero rather than being reported as a clean pass.
async fn sweep_sessions_off_thread(
    state: SharedDaemonState,
    ttl: std::time::Duration,
) -> (usize, usize) {
    let sweep = tokio::task::spawn_blocking(move || {
        (
            state.reap_expired_sessions(ttl),
            state.reap_dead_pid_sessions(STALE_SESSION_HEARTBEAT),
        )
    });
    match sweep.await {
        Ok(counts) => counts,
        Err(error) => {
            tracing::warn!("session reaper sweep did not complete: {error}");
            (0, 0)
        }
    }
}

/// Wait for `port` to stop answering health checks. Returns whether it actually
/// did: callers use this to decide if a daemon is CONFIRMED gone, and a timeout
/// must never be mistaken for success — removing a live daemon's runtime records
/// orphans it permanently.
async fn wait_for_daemon_unhealthy(port: u16) -> bool {
    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(3);
    while tokio::time::Instant::now() < deadline {
        if !daemon_health_ok(port).await {
            return true;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }
    !daemon_health_ok(port).await
}

fn try_acquire_start_lock_at(
    control_state_dir: &ControlStateDir,
) -> anyhow::Result<Option<DaemonStartLock>> {
    let path = daemon_dir_for(control_state_dir)?.join(daemon_start_lock_file_name());
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        Ok(_) => Ok(Some(DaemonStartLock { path })),
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
            // Check if the lock is stale (older than 30 seconds).
            // Daemon startup takes <5s normally, so a 30s-old lock is certainly stale.
            if let Ok(metadata) = std::fs::metadata(&path)
                && let Ok(modified) = metadata.modified()
                && modified.elapsed().unwrap_or_default() > std::time::Duration::from_secs(30)
            {
                tracing::warn!("removing stale daemon start lock (age > 30s)");
                let _ = std::fs::remove_file(&path);
                // Retry creation — another process may grab it first.
                if std::fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(&path)
                    .is_ok()
                {
                    return Ok(Some(DaemonStartLock { path }));
                }
            }
            Ok(None)
        }
        Err(error) => Err(error).context("creating daemon start lock"),
    }
}

/// Operator kill-switch for daemon auto-spawn: set
/// `SYMFORGE_DAEMON_AUTOSPAWN=off` (or `0`/`false`/`no`) to make
/// `ensure_daemon_running` connect-only — it will attach to an already
/// running compatible daemon but never start one.
pub const DAEMON_AUTOSPAWN_ENV: &str = "SYMFORGE_DAEMON_AUTOSPAWN";

fn daemon_autospawn_disabled() -> bool {
    std::env::var(DAEMON_AUTOSPAWN_ENV)
        .map(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "off" | "0" | "false" | "no"
            )
        })
        .unwrap_or(false)
}

/// Spawn `executable daemon` detached; `None` spawns this process's own binary.
fn spawn_daemon_process(executable: Option<&Path>) -> anyhow::Result<()> {
    let current_exe = match executable {
        Some(executable) => executable.to_path_buf(),
        None => std::env::current_exe().context("locating current symforge executable")?,
    };
    // INCIDENT GUARD (2026-07-11): under `cargo test`, `current_exe` is the
    // libtest binary and the `daemon` argument below is interpreted as a TEST
    // FILTER — spawning it recursively re-runs the daemon test subset, which
    // spawns again: an exponential fork bomb whose child processes flood the
    // desktop with console windows and steal focus. Three independent locks:
    // (1) a test build refuses statically; (2) a binary living in a Cargo
    // `deps/` directory (every test/bench artifact) refuses by path; (3) the
    // operator kill-switch refuses by env. Production `symforge.exe` (durable
    // install or `target/release/symforge.exe`) passes all three.
    if cfg!(test) {
        anyhow::bail!(
            "refusing to auto-spawn a daemon from a test build; start `symforge daemon` explicitly"
        );
    }
    if current_exe
        .parent()
        .and_then(|dir| dir.file_name())
        .is_some_and(|name| name == "deps")
    {
        anyhow::bail!(
            "refusing to auto-spawn a daemon from a Cargo deps/ test artifact: {}",
            current_exe.display()
        );
    }
    if daemon_autospawn_disabled() {
        anyhow::bail!(
            "daemon auto-spawn disabled by {DAEMON_AUTOSPAWN_ENV}; start `symforge daemon` explicitly"
        );
    }
    let mut command = std::process::Command::new(current_exe);
    if std::env::var_os(DAEMON_IDLE_SHUTDOWN_ENV).is_none() {
        command.env(
            DAEMON_IDLE_SHUTDOWN_ENV,
            DEFAULT_DAEMON_IDLE_SHUTDOWN_SECS.to_string(),
        );
    }
    command
        .arg("daemon")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;

        const DETACHED_PROCESS: u32 = 0x0000_0008;
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        command.creation_flags(DETACHED_PROCESS | CREATE_NO_WINDOW);
        stop_std_handle_inheritance();
    }

    command
        .spawn()
        .context("spawning detached symforge daemon")?;
    Ok(())
}

/// A Windows child inherits EVERY inheritable handle of its parent, not just
/// the three it is given, so the detached daemon would otherwise hold this
/// process's own stdio: a harness pipe when a stdio session spawns it, or the
/// caller's pipe when `symforge update | tee` restarts it. A daemon holding a
/// write end keeps that reader from ever seeing EOF (measured: a piped
/// `symforge update` hung until the daemon exited). Clearing the inherit flag
/// is safe for later children: `Stdio::inherit` duplicates the std handles
/// into a fresh inheritable copy.
#[cfg(windows)]
#[allow(unsafe_code)]
fn stop_std_handle_inheritance() {
    use std::os::windows::io::AsRawHandle;
    use windows::Win32::Foundation::{
        HANDLE, HANDLE_FLAG_INHERIT, HANDLE_FLAGS, SetHandleInformation,
    };

    for (name, raw) in [
        ("stdin", std::io::stdin().as_raw_handle()),
        ("stdout", std::io::stdout().as_raw_handle()),
        ("stderr", std::io::stderr().as_raw_handle()),
    ] {
        if raw.is_null() {
            continue; // no such handle, nothing to inherit
        }
        // SAFETY: `raw` is this process's live std handle, borrowed for the
        // call only; SetHandleInformation changes its inherit flag and touches
        // no memory we own.
        if let Err(error) =
            unsafe { SetHandleInformation(HANDLE(raw), HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0)) }
        {
            tracing::warn!("could not stop the daemon inheriting {name}: {error}");
        }
    }
}

fn current_daemon_identity() -> DaemonIdentity {
    let executable_path = std::env::current_exe()
        .ok()
        .map(|path| normalized_path_string(&path))
        .unwrap_or_else(|| "unknown".to_string());
    DaemonIdentity {
        version: env!("CARGO_PKG_VERSION").to_string(),
        executable_path,
    }
}

fn daemon_health_matches(health: &DaemonHealth, identity: &DaemonIdentity) -> bool {
    if health.daemon_version != identity.version {
        return false;
    }

    if health.executable_path == "unknown" || identity.executable_path == "unknown" {
        return true;
    }

    // Canonical, so one binary reached through a symlinked or junctioned
    // directory (nvm-windows points `C:\Program Files\nodejs` at the active
    // version dir) is one identity, not two daemons replacing each other.
    let canonical = |path: &str| {
        dunce::canonicalize(path)
            .map(|path| normalized_path_string(&path))
            .unwrap_or_else(|_| path.to_string())
    };
    stable_path_identity(&canonical(&health.executable_path))
        == stable_path_identity(&canonical(&identity.executable_path))
}

fn daemon_health_matches_recorded_pid(health: &DaemonHealth, recorded_pid: u32) -> bool {
    health.pid == Some(recorded_pid)
}

fn should_terminate_recorded_daemon(
    health: &DaemonHealth,
    identity: &DaemonIdentity,
    recorded_pid: u32,
) -> bool {
    if !daemon_health_matches_recorded_pid(health, recorded_pid) {
        return false;
    }

    if !daemon_executable_name_matches_current(health, identity) {
        return false;
    }

    #[cfg(target_os = "linux")]
    {
        if !recorded_pid_owner_matches_current_user(recorded_pid).unwrap_or(false) {
            return false;
        }

        if !recorded_pid_executable_matches_health(recorded_pid, health).unwrap_or(false) {
            return false;
        }
    }

    true
}

fn daemon_executable_name_matches_current(
    health: &DaemonHealth,
    identity: &DaemonIdentity,
) -> bool {
    let Some(health_name) = daemon_executable_file_name(&health.executable_path) else {
        return false;
    };
    let Some(identity_name) = daemon_executable_file_name(&identity.executable_path) else {
        return false;
    };
    health_name == identity_name
}

fn daemon_executable_file_name_for_platform(path: &str, windows: bool) -> Option<String> {
    if path == "unknown" {
        return None;
    }

    let normalized = normalized_path_text(path, windows);
    let name = normalized.rsplit('/').find(|part| !part.is_empty())?;
    if windows {
        Some(name.to_lowercase())
    } else {
        Some(name.to_string())
    }
}

fn daemon_executable_file_name(path: &str) -> Option<String> {
    daemon_executable_file_name_for_platform(path, cfg!(windows))
}

#[cfg(target_os = "linux")]
#[allow(unsafe_code)] // Reading /proc ownership needs the current effective uid from libc.
fn recorded_pid_owner_matches_current_user(pid: u32) -> Option<bool> {
    let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
    let uid_line = status.lines().find(|line| line.starts_with("Uid:"))?;
    let effective_uid = uid_line.split_whitespace().nth(2)?.parse::<u32>().ok()?;
    let current_uid = unsafe { libc::geteuid() as u32 };
    Some(effective_uid == current_uid)
}

#[cfg(target_os = "linux")]
fn recorded_pid_executable_matches_health(pid: u32, health: &DaemonHealth) -> Option<bool> {
    if health.executable_path == "unknown" {
        return None;
    }

    let actual = std::fs::read_link(format!("/proc/{pid}/exe")).ok()?;
    Some(
        stable_path_identity(&normalized_path_string(&actual))
            == stable_path_identity(&health.executable_path),
    )
}

fn stable_path_identity_for_platform(path: &str, windows: bool) -> String {
    let normalized = normalized_path_text(path, windows);
    if windows {
        normalized.to_lowercase()
    } else {
        normalized
    }
}

fn stable_path_identity(path: &str) -> String {
    stable_path_identity_for_platform(path, cfg!(windows))
}

impl ProjectInstance {
    #[cfg(test)]
    fn load(canonical_root: &Path) -> anyhow::Result<Self> {
        Self::load_rooted(canonical_root, None)
    }

    /// The `/v1/sessions/open` load. A cold index (no usable snapshot) gets at
    /// most [`SESSION_OPEN_COLD_INDEX_BUDGET`] inside the request; past that
    /// the open answers with the project still `Loading` and the load finishes
    /// in the background. Without the budget one open on a large repository ran
    /// the whole cold parse inside the request and outlived the client timeout.
    fn load_for_session_open(canonical_root: &Path) -> anyhow::Result<Self> {
        Self::load_rooted(canonical_root, Some(SESSION_OPEN_COLD_INDEX_BUDGET))
    }

    fn load_rooted(
        canonical_root: &Path,
        cold_index_budget: Option<Duration>,
    ) -> anyhow::Result<Self> {
        let binding = RootBinding {
            source: RootCandidateSource::InitCwd,
            canonical_root: canonical_root.to_path_buf(),
            root_id: crate::discovery::project_id_for_canonical_root(canonical_root),
            access_mode: SourceAccessMode::NormalProject,
        };
        let state_placement = crate::discovery::resolve_state_placement(&binding);
        Self::load_bound_within(&binding, state_placement, cold_index_budget)
    }

    fn load_bound(binding: &RootBinding, state_placement: StatePlacement) -> anyhow::Result<Self> {
        Self::load_bound_within(binding, state_placement, None)
    }

    fn load_bound_within(
        binding: &RootBinding,
        state_placement: StatePlacement,
        cold_index_budget: Option<Duration>,
    ) -> anyhow::Result<Self> {
        let canonical_root = &binding.canonical_root;
        let project_name = canonical_root
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("project")
            .to_string();

        // V11 bootstrap (C4b): every daemon project flows through the
        // process registry's single-flight admission BEFORE its index is
        // built. A refusal fails the open honestly — admission is
        // authoritative, not advisory. The live slot rides on the runtime
        // handle (C4c) so the dispatch neck can refuse a retired admission.
        let admission = live_index::index_lifecycle::activation::admit_project_with_outcome(
            live_index::index_lifecycle::process_runtime::SurfaceKind::Daemon,
            canonical_root,
            &binding.root_id.0,
            binding.access_mode,
            &state_placement,
        )
        .map_err(|refusal| {
            anyhow::anyhow!(
                "project admission refused for '{}': {refusal:?}",
                binding.root_id.0
            )
        })?;

        let persistence_status = if matches!(
            &state_placement,
            StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. }
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        let curation_coordinator =
            Arc::new(crate::protocol::knowledge_curation::KnowledgeCurationCoordinator::default());
        let background_load = Arc::new(BackgroundLoad::default());
        let bootstrapped = match cold_index_budget {
            Some(budget) => bootstrap_project_index_within(
                canonical_root,
                &state_placement,
                budget,
                &curation_coordinator,
                persistence_status,
                &background_load,
            ),
            None => bootstrap_project_index(canonical_root, &state_placement, &background_load)
                .map(|index| (index, ColdIndex::Loaded)),
        };
        let index = match bootstrapped {
            Ok((index, ColdIndex::Loaded)) => {
                if let Err(error) = curation_coordinator.recover_on_project_load(
                    &index,
                    canonical_root,
                    Some(&state_placement),
                    persistence_status,
                ) {
                    tracing::warn!(
                        "knowledge curation startup recovery remained fail-closed: {error}"
                    );
                }
                index
            }
            // The background finisher runs curation recovery once the index it
            // recovers against exists; against the placeholder it could only
            // fail closed and skip this load's recovery.
            Ok((index, ColdIndex::LoadingInBackground)) => index,
            Err(error) => {
                cleanup_failed_daemon_admission(&binding.root_id.0, admission);
                return Err(error);
            }
        };
        let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
        let token_stats = TokenStats::new();
        let persistence_health = Arc::new(RwLock::new(persistence_status));

        Ok(Self {
            project_id: binding.root_id.0.clone(),
            canonical_root: canonical_root.to_path_buf(),
            project_name,
            source_access_mode: binding.access_mode,
            state_placement,
            persistence_health,
            curation_coordinator,
            index:
                crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind_admitted(
                    index,
                    admission.into_slot(),
                ),
            watcher_info,
            watcher_task: None,
            stop_token: Arc::new(AtomicBool::new(false)),
            background_load,
            token_stats,
            symbol_cache: Arc::new(RwLock::new(HashMap::new())),
            session_ids: HashSet::new(),
            opened_at: SystemTime::now(),
            activation_state: ActivationState::Inactive,
        })
    }

    /// Activate background tasks (watcher + git temporal) for this project.
    /// Must only be called once, on an `Inactive` instance, after the caller
    /// has committed the instance into the project map under write-lock.
    fn activate(&mut self) {
        if self.activation_state != ActivationState::Inactive {
            tracing::error!(
                project_id = %self.project_id,
                state = ?self.activation_state,
                "activate() called on a project that is not Inactive — skipping"
            );
            return;
        }
        self.activation_state = ActivationState::Activating;

        self.stop_token = Arc::new(AtomicBool::new(false));
        self.watcher_task = start_project_watcher(
            self.canonical_root.clone(),
            self.index.shared(),
            Arc::clone(&self.watcher_info),
            Arc::clone(&self.stop_token),
        );

        // Kick off background git temporal analysis (non-blocking).
        let expected_gen = self.index.data_plane().current_project_generation();
        live_index::git_temporal::spawn_git_temporal_computation(
            self.index.shared(),
            self.canonical_root.clone(),
            expected_gen,
        );

        self.activation_state = ActivationState::Active;
    }
}

fn cleanup_failed_daemon_admission(
    project_id: &str,
    admission: live_index::index_lifecycle::activation::ProjectAdmission,
) {
    let key = live_index::index_lifecycle::registry::ProjectKey::new(project_id);
    let slot = admission.slot().slot();
    // A JoinedLive daemon opener may be joining a slot installed before
    // ProjectSlot construction; stop_if_unheld is the holder-safety guard.
    drop(admission);
    if let Err(refusal) = live_index::index_lifecycle::activation::process_project_registry()
        .stop_if_unheld(&key, slot)
    {
        tracing::debug!(
            project_id = %project_id,
            refusal = ?refusal,
            "failed daemon bootstrap left admission cleanup to another holder"
        );
    }
}

impl ProjectSlot {
    fn new(project: ProjectInstance) -> Self {
        Self {
            metadata: RwLock::new(project),
            mutation: Mutex::new(()),
        }
    }

    fn activate(&self) {
        let _mutation = self.mutation.lock();
        let mut project = self.metadata.write();
        if project.activation_state == ActivationState::Inactive {
            project.activate();
        }
    }

    /// Start the background cold load again when the last one failed, so a
    /// new session is not joined to that failure for the daemon's lifetime.
    fn retry_failed_background_load(&self) {
        // Serialized with `reload_with`, which holds the mutation lock through
        // an `index_folder` reload. A reload in flight will settle the project
        // itself; the retry stays flagged for the next open instead of
        // blocking this one behind it.
        let Some(_mutation) = self.mutation.try_lock() else {
            return;
        };
        let job = {
            let project = self.metadata.read();
            // A reload that since succeeded, `index_folder` for one, cleared the
            // failure's empty reason: nothing is left to retry.
            if !project.background_load.failed.swap(false, Ordering::AcqRel)
                || project
                    .index
                    .shared()
                    .published_state()
                    .local_empty_reason
                    .is_none()
            {
                return;
            }
            ColdLoadJob {
                index: project.index.shared(),
                root: project.canonical_root.clone(),
                placement: project.state_placement.clone(),
                curation_coordinator: Arc::clone(&project.curation_coordinator),
                persistence_status: *project.persistence_health.read(),
                background: Arc::clone(&project.background_load),
            }
        };
        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
            job.background.failed.store(true, Ordering::Release);
            return;
        };
        tracing::info!(
            root = %job.root.display(),
            "retrying the project's failed background index load for a new session"
        );
        let load = job.reload();
        job.retry(&runtime, load);
    }

    fn stop(&self) {
        let _mutation = self.mutation.lock();
        let (mut watcher_task, stop_token, project_id) = {
            let mut project = self.metadata.write();
            project
                .background_load
                .cancel
                .store(true, Ordering::Release);
            (
                project.watcher_task.take(),
                Arc::clone(&project.stop_token),
                project.project_id.clone(),
            )
        };
        abort_watcher_task(&mut watcher_task, &stop_token);
        // V11 bootstrap (C4b): retire the project's admission slot. A
        // refusal here means the registry never held this project live
        // (possible only for instances minted outside `load_bound`);
        // surfaced at debug so an orphaned slot is observable, not silent.
        if let Err(refusal) = live_index::index_lifecycle::activation::process_project_registry()
            .stop(&live_index::index_lifecycle::registry::ProjectKey::new(
                &project_id,
            ))
        {
            tracing::debug!(?refusal, project_id, "admission slot stop refused");
        }
    }

    fn base(&self) -> Arc<IndexBase> {
        let (canonical_root, index) = {
            let project = self.metadata.read();
            (
                project.canonical_root.clone(),
                Arc::clone(&project.index.data_plane().read()),
            )
        };
        let commit = match crate::git::head_sha(&canonical_root) {
            Ok(sha) => CommitId::Sha(sha),
            Err(_) => CommitId::Dirtyless,
        };
        Arc::new(IndexBase::new(
            BaseKey::new(canonical_root, commit),
            index,
            1,
        ))
    }

    fn server_for_session(&self) -> SymForgeServer {
        let (
            index,
            project_name,
            watcher_info,
            canonical_root,
            state_placement,
            persistence_health,
            curation_coordinator,
            token_stats,
        ) = {
            let project = self.metadata.read();
            (
                project.index.shared(),
                project.project_name.clone(),
                Arc::clone(&project.watcher_info),
                project.canonical_root.clone(),
                project.state_placement.clone(),
                Arc::clone(&project.persistence_health),
                Arc::clone(&project.curation_coordinator),
                Arc::clone(&project.token_stats),
            )
        };
        let mut server = SymForgeServer::new_with_state_placement(
            index,
            project_name,
            watcher_info,
            Some(canonical_root),
            Some(state_placement),
            Some(token_stats),
        );
        server.persistence_health = persistence_health;
        server.curation_coordinator = curation_coordinator;
        server
    }

    fn reload_for_binding(&self, binding: &RootBinding) -> anyhow::Result<(usize, usize)> {
        let (project_state_dir, source_exclusions) = {
            let project = self.metadata.read();
            (
                project.state_placement.directory().cloned(),
                crate::discovery::SourceExclusions::for_state_placement(
                    &binding.canonical_root,
                    &project.state_placement,
                ),
            )
        };
        self.reload_with(&binding.canonical_root, move |index, root| {
            index.reload_for_binding_with_exclusions(root, project_state_dir, source_exclusions)
        })
    }

    fn reload_with<F>(
        &self,
        canonical_root: &Path,
        reload_index: F,
    ) -> anyhow::Result<(usize, usize)>
    where
        F: FnOnce(&SharedIndex, &Path) -> anyhow::Result<()>,
    {
        let _mutation = self.mutation.lock();
        let (index, watcher_info, mut watcher_task, old_stop_token) = {
            let mut project = self.metadata.write();
            (
                project.index.shared(),
                Arc::clone(&project.watcher_info),
                project.watcher_task.take(),
                Arc::clone(&project.stop_token),
            )
        };
        let observer_aborted = abort_watcher_task(&mut watcher_task, &old_stop_token);

        // A failed rebuild must not leave the project blind. The abort above
        // stopped the observer and `take()` already cleared its handle, so
        // returning straight through `?` here drops the project's only
        // source-change trigger until it is reopened -- the retained index
        // stays queryable, but no later edit is ever observed. Start a
        // replacement before propagating the error, on the root the project is
        // STILL bound to: the success path below is what retargets
        // `canonical_root`, so on this path the old root is the one to watch.
        if let Err(error) = reload_index(&index, canonical_root) {
            // `task.abort()` is a hard abort: the watcher's cooperative tail --
            // the one place that latches its own cancellation gap -- never
            // runs on this path. The RETAINED index keeps serving, and every
            // change between the abort and the replacement below is unseen,
            // so the daemon must latch the gap the watcher could not. The
            // success path needs no latch: a completed reload is a full
            // re-scan that supersedes anything the old observer missed.
            //
            // Unfenced on purpose. `_mutation` is held for this whole window,
            // so no concurrent retarget can make this a stale incarnation's
            // gap -- the fenced variant would compare a generation to itself.
            if observer_aborted {
                index.latch_observer_gap();
            }
            let retained_root = self.metadata.read().canonical_root.clone();
            let stop_token = Arc::new(AtomicBool::new(false));
            let watcher_task = start_project_watcher(
                retained_root,
                Arc::clone(&index),
                Arc::clone(&watcher_info),
                Arc::clone(&stop_token),
            );
            {
                let mut project = self.metadata.write();
                project.stop_token = stop_token;
                project.watcher_task = watcher_task;
            }
            return Err(error);
        }
        let published = index.published_state();
        let counts = (published.file_count, published.symbol_count);
        let stop_token = Arc::new(AtomicBool::new(false));
        let watcher_task = start_project_watcher(
            canonical_root.to_path_buf(),
            Arc::clone(&index),
            watcher_info,
            Arc::clone(&stop_token),
        );
        {
            let mut project = self.metadata.write();
            project.stop_token = stop_token;
            project.watcher_task = watcher_task;
            project.canonical_root = canonical_root.to_path_buf();
            project.project_name = canonical_root
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("project")
                .to_string();
            project.project_id = project_key(canonical_root);
        }

        let expected_gen = index.current_project_generation();
        // Feature 020 (L-V02): opt-in, gated OFF by default — a no-op unless
        // SYMFORGE_LOCAL_REF_LANES is set, so the current-only path is unchanged.
        // Detached fire-and-forget, exactly like the git-temporal spawn below.
        spawn_local_ref_reconcile(Arc::clone(&index), canonical_root.to_path_buf());
        live_index::git_temporal::spawn_git_temporal_computation(
            index,
            canonical_root.to_path_buf(),
            expected_gen,
        );
        Ok(counts)
    }
}

/// Feature 020 (L-G05/L-G07/L-V04): publish P1 local-ref lanes for a project's
/// bare local branches on open/reload, mirroring `spawn_git_temporal_computation`
/// — fire-and-forget, never blocking P0 readiness. Gated OFF by default
/// (`local_ref_lanes_enabled`); when OFF this is a no-op and the current-only P0
/// path is byte-unchanged (L-V02). A non-git/unreadable repo or a failed
/// reconcile is swallowed: it never surfaces to the caller and never touches the
/// P0 lane (L-V04). Returns the spawned task handle (mainly so a test can await
/// it); production drops it to detach.
///
// ponytail: republishes ref lanes on open/reload ONLY. Live `.git/refs` movement
// (a branch created/deleted/moved while the project stays open) is not watched
// yet, so L-R03 holds across a reopen but not live. Upgrade path: a refs watcher
// (like the filesystem watcher) that calls `reconcile_local_ref_topology` on ref
// change.
// V11 callbacks census (Feature 020 Slice 4, C3b): publication-fence-gated
// DATA-PLANE enrichment — it publishes local-ref topology into the index and
// admits no repository-source bytes, so it holds no source-observation or
// publication authority of its own. C4's typed roots gate its publication.
fn spawn_local_ref_reconcile(
    index: SharedIndex,
    canonical_root: PathBuf,
) -> Option<tokio::task::JoinHandle<()>> {
    if !local_ref_lanes_enabled() {
        return None;
    }
    // Guard: only spawn if a tokio runtime is available (not the case in some
    // sync tests) — mirrors `spawn_git_temporal_computation`.
    if tokio::runtime::Handle::try_current().is_err() {
        return None;
    }
    // Blocking git tree-walk + parse work runs off the async worker threads.
    Some(tokio::task::spawn_blocking(move || {
        let Ok(canonical) = dunce::canonicalize(&canonical_root) else {
            return;
        };
        let Ok(repository) = git2::Repository::open(&canonical) else {
            // Non-git or unreadable repo: no local refs to publish. Never
            // propagated — the P0 lane is unaffected (L-V04).
            return;
        };
        let project_id = crate::discovery::project_id_for_canonical_root(&canonical);
        let repository_id =
            match crate::live_index::persist::capture_repository_source(&canonical, &project_id) {
                Ok(captured) => captured.source.repository_id,
                Err(error) => {
                    tracing::debug!(%error, "local ref reconcile: repository identity unavailable");
                    return;
                }
            };
        match live_index::local_ref_scout::reconcile_local_ref_topology(
            &index,
            &repository,
            repository_id,
            &live_index::local_ref_scout::LocalRefScoutBudget::default(),
        ) {
            Ok(outcome) => tracing::info!(
                published = outcome.published.len(),
                removed = outcome.removed.len(),
                checked_out = outcome.checked_out.len(),
                "local ref lanes reconciled",
            ),
            Err(error) => tracing::debug!(%error, "local ref reconcile skipped"),
        }
    }))
}

/// Bootstrap a project's live index for a daemon open/switch.
///
/// Fast path (contracts/team-artifact.md § Import flow): consume the persisted
/// `.symforge/index.bin`, or — when that is absent — the shared team artifact
/// `index.bin.zst`, via [`live_index::persist::load_snapshot`] (which verifies
/// integrity and quarantines a corrupt/stale/unverifiable artifact, returning
/// `None`). This is the whole point of the exported artifact: a teammate who
/// just `git clone`d gets a warm index instead of a cold full scan. A
/// background stat-check reconciles on-disk drift, mirroring the stdio local
/// path in `main.rs::run_local_mcp_server_async`.
///
/// Cold path: no snapshot/artifact present (or it was quarantined) — fall back
/// to a full discovery+parse [`live_index::LiveIndex::load`].
fn bootstrap_project_index(
    canonical_root: &Path,
    state_placement: &StatePlacement,
    background: &Arc<BackgroundLoad>,
) -> anyhow::Result<SharedIndex> {
    match restore_project_snapshot(canonical_root, state_placement, background) {
        Some(index) => Ok(index),
        None => cold_load_project_index(canonical_root, state_placement),
    }
}

/// Session-open bound on an inline cold load (see
/// [`ProjectInstance::load_for_session_open`]). Small repositories finish well
/// inside it and open exactly as before; a large one opens `Loading`.
const SESSION_OPEN_COLD_INDEX_BUDGET: Duration = Duration::from_secs(5);

/// Whether the index handed back by a bootstrap has been loaded, or is a
/// placeholder a background task is still filling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColdIndex {
    Loaded,
    LoadingInBackground,
}

/// Who owns a bounded cold load's outcome: the opener, while it is still
/// waiting, or the background finisher once the opener stopped waiting.
enum ColdLoadHandoff {
    Waiting,
    Done(anyhow::Result<()>),
    Abandoned,
}

/// What a project slot shares with its background cold load.
#[derive(Default)]
struct BackgroundLoad {
    /// Set when the slot stops. The load abandons its unpublished candidate
    /// and its outcome is dropped: there is no project left to report it to.
    cancel: AtomicBool,
    /// Set when a load nobody was waiting for failed. The next session open
    /// retries it rather than joining the failure for the daemon's lifetime.
    failed: AtomicBool,
}

/// A session-open cold load: the placeholder it fills and everything its
/// outcome is settled against.
#[derive(Clone)]
struct ColdLoadJob {
    index: SharedIndex,
    root: PathBuf,
    placement: StatePlacement,
    curation_coordinator: Arc<crate::protocol::knowledge_curation::KnowledgeCurationCoordinator>,
    persistence_status: CapabilityStatus,
    background: Arc<BackgroundLoad>,
}

impl ColdLoadJob {
    /// The production load: a full reload of the project that stops early
    /// once the slot is stopped.
    fn reload(
        &self,
    ) -> impl FnOnce(&SharedIndex, &AtomicBool) -> anyhow::Result<()> + Send + 'static {
        let (root, placement) = (self.root.clone(), self.placement.clone());
        move |index, cancel| {
            index.reload_for_binding_with_exclusions_cancellable(
                &root,
                placement.directory().cloned(),
                crate::discovery::SourceExclusions::for_state_placement(&root, &placement),
                cancel,
            )
        }
    }

    /// Run `load` into the placeholder on the blocking pool and wait up to
    /// `budget` for it. Within the budget its outcome is the open's, exactly
    /// like the inline path, including failing the open on an error. Past it
    /// the placeholder is returned (`Loading`, which every tool guard already
    /// reports) and [`Self::finish`] owns the outcome.
    fn open_within<L>(
        self,
        runtime: &tokio::runtime::Handle,
        budget: Duration,
        load: L,
    ) -> anyhow::Result<(SharedIndex, ColdIndex)>
    where
        L: FnOnce(&SharedIndex, &AtomicBool) -> anyhow::Result<()> + Send + 'static,
    {
        self.index.mark_bootstrap_loading();
        let handoff = Arc::new((Mutex::new(ColdLoadHandoff::Waiting), Condvar::new()));
        {
            let job = self.clone();
            let handoff = Arc::clone(&handoff);
            runtime.spawn_blocking(move || {
                let result = job.run(load);
                {
                    let (state, ready) = &*handoff;
                    let mut state = state.lock();
                    if matches!(*state, ColdLoadHandoff::Waiting) {
                        *state = ColdLoadHandoff::Done(result);
                        ready.notify_one();
                        return;
                    }
                }
                job.finish(result);
            });
        }

        let (state, ready) = &*handoff;
        let mut state = state.lock();
        ready.wait_while_for(
            &mut state,
            |state| matches!(state, ColdLoadHandoff::Waiting),
            budget,
        );
        match std::mem::replace(&mut *state, ColdLoadHandoff::Abandoned) {
            ColdLoadHandoff::Done(result) => {
                degrade_on_capacity_refusal(&self.index, &self.root, result)
                    .with_context(|| {
                        format!("failed to load project index for {}", self.root.display())
                    })
                    .map(|()| (self.index, ColdIndex::Loaded))
            }
            ColdLoadHandoff::Waiting => {
                tracing::info!(
                    root = %self.root.display(),
                    budget_ms = budget.as_millis() as u64,
                    "cold index load exceeded the session-open budget; continuing in the background"
                );
                Ok((self.index, ColdIndex::LoadingInBackground))
            }
            ColdLoadHandoff::Abandoned => unreachable!("only the opener abandons a cold load"),
        }
    }

    /// Start `load` again after a background load failed. Nobody waits for
    /// it; [`Self::finish`] owns its outcome.
    fn retry<L>(self, runtime: &tokio::runtime::Handle, load: L)
    where
        L: FnOnce(&SharedIndex, &AtomicBool) -> anyhow::Result<()> + Send + 'static,
    {
        self.index.set_local_empty_reason(None);
        self.index.mark_bootstrap_loading();
        runtime.spawn_blocking(move || {
            let result = self.run(load);
            self.finish(result);
        });
    }

    fn run<L>(&self, load: L) -> anyhow::Result<()>
    where
        L: FnOnce(&SharedIndex, &AtomicBool) -> anyhow::Result<()>,
    {
        load_catching_panic(|| load(&self.index, &self.background.cancel))
    }

    /// The half of a session-open cold load the opener stopped waiting for:
    /// curation recovery and git temporal on success, a named empty reason
    /// and a retry on the next open on failure, nothing once the slot stopped.
    fn finish(&self, result: anyhow::Result<()>) {
        if self.background.cancel.load(Ordering::Acquire) {
            tracing::info!(
                root = %self.root.display(),
                "background cold index load abandoned: its project was closed"
            );
            return;
        }
        // Another load published while this one ran, `index_folder` for one:
        // its index stands, and this failure has nothing left to settle.
        if result.is_err()
            && self.index.published_state().load_source
                != crate::live_index::IndexLoadSource::EmptyBootstrap
        {
            tracing::info!(
                root = %self.root.display(),
                "background cold index load failed after another load published; keeping that index"
            );
            return;
        }
        // Settle before flagging the retry: a retry that started first would
        // have its fresh `Loading` overwritten by this failure.
        if !settle_background_cold_load(&self.index, &self.root, result) {
            self.background.failed.store(true, Ordering::Release);
            return;
        }
        if let Err(error) = self.curation_coordinator.recover_on_project_load(
            &self.index,
            &self.root,
            Some(&self.placement),
            self.persistence_status,
        ) {
            tracing::warn!("knowledge curation startup recovery remained fail-closed: {error}");
        }
        let expected_gen = self.index.current_project_generation();
        live_index::git_temporal::spawn_git_temporal_computation(
            Arc::clone(&self.index),
            self.root.clone(),
            expected_gen,
        );
        tracing::info!(root = %self.root.display(), "background cold index load complete");
    }
}

/// [`bootstrap_project_index`] with the cold load bounded by `budget`; see
/// [`ColdLoadJob::open_within`]. A snapshot restore is unchanged.
fn bootstrap_project_index_within(
    canonical_root: &Path,
    state_placement: &StatePlacement,
    budget: Duration,
    curation_coordinator: &Arc<crate::protocol::knowledge_curation::KnowledgeCurationCoordinator>,
    persistence_status: CapabilityStatus,
    background: &Arc<BackgroundLoad>,
) -> anyhow::Result<(SharedIndex, ColdIndex)> {
    if let Some(index) = restore_project_snapshot(canonical_root, state_placement, background) {
        return Ok((index, ColdIndex::Loaded));
    }
    let Ok(runtime) = tokio::runtime::Handle::try_current() else {
        return cold_load_project_index(canonical_root, state_placement)
            .map(|index| (index, ColdIndex::Loaded));
    };
    let job = ColdLoadJob {
        index: LiveIndex::empty(),
        root: canonical_root.to_path_buf(),
        placement: state_placement.clone(),
        curation_coordinator: Arc::clone(curation_coordinator),
        persistence_status,
        background: Arc::clone(background),
    };
    let load = job.reload();
    job.open_within(&runtime, budget, load)
}

/// Run a background index load with a panic turned into an error, so the
/// placeholder it fills is settled instead of left `Loading` by a load that
/// died. The load builds its candidate outside the index and publishes it by
/// swap, so a panic leaves nothing half-published behind.
pub(crate) fn load_catching_panic(load: impl FnOnce() -> anyhow::Result<()>) -> anyhow::Result<()> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(load)).unwrap_or_else(|panic| {
        let detail = panic
            .downcast_ref::<&str>()
            .map(|message| (*message).to_string())
            .or_else(|| panic.downcast_ref::<String>().cloned())
            .unwrap_or_default();
        Err(anyhow::anyhow!("the index load panicked: {detail}"))
    })
}

/// Settle a background cold load's outcome on its placeholder: a capacity
/// refusal keeps the project open and non-ready, and any other failure becomes
/// its named empty reason. Either way the index leaves `Loading`, because no
/// load is coming. Returns whether the load succeeded. The local stdio lane
/// settles its own cold start through this too.
pub(crate) fn settle_background_cold_load(
    index: &SharedIndex,
    root: &Path,
    result: anyhow::Result<()>,
) -> bool {
    match degrade_on_capacity_refusal(index, root, result) {
        Ok(()) => true,
        Err(error) => {
            tracing::error!(root = %root.display(), "background cold index load failed: {error:#}");
            index.set_local_empty_reason(Some(format!(
                "the background index load failed: {error:#}"
            )));
            false
        }
    }
}

/// The inline cold path's catalog-capacity rule, applied to a placeholder: a
/// capacity refusal keeps the project non-ready but open; any other failure is
/// returned. The placeholder was marked as loading, and no load is coming now,
/// so the refusal is also its empty reason: `Empty`, never `Loading`.
fn degrade_on_capacity_refusal(
    index: &SharedIndex,
    canonical_root: &Path,
    result: anyhow::Result<()>,
) -> anyhow::Result<()> {
    let Err(error) = result else {
        return Ok(());
    };
    let Some(capacity) = error.downcast_ref::<crate::discovery::ScoutCapacityError>() else {
        return Err(error);
    };
    index.set_freshness_status(crate::domain::FreshnessStatus::Degraded {
        last_valid_content_generation: 0,
        reason_codes: vec![capacity.reason()],
    });
    index.set_local_empty_reason(Some(format!(
        "cold project observation refused by catalog capacity: {error:#}"
    )));
    tracing::warn!(
        root = %canonical_root.display(),
        reason = ?capacity.reason(),
        "cold project observation refused by catalog capacity; keeping project non-ready"
    );
    Ok(())
}

fn restore_project_snapshot(
    canonical_root: &Path,
    state_placement: &StatePlacement,
    background: &Arc<BackgroundLoad>,
) -> Option<SharedIndex> {
    let source_exclusions =
        crate::discovery::SourceExclusions::for_state_placement(canonical_root, state_placement);
    if let Some(snapshot) = live_index::persist::load_snapshot(canonical_root, state_placement) {
        let file_count = snapshot.files.len();
        let snapshot_mtimes: HashMap<String, u64> = snapshot
            .files
            .iter()
            .map(|(path, file)| (path.clone(), file.mtime_secs))
            .collect();
        let (live, code_signals) =
            live_index::persist::snapshot_to_live_index_with_code_signals(snapshot, canonical_root);
        tracing::info!(
            files = file_count,
            load_source = ?live.load_source(),
            root = %canonical_root.display(),
            "daemon bootstrap restored index from .symforge snapshot/team artifact"
        );
        let shared: SharedIndex =
            live_index::SharedIndexHandle::shared_with_source_exclusions_and_code_signals(
                live,
                source_exclusions.clone(),
                code_signals,
            );

        // Reconcile the restored snapshot against current disk state (offline
        // edits, or a teammate-cloned artifact vs their own working tree). Only
        // when a tokio runtime is present — daemon opens run under
        // `spawn_blocking`, so `Handle::current()` is available; a bare-sync
        // caller (e.g. a unit test) simply skips reconciliation and relies on
        // the watcher started in `activate()` for subsequent changes. Same
        // guard style as `start_project_watcher`.
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            let bg_index = shared.clone();
            let bg_root = canonical_root.to_path_buf();
            // V11 callbacks census (C3b): the verify callback carries the
            // observer incarnation current at its spawn; the watcher's later
            // registration in `activate()` makes it stale, and the lane then
            // refuses its observations (late V10 callbacks unreachable).
            let observer =
                live_index::index_lifecycle::activation::project_source_authority(canonical_root)
                    .active_observer();
            // A stopped slot retires this index; the verify stops with it
            // instead of re-reading a repository nobody will query.
            let background = Arc::clone(background);
            handle.spawn(async move {
                live_index::persist::background_verify_cancellable(
                    bg_index,
                    bg_root,
                    snapshot_mtimes,
                    observer,
                    move || background.cancel.load(Ordering::Acquire),
                )
                .await;
            });
        }

        return Some(shared);
    }
    None
}

fn cold_load_project_index(
    canonical_root: &Path,
    state_placement: &StatePlacement,
) -> anyhow::Result<SharedIndex> {
    let source_exclusions =
        crate::discovery::SourceExclusions::for_state_placement(canonical_root, state_placement);
    let cold_result = if matches!(state_placement, StatePlacement::ProjectLocal { .. }) {
        live_index::LiveIndex::load_for_state_placement(canonical_root, state_placement)
            .with_context(|| {
                format!(
                    "failed to load project index for {}",
                    canonical_root.display()
                )
            })
    } else {
        let index = LiveIndex::empty();
        match index.reload_for_binding_with_exclusions(
            canonical_root,
            state_placement.directory().cloned(),
            source_exclusions,
        ) {
            Ok(()) => Ok(index),
            Err(error) => Err(error),
        }
    };

    match cold_result {
        Ok(index) => Ok(index),
        Err(error) => {
            let Some(capacity) = error.downcast_ref::<crate::discovery::ScoutCapacityError>()
            else {
                return Err(error);
            };
            let index = LiveIndex::empty();
            index.set_freshness_status(crate::domain::FreshnessStatus::Degraded {
                last_valid_content_generation: 0,
                reason_codes: vec![capacity.reason()],
            });
            tracing::warn!(
                root = %canonical_root.display(),
                reason = ?capacity.reason(),
                "cold project observation refused by catalog capacity; keeping project non-ready"
            );
            Ok(index)
        }
    }
}

// V11 callbacks census (C3b): the observer-incarnation registration for this
// census row lives inside `run_watcher_with_stop` (C3a) — one incarnation per
// watcher instance, registered on the same authority every observation names.
fn start_project_watcher(
    repo_root: PathBuf,
    index: SharedIndex,
    watcher_info: Arc<Mutex<WatcherInfo>>,
    stop_token: Arc<AtomicBool>,
) -> Option<tokio::task::JoinHandle<()>> {
    tokio::runtime::Handle::try_current().ok().map(|handle| {
        handle.spawn(watcher::run_watcher_with_stop(
            repo_root,
            index,
            watcher_info,
            stop_token,
        ))
    })
}

fn abort_watcher_task(
    task: &mut Option<tokio::task::JoinHandle<()>>,
    stop_token: &Arc<AtomicBool>,
) -> bool {
    stop_token.store(true, Ordering::Release);
    if let Some(task) = task.take() {
        task.abort();
        true
    } else {
        false
    }
}

pub fn build_router(state: SharedDaemonState) -> Router {
    Router::new()
        .route("/health", get(daemon_health_handler))
        .route("/v1/projects", get(list_projects_handler))
        .route(
            "/v1/projects/{project_id}/health",
            get(project_health_handler),
        )
        .route(
            "/v1/projects/{project_id}/sessions",
            get(list_sessions_handler),
        )
        .route("/v1/sessions/open", post(open_project_session_handler))
        .route(
            "/v1/sessions/{session_id}/tools/{tool_name}",
            post(call_tool_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/health",
            get(sidecar_health_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/outline",
            get(sidecar_outline_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/workflows/source-read",
            get(sidecar_outline_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/impact",
            get(sidecar_impact_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/workflows/post-edit-impact",
            get(sidecar_impact_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/symbol-context",
            get(sidecar_symbol_context_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/workflows/search-hit-expansion",
            get(sidecar_symbol_context_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/repo-map",
            get(sidecar_repo_map_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/workflows/repo-start",
            get(sidecar_repo_map_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/prompt-context",
            get(sidecar_prompt_context_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/workflows/prompt-context",
            get(sidecar_prompt_context_handler),
        )
        .route(
            "/v1/sessions/{session_id}/sidecar/stats",
            get(sidecar_stats_handler),
        )
        .route(
            "/v1/sessions/{session_id}/heartbeat",
            post(heartbeat_handler),
        )
        .route("/v1/sessions/{session_id}", delete(close_session_handler))
        .with_state(state)
}

pub async fn spawn_daemon(bind_host: &str) -> anyhow::Result<DaemonHandle> {
    let control_state_dir = process_control_state_dir()?;
    spawn_daemon_at(bind_host, control_state_dir).await
}

/// Spawn a daemon under an explicitly resolved control-state owner.
///
/// This is the typed-owner form used by embedders and isolated integration
/// harnesses. Process entry points should normally call [`spawn_daemon`].
#[doc(hidden)]
pub async fn spawn_daemon_at(
    bind_host: &str,
    control_state_dir: &ControlStateDir,
) -> anyhow::Result<DaemonHandle> {
    let resolved_host = resolve_daemon_bind_host(bind_host)?;
    cleanup_daemon_runtime_files_at(control_state_dir);

    let listener = TcpListener::bind(daemon_socket_bind_address(&resolved_host)).await?;
    let port = listener.local_addr()?.port();

    // Establish the fail-closed auth token and persist it BEFORE the port file.
    // Clients discover the daemon via the port file and then read the token file;
    // writing the token first guarantees a client that observes the port can
    // always read a valid token (no open-then-tokenless window).
    let auth_token = establish_daemon_auth_token();
    write_daemon_token_file_at(control_state_dir, &auth_token)?;
    write_daemon_port_file_at(control_state_dir, port)?;
    write_daemon_pid_file_at(control_state_dir, std::process::id())?;
    // This process is now A daemon. Whether it is still THE recorded daemon is
    // re-checked per `status` call — a later incompatible start can orphan us
    // (see `unrecorded_daemon_pid`).
    DAEMON_BOUND.store(true, std::sync::atomic::Ordering::Release);

    let state = Arc::new(DaemonState::with_token_at(
        auth_token,
        control_state_dir.clone(),
    ));
    let app = build_router(Arc::clone(&state));
    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();

    let owned_token = state.auth_token_for_cleanup();
    let cleanup_control_state_dir = control_state_dir.clone();
    let server_task = tokio::spawn(async move {
        let shutdown_signal = async move {
            let _ = shutdown_rx.await;
        };

        if let Err(error) = axum::serve(listener, app)
            .with_graceful_shutdown(shutdown_signal)
            .await
        {
            tracing::error!("daemon server error: {error}");
        }

        // Owner-checked: never delete a successor daemon's fresh runtime files.
        cleanup_daemon_runtime_files_if_owner_at(
            &cleanup_control_state_dir,
            port,
            std::process::id(),
            &owned_token,
        );
    });

    // Task 9: one daemon-owned bounded reaper. The interval is derived from
    // the TTL (quarter period, clamped to [10s, 600s]) so a shortened test TTL
    // sweeps promptly while production stays quiet. The task holds only a
    // `Weak` on the state: it exits when the daemon state drops.
    let ttl = session_ttl_from_env();
    let idle_shutdown_after = daemon_idle_shutdown_from_env();
    let reaper_state = Arc::downgrade(&state);
    let reaper_task = tokio::spawn(async move {
        let mut period_secs = (ttl.as_secs() / 4)
            .clamp(10, 600)
            .min(SESSION_REAP_TICK_SECS);
        if let Some(idle) = idle_shutdown_after {
            // Sweep at least 4x per idle window so shutdown is not overly late.
            period_secs = period_secs.min((idle.as_secs() / 4).max(10));
        }
        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(period_secs));
        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        // Fire the idle notification at most once per idle stretch; keep
        // reaping afterwards for embedders that ignore the notification.
        let mut idle_fired = false;
        loop {
            interval.tick().await;
            let Some(state) = reaper_state.upgrade() else {
                break;
            };
            let (reaped, dead) = sweep_sessions_off_thread(Arc::clone(&state), ttl).await;
            if reaped > 0 {
                tracing::info!(reaped, ttl_secs = ttl.as_secs(), "session reaper sweep");
            }
            if dead > 0 {
                tracing::info!(dead, "session reaper closed sessions whose process exited");
            }
            if let Some(idle) = idle_shutdown_after {
                if state.active_authenticated_requests.load(Ordering::Relaxed) > 0 {
                    idle_fired = false;
                    continue;
                }
                let idle_ms = now_epoch_millis()
                    .saturating_sub(state.last_activity_at.load(Ordering::Relaxed));
                if idle_ms >= idle.as_millis() as u64 {
                    if !idle_fired {
                        idle_fired = true;
                        tracing::info!(
                            idle_secs = idle_ms / 1000,
                            "no authenticated activity within the idle window; requesting daemon shutdown"
                        );
                        state.idle_shutdown.notify_one();
                    }
                } else {
                    idle_fired = false;
                }
            }
        }
    });

    Ok(DaemonHandle {
        port,
        shutdown_tx,
        state,
        server_task,
        reaper_task,
    })
}

pub async fn run_daemon_until_shutdown(bind_host: &str) -> anyhow::Result<()> {
    // Task 9: foreground/service starts go through the guarded seam so they
    // can never clobber a live daemon's runtime record.
    let handle = match guarded_daemon_start(bind_host).await? {
        GuardedStart::Started(handle) => handle,
        GuardedStart::AlreadyRunning { port } => {
            anyhow::bail!(
                "a compatible symforge daemon is already running on port {port}; not starting a second one"
            );
        }
    };
    tracing::info!(port = handle.port, "shared daemon started");
    // Wait for SIGINT (Ctrl+C), SIGTERM (kill, systemd, containers), or the
    // reaper's idle-shutdown notification. All trigger the same graceful path.
    let idle_state = Arc::clone(&handle.state);
    #[cfg(unix)]
    {
        use tokio::signal::unix::{SignalKind, signal};
        let mut sigterm = signal(SignalKind::terminate())?;
        tokio::select! {
            _ = tokio::signal::ctrl_c() => {
                tracing::info!("received SIGINT, shutting down");
            },
            _ = sigterm.recv() => {
                tracing::info!("received SIGTERM, shutting down");
            },
            _ = idle_state.idle_shutdown.notified() => {
                tracing::info!("idle-shutdown window elapsed, shutting down");
            },
        }
    }
    #[cfg(not(unix))]
    {
        tokio::select! {
            result = tokio::signal::ctrl_c() => {
                result?;
                tracing::info!("received Ctrl+C, shutting down");
            },
            _ = idle_state.idle_shutdown.notified() => {
                tracing::info!("idle-shutdown window elapsed, shutting down");
            },
        }
    }
    let DaemonHandle {
        shutdown_tx,
        server_task,
        reaper_task,
        ..
    } = handle;
    reaper_task.abort();
    let _ = shutdown_tx.send(());
    match tokio::time::timeout(tokio::time::Duration::from_secs(5), server_task).await {
        Ok(Ok(())) => {}
        Ok(Err(join_err)) => tracing::warn!("daemon server task ended with join error: {join_err}"),
        Err(_) => tracing::warn!("timed out waiting for daemon server task to shut down"),
    }
    Ok(())
}

async fn daemon_health_handler(State(state): State<SharedDaemonState>) -> Json<DaemonHealth> {
    Json(state.health())
}

async fn list_projects_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
) -> Result<Json<Vec<ProjectSummary>>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    Ok(Json(state.list_projects()))
}

async fn project_health_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(project_id): AxumPath<String>,
) -> Result<Json<ProjectHealth>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    state
        .project_health(&project_id)
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)
}

async fn list_sessions_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(project_id): AxumPath<String>,
) -> Result<Json<Vec<SessionSummary>>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    state
        .list_sessions(&project_id)
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)
}

async fn open_project_session_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    Json(request): Json<OpenProjectRequest>,
) -> Result<Json<OpenProjectResponse>, (StatusCode, String)> {
    let _activity = authorize_daemon_request(&state, &headers).map_err(daemon_auth_error)?;
    let state_for_load = Arc::clone(&state);
    let response =
        tokio::task::spawn_blocking(move || state_for_load.open_project_session(request))
            .await
            .map_err(internal_error)?
            .map_err(bad_request)?;
    Ok(Json(response))
}

/// Resolve the [`crate::protocol::surface_probe::CONNECTION_SURFACE_HEADER`] on a
/// proxied daemon request to a surface profile (D23).
///
/// Absent or non-canonical -> `None`, so the empty-index guard renderer falls
/// back to the daemon's own env. Backward compatible with adapters that predate
/// the header and with direct clients that never send it — neither is an error.
fn connection_surface_from_headers(
    headers: &HeaderMap,
) -> Option<crate::protocol::surface_probe::SurfaceProfile> {
    headers
        .get(crate::protocol::surface_probe::CONNECTION_SURFACE_HEADER)
        .and_then(|value| value.to_str().ok())
        .and_then(crate::protocol::surface_probe::surface_profile_from_label)
}

/// Decode routing selectors without serde's permissive unknown-field/default
/// behavior. The daemon HTTP endpoint is independently callable, so malformed
/// selector values must be rejected before any ACTIVE/HOME runtime is chosen.
fn strict_daemon_project_selectors(
    params: &serde_json::Value,
) -> Result<(Option<String>, Option<Vec<String>>), String> {
    let Some(object) = params.as_object() else {
        return Ok((None, None));
    };
    let project = match object.get("project") {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::String(project)) => Some(project.clone()),
        Some(_) => return Err("project must be a string project id/alias.".to_string()),
    };
    let projects = match object.get("projects") {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::Array(projects)) => {
            let mut decoded = Vec::with_capacity(projects.len());
            for project in projects {
                let Some(project) = project.as_str() else {
                    return Err(
                        "projects entries must all be string project ids/aliases.".to_string()
                    );
                };
                decoded.push(project.to_string());
            }
            Some(decoded)
        }
        Some(_) => return Err("projects must be an array of project ids/aliases.".to_string()),
    };

    // Reuse the public selector contract for blank/empty/path/conflict checks.
    let _ = resolve_targets(project.as_deref(), projects.as_deref(), "<active>")?;
    if projects
        .as_deref()
        .is_some_and(|projects| projects.len() > 1 && projects.iter().any(|project| project == "*"))
    {
        return Err(
            "projects wildcard `*` must be the only entry; do not mix it with explicit projects."
                .to_string(),
        );
    }
    Ok((project, projects))
}

/// Adapter-only routing field for active-project tools whose public schema has
/// no `project` selector. Direct daemon callers may not use it for other tools
/// or combine it with public selector fields.
pub(crate) const PRIVATE_PROJECT_ROUTE_PIN: &str = "_symforge_project_route_pin";

pub(crate) fn private_project_routed_tool(tool_name: &str) -> bool {
    matches!(
        tool_name,
        "inspect_match"
            | "checkpoint_now"
            | "detect_impact"
            | "conventions"
            | "health"
            | "health_compact"
            | "status"
            | "context_inventory"
            | "symforge_retrieve"
    )
}

fn take_private_project_route_pin(
    tool_name: &str,
    params: &mut serde_json::Value,
) -> Result<Option<String>, String> {
    let Some(object) = params.as_object_mut() else {
        return Ok(None);
    };
    let has_public_selector = object.contains_key("project") || object.contains_key("projects");
    let Some(pin) = object.remove(PRIVATE_PROJECT_ROUTE_PIN) else {
        return Ok(None);
    };
    if !private_project_routed_tool(tool_name) {
        return Err(format!(
            "tool '{tool_name}' does not accept the daemon-private project route pin."
        ));
    }
    if has_public_selector {
        return Err(
            "the daemon-private project route pin cannot be combined with `project` or `projects`."
                .to_string(),
        );
    }
    let serde_json::Value::String(project) = pin else {
        return Err("the daemon-private project route pin must be a string.".to_string());
    };
    if project.trim().is_empty() || project.trim() != project {
        return Err(
            "the daemon-private project route pin must be a nonblank canonical project id."
                .to_string(),
        );
    }
    Ok(Some(project))
}

async fn call_tool_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath((session_id, tool_name)): AxumPath<(String, String)>,
    Json(mut params): Json<serde_json::Value>,
) -> Result<axum::response::Response, (StatusCode, String)> {
    use axum::response::IntoResponse;
    let _activity = authorize_daemon_request(&state, &headers).map_err(daemon_auth_error)?;
    let private_project_route_pin = match take_private_project_route_pin(&tool_name, &mut params) {
        Ok(pin) => pin,
        Err(message) => {
            return Ok(format!("Error: project_routing: {message}").into_response());
        }
    };
    if tool_name == "index_folder" {
        if params
            .as_object()
            .is_some_and(|object| object.contains_key("project") || object.contains_key("projects"))
        {
            return Ok(
                "Error: project_routing: tool 'index_folder' does not accept `project` or \
                 `projects`; `path` is the project selection for this operation."
                    .into_response(),
            );
        }
        let input = decode_params::<IndexFolderInput>(params).map_err(bad_request)?;
        let state_for_index = state.clone();
        let session_id_owned = session_id.clone();
        return state
            .governor
            .execute_non_abortable("index_folder", async move {
                tokio::task::spawn_blocking(move || {
                    state_for_index.index_folder_for_session(&session_id_owned, input)
                })
                .await
                .map_err(|join_err| anyhow::anyhow!("index_folder task panicked: {join_err}"))?
            })
            .await
            .map_err(|gov_err| bad_request(gov_err.into()))?
            .map_err(bad_request)
            .map(|text| text.into_response());
    }

    // Knowledge security ordering: reject a sensitive/invalid knowledge request
    // before project routing, working-set refresh, cache/CCR access, or any
    // repository observation. The protocol front-end performs the same guard,
    // but the daemon HTTP route is independently callable and must fail closed.
    if tool_name == "curate_knowledge" {
        let input = decode_params::<CurateKnowledgeInput>(params.clone()).map_err(bad_request)?;
        if let Err(message) = crate::protocol::knowledge_curation::validate_input(&input) {
            return Ok(message.into_response());
        }
    }
    let (raw_project, raw_projects) = match strict_daemon_project_selectors(&params) {
        Ok(selectors) => selectors,
        Err(message) => {
            return Ok(format!("Error: project_routing: {message}").into_response());
        }
    };
    let cross_project_selector_tool = matches!(
        tool_name.as_str(),
        "search_knowledge"
            | "review_knowledge"
            | "search_symbols"
            | "search_text"
            | "search_files"
            | "find_references"
    );
    if raw_project.is_some()
        && !cross_project_selector_tool
        && !single_project_routed_tool(&tool_name)
    {
        return Ok(format!(
            "Error: project_routing: tool '{tool_name}' does not accept a public `project` \
             selector."
        )
        .into_response());
    }
    if raw_projects.is_some() && !cross_project_selector_tool {
        return Ok(format!(
            "Error: project_routing: tool '{tool_name}' accepts at most one `project`; \
             `projects` is supported only by the set-valued discovery tools."
        )
        .into_response());
    }
    let mut scalar_target_runtime: Option<SessionRuntime> = None;
    let mut has_explicit_project_set = false;
    if cross_project_selector_tool {
        let (project, projects) = match tool_name.as_str() {
            "search_knowledge" => {
                let input =
                    decode_params::<SearchKnowledgeInput>(params.clone()).map_err(bad_request)?;
                if let Err(message) = crate::protocol::knowledge_search::validate_input(&input) {
                    return Ok(message.into_response());
                }
                (raw_project.clone(), raw_projects.clone())
            }
            "review_knowledge" => {
                let input =
                    decode_params::<ReviewKnowledgeInput>(params.clone()).map_err(bad_request)?;
                if let Err(message) = crate::protocol::knowledge_review::validate_input(&input) {
                    return Ok(message.into_response());
                }
                (raw_project.clone(), raw_projects.clone())
            }
            // The cross-project code-navigation verbs accept the SAME id/name
            // selectors but carry different input types, and they are
            // deliberately absent from `single_project_routed_tool`, so they
            // never met `runtime_for_target` — the only name->id resolver in the
            // tree. A project opened by `index_folder(add: true)`, whose receipt
            // advertises `project_name`, was therefore denied as "project not
            // open" when that same name was used as a selector.
            //
            // Read the selectors straight off the JSON rather than adding a
            // typed arm per verb: the write-back below already edits this same
            // object, and the knowledge validation above stays scoped to the
            // knowledge verbs that require it.
            _ => (raw_project.clone(), raw_projects.clone()),
        };

        if project.is_some() && projects.is_some() {
            return Ok(
                "Error: project_routing: project and projects are mutually exclusive: pass \
                 exactly one (a single id in `project`, or a list/`[\"*\"]` in `projects`)."
                    .into_response(),
            );
        }
        has_explicit_project_set = projects.is_some();

        // `search_knowledge` owns both scalar and set-valued targeting, so it
        // bypasses the single-project route below. Canonicalize every explicit
        // id/name selector through the same session-scoped resolver used by the
        // rest of the daemon before the cross-project dispatcher captures its
        // immutable source set. Wildcard expansion remains session-local.
        if let Some(selector) = project.as_deref() {
            let target_runtime = match state.runtime_for_target(&session_id, Some(selector)) {
                Ok(runtime) => runtime,
                Err(message) if message.starts_with("unknown session") => {
                    return Err((StatusCode::NOT_FOUND, message));
                }
                Err(message) => {
                    return Ok(format!("Error: project_routing: {message}").into_response());
                }
            };
            let project_id = target_runtime.project_id.clone();
            scalar_target_runtime = Some(target_runtime);
            if let Some(object) = params.as_object_mut() {
                object.insert("project".to_string(), serde_json::Value::String(project_id));
            }
        } else if let Some(selectors) = projects.as_deref()
            && !(selectors.len() == 1 && selectors[0] == "*")
        {
            let mut project_ids = Vec::with_capacity(selectors.len());
            for selector in selectors {
                let project_id = match state.runtime_for_target(&session_id, Some(selector)) {
                    Ok(runtime) => runtime.project_id,
                    Err(message) if message.starts_with("unknown session") => {
                        return Err((StatusCode::NOT_FOUND, message));
                    }
                    Err(message) => {
                        return Ok(format!("Error: project_routing: {message}").into_response());
                    }
                };
                if !project_ids.contains(&project_id) {
                    project_ids.push(project_id);
                }
            }
            if let Some(object) = params.as_object_mut() {
                object.insert("projects".to_string(), serde_json::json!(project_ids));
            }
        }
    }

    // Task 7: `status(detail="projects")` renders the SESSION's open-project
    // inventory (the daemon owns that state; the per-project server cannot see
    // sibling projects). Intercept before dispatch. Other detail levels keep
    // the existing per-project dispatch unchanged.
    if tool_name == "status" {
        #[derive(serde::Deserialize)]
        struct DetailPeek {
            #[serde(default)]
            detail: Option<String>,
        }
        let peek: DetailPeek =
            serde_json::from_value(params.clone()).unwrap_or(DetailPeek { detail: None });
        if peek.detail.as_deref() == Some("projects") {
            return state
                .render_session_project_inventory(&session_id)
                .ok_or_else(|| {
                    (
                        StatusCode::NOT_FOUND,
                        format!("unknown session '{session_id}'"),
                    )
                })
                .map(|text| text.into_response());
        }
    }

    // Task 4 (outstanding-work hardening): explicit single-project routing.
    // For the routed read/guidance verbs, peek the optional `project` selector,
    // resolve the target runtime through the ONE shared resolver, canonicalize
    // or strip the routing field, and dispatch the existing per-project
    // implementation. Curation retains the canonical explicit selector because
    // implicit-worktree mutation must fail closed. Omission selects the session's
    // ACTIVE project. The three cross-project
    // discovery verbs (search_symbols/search_text/find_references) keep their
    // own `project`/`projects` handling inside `execute_tool_call`.
    let runtime = if let Some(project) = private_project_route_pin.as_deref() {
        match state.runtime_for_target(&session_id, Some(project)) {
            Ok(runtime) => runtime,
            Err(message) if message.starts_with("unknown session") => {
                return Err((StatusCode::NOT_FOUND, message));
            }
            Err(message) => {
                return Ok(format!("Error: project_routing: {message}").into_response());
            }
        }
    } else if single_project_routed_tool(&tool_name) {
        #[derive(serde::Deserialize)]
        struct ProjectPeek {
            #[serde(default)]
            project: Option<String>,
            #[serde(default)]
            projects: Option<Vec<String>>,
        }
        let peek: ProjectPeek = serde_json::from_value(params.clone()).unwrap_or(ProjectPeek {
            project: None,
            projects: None,
        });
        // `search_files` is BOTH single-project routed (lone `project` keeps
        // the full handler with resolve/coupling modes) and set-valued
        // (`projects` fans out via the cross-project read route). The routed
        // strip below would silently swallow a `project`+`projects` conflict
        // before `resolve_targets` could see it, so reject it here.
        if peek.project.is_some() && peek.projects.is_some() {
            return Ok(
                "Error: project_routing: project and projects are mutually exclusive: pass \
                 exactly one (a single id in `project`, or a list/`[\"*\"]` in `projects`)."
                    .into_response(),
            );
        }
        match state.runtime_for_target(&session_id, peek.project.as_deref()) {
            Ok(runtime) => {
                if peek.project.is_some()
                    && let Some(object) = params.as_object_mut()
                {
                    if tool_name == "curate_knowledge" {
                        object.insert(
                            "project".to_string(),
                            serde_json::Value::String(runtime.project_id.clone()),
                        );
                    } else {
                        object.remove("project");
                    }
                }
                runtime
            }
            Err(message) if message.starts_with("unknown session") => {
                return Err((StatusCode::NOT_FOUND, message));
            }
            // Deterministic routing errors surface as HTTP 200 tool text (same
            // convention as tool errors below) so the MCP client sees the
            // candidates immediately instead of a transport failure.
            Err(message) => {
                return Ok(format!("Error: project_routing: {message}").into_response());
            }
        }
    } else {
        state.session_runtime(&session_id).ok_or_else(|| {
            (
                StatusCode::NOT_FOUND,
                format!("unknown session '{session_id}'"),
            )
        })?
    };

    // Tool handlers acquire parking_lot::RwLock on the shared index, which
    // blocks the OS thread. Running them directly on the async runtime starves
    // tokio worker threads under concurrent load (10+ subagents).
    //
    // spawn_blocking moves execution to tokio's blocking thread pool (default
    // 512 threads), keeping async worker threads free for I/O, MCP transport,
    // and new request acceptance.
    // Task 7: the selected-project trust evidence for THIS call, captured from
    // the resolved runtime before dispatch. Returned out-of-band as a response
    // header so the human-readable body stays byte-identical; the adapter
    // parses it into the typed receipt and attaches it to `_meta`.
    let initial_call_evidence = if has_explicit_project_set {
        // A set-valued result has no honest single ProjectEvidence identity.
        // The adapter clears its HOME seed before proxying and will disclose
        // evidence unavailable until an aggregate receipt schema exists.
        None
    } else {
        let evidence_runtime = scalar_target_runtime.as_ref().unwrap_or(&runtime);
        // T046: one capture. `generation`, `load_source`, the counts, and
        // `index_state` all come off the SAME published bundle — the atomic
        // project-generation counter is not consulted, so the evidence cannot
        // pair a newer generation number with an older publication's counts.
        let generation = evidence_runtime.index.data_plane().published_generation();
        Some(crate::protocol::result_status::ProjectEvidence {
            project_id: evidence_runtime.project_id.clone(),
            project_name: evidence_runtime
                .canonical_root
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("project")
                .to_string(),
            canonical_root: Some(normalized_path_string(&evidence_runtime.canonical_root)),
            // Receipt equality must distinguish ordinary immutable publication
            // changes; project_generation intentionally stays stable across
            // content-only publishes.
            generation: generation.publication_generation,
            index_state: generation.health.status_label().to_string(),
            load_source: generation.live.load_source().label().to_string(),
            index_files: generation.health.file_count,
            index_symbols: generation.health.symbol_count,
        })
    };

    let tool_name_owned = tool_name.clone();
    let tool_name_for_panic = tool_name.clone();
    let state_for_refresh = Arc::clone(&state);
    // D23: the surface served on the connection this proxied call arrived on,
    // threaded out-of-band by the adapter. Bound around the dispatch below so any
    // empty-index recovery hint names only tools callable on the AGENT's surface,
    // not this daemon process's env. `None` (older adapter / direct attach) leaves
    // it unbound -> env fallback (unchanged behavior).
    let connection_surface = connection_surface_from_headers(&headers);
    match state
        .governor
        .execute_non_abortable(&tool_name, async move {
            let handle = tokio::runtime::Handle::current();
            match tokio::task::spawn_blocking(move || {
                // B2/D12: on the CROSS-PROJECT read path ONLY, lazily refresh each
                // targeted working-set base if the project's published index has
                // advanced since intern, BEFORE the search. The gate is shared with
                // the read route (`resolve_cross_project_targets` returns `None` for
                // the byte-identical single-active path), so single-project reads
                // never compare/re-intern and stay frecency-neutral (SC-4). Errors
                // and invalid targeting are surfaced by `execute_tool_call` itself.
                if tool_name_owned != "search_knowledge"
                    && let Some(targets) = resolve_cross_project_targets(
                        &tool_name_owned,
                        &params,
                        &runtime.project_id,
                    )
                {
                    state_for_refresh.refresh_working_set_bases(&runtime.working_set, &targets);
                }
                handle.block_on(crate::protocol::result_status::with_project_evidence_scope(
                    initial_call_evidence,
                    async move {
                        let result = crate::protocol::surface_probe::with_connection_surface(
                            connection_surface,
                            execute_tool_call(runtime, &tool_name_owned, params),
                        )
                        .await;
                        let evidence = crate::protocol::result_status::current_project_evidence();
                        (result, evidence)
                    },
                ))
            })
            .await
            {
                Ok(result) => result,
                Err(join_err) => (Err(anyhow::anyhow!("tool task panicked: {join_err}")), None),
            }
        })
        .await
    {
        Ok((Ok(mut result), mut response_evidence)) => {
            // Task 7: `health`/`health_compact` gain the session's open-project
            // inventory once MORE than one project is open. Single-project
            // sessions stay byte-identical.
            //
            // `status` is included for the same reason, not despite it: on the
            // compact-3 surface `status` is the ONLY health verb an agent has,
            // and every detail level except "projects" dispatches per-project
            // against the immutable home — so a project opened by
            // `index_folder(add: true)` was invisible BY CONSTRUCTION there. An
            // additive open that reports success and then cannot be observed is
            // the same silent-divergence class as an orphaned daemon.
            // `status(detail="projects")` is intercepted before dispatch, so it
            // never reaches here and cannot double-append.
            if matches!(
                tool_name_for_panic.as_str(),
                "health" | "health_compact" | "status"
            ) && let Some(inventory) =
                state.render_session_project_inventory_if_multi(&session_id)
            {
                result.push('\n');
                result.push_str(&inventory);
            }
            let mut response = result.into_response();
            if has_explicit_project_set {
                response_evidence = None;
            }
            if let Some(evidence) = response_evidence
                && let Ok(json) = serde_json::to_string(&evidence)
                && let Ok(value) = axum::http::HeaderValue::try_from(json)
            {
                response.headers_mut().insert(
                    crate::protocol::result_status::PROJECT_EVIDENCE_HEADER,
                    value,
                );
            }
            Ok(response)
        }
        Ok((Err(tool_err), _)) => {
            // Tool returned an error — surface it as HTTP 200 so the MCP client
            // gets the message immediately instead of entering reconnect/timeout.
            Ok(format!("Error in {}: {}", tool_name_for_panic, tool_err).into_response())
        }
        Err(gov_err) => {
            // Governor error (timeout, queue full, panic) — return as HTTP 200
            // with a clear error prefix so the model knows to stop waiting.
            let msg = format!(
                "Error: tool '{}' failed — {}. The tool did not complete. Do not retry immediately.",
                tool_name_for_panic, gov_err
            );
            tracing::error!(tool = %tool_name_for_panic, "tool execution failed: {gov_err}");
            Ok(msg.into_response())
        }
    }
}

/// Dogfood #6 parity for daemon-proxied sidecar routes: the local sidecar
/// router installs `caller_root_guard`; the daemon duplicates those routes
/// and must enforce the SAME check, or a session whose ACTIVE project moved
/// (a default `index_folder` by this or another agent) answers a caller
/// rooted elsewhere with the wrong project's data. 409 mirrors the local
/// contract so the hook falls back and re-resolves the project BY ROOT.
/// `/health`-style liveness is never routed here, so no path exemption is
/// needed.
fn guard_session_caller_root(
    runtime: &SessionRuntime,
    query: Option<&str>,
) -> Result<(), StatusCode> {
    if let Some(caller_root) = crate::sidecar::handlers::query_param(query, "caller_root")
        && !crate::sidecar::handlers::roots_match(
            std::path::Path::new(&caller_root),
            &runtime.canonical_root,
        )
    {
        tracing::warn!(
            caller_root,
            serving_root = %runtime.canonical_root.display(),
            "daemon sidecar caller-root mismatch — 409 (hook re-resolves by root)"
        );
        return Err(StatusCode::CONFLICT);
    }
    Ok(())
}

async fn sidecar_health_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
) -> Result<Json<crate::sidecar::handlers::HealthResponse>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/health", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(crate::sidecar::handlers::health_handler(State(sidecar)))
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn sidecar_outline_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
    uri: axum::http::Uri,
    Query(params): Query<crate::sidecar::handlers::OutlineParams>,
) -> Result<String, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    guard_session_caller_root(&runtime, uri.query())?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/outline", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(crate::sidecar::handlers::outline_handler(
                    State(sidecar),
                    Query(params),
                ))
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn sidecar_impact_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
    uri: axum::http::Uri,
    Query(params): Query<crate::sidecar::handlers::ImpactParams>,
) -> Result<String, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    guard_session_caller_root(&runtime, uri.query())?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/impact", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(crate::sidecar::handlers::impact_handler(
                    State(sidecar),
                    Query(params),
                ))
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn sidecar_symbol_context_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
    uri: axum::http::Uri,
    Query(params): Query<crate::sidecar::handlers::SymbolContextParams>,
) -> Result<String, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    guard_session_caller_root(&runtime, uri.query())?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/symbol-context", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(crate::sidecar::handlers::symbol_context_handler(
                    State(sidecar),
                    Query(params),
                ))
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn sidecar_repo_map_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
    uri: axum::http::Uri,
) -> Result<String, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    guard_session_caller_root(&runtime, uri.query())?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/repo-map", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(crate::sidecar::handlers::repo_map_handler(State(sidecar)))
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn sidecar_prompt_context_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
    uri: axum::http::Uri,
    Query(params): Query<crate::sidecar::handlers::PromptContextParams>,
) -> Result<String, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    guard_session_caller_root(&runtime, uri.query())?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/prompt-context", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(crate::sidecar::handlers::prompt_context_handler(
                    State(sidecar),
                    Query(params),
                ))
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn sidecar_stats_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
) -> Result<Json<crate::sidecar::StatsSnapshot>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    let runtime = state
        .session_runtime(&session_id)
        .ok_or(StatusCode::NOT_FOUND)?;
    let sidecar = sidecar_state_for_runtime(&runtime);
    state
        .governor
        .execute("sidecar/stats", async move {
            let handle = tokio::runtime::Handle::current();
            tokio::task::spawn_blocking(move || {
                handle.block_on(async {
                    Ok(crate::sidecar::handlers::stats_handler(State(sidecar)).await)
                })
            })
            .await
            .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR))
        })
        .await
        .map_err(|_| StatusCode::GATEWAY_TIMEOUT)?
}

async fn heartbeat_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
) -> Result<Json<HeartbeatResponse>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    Ok(Json(state.heartbeat(&session_id)))
}

async fn close_session_handler(
    State(state): State<SharedDaemonState>,
    headers: HeaderMap,
    AxumPath(session_id): AxumPath<String>,
) -> Result<Json<CloseSessionResponse>, StatusCode> {
    let _activity = authorize_daemon_request(&state, &headers)?;
    state
        .close_session(&session_id)
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)
}

/// Feature 012 (Phase 3): resolve the cross-project `project` / `projects`
/// params into a [`Targets`] selector, enforcing the surface contract.
///
/// CONTRACT (FR-004 / SC-001):
/// * BOTH omitted -> `One(active_project_id)` -> today's exact single-project
///   behavior (the caller dispatches it down the unchanged per-project path).
/// * `project` AND `projects` both set -> error (mutually exclusive).
/// * `projects: []` -> error (no silent "all"; `["*"]` is the explicit all).
/// * `projects: ["*"]` -> `All`.
/// * `project` containing a path separator -> corrective error (targets key on
///   project id/alias, NEVER a filesystem path).
/// * `project: id` -> `One(id)`; `projects: [ids..]` -> `Subset(ids)`.
///
/// Returns `Err(message)` for any contract violation; the message is surfaced to
/// the caller as an `InvalidRequest`-class tool response.
fn resolve_targets(
    project: Option<&str>,
    projects: Option<&[String]>,
    active_project_id: &str,
) -> Result<Targets, String> {
    match (project, projects) {
        (Some(_), Some(_)) => Err(
            "project and projects are mutually exclusive: pass exactly one (a single \
             id in `project`, or a list/`[\"*\"]` in `projects`)."
                .to_string(),
        ),
        (Some(id), None) => {
            if id.trim().is_empty() {
                return Err("project must be a non-empty project id/alias.".to_string());
            }
            // Target keys on project id/alias, NEVER a filesystem path. A path
            // here is a usage mistake -> corrective error pointing at the open
            // verb. `project-<hash>` ids and aliases never contain separators.
            if id.contains('/') || id.contains('\\') {
                return Err(format!(
                    "project must be a project id/alias, not a filesystem path ('{id}'). \
                     Open the folder first with index_folder(path=\"{id}\", add=true), \
                     then target it by its returned project id."
                ));
            }
            Ok(Targets::One(id.to_string()))
        }
        (None, Some(list)) => {
            if list.is_empty() {
                return Err(
                    "projects must not be empty: pass [\"*\"] for all open projects or an \
                     explicit list of project ids."
                        .to_string(),
                );
            }
            // Whitespace-only entries are invalid, but nonblank selector bytes
            // are identity-bearing. In particular, a trailing space is legal
            // in a Unix project name and must not retarget another project.
            let exact: Vec<&str> = list.iter().map(String::as_str).collect();
            if exact.iter().any(|id| id.trim().is_empty()) {
                return Err(
                    "projects entries must be non-empty project ids/aliases (blank entry found)."
                        .to_string(),
                );
            }
            if exact.contains(&"*") {
                // Any `*` in the list means "all open projects".
                return Ok(Targets::All);
            }
            for id in &exact {
                if id.contains('/') || id.contains('\\') {
                    return Err(format!(
                        "projects entries must be project ids/aliases, not filesystem paths \
                         ('{id}'). Open the folder first with \
                         index_folder(path=\"{id}\", add=true)."
                    ));
                }
            }
            // Dedup the subset's ids (order-preserving): a duplicate id would
            // otherwise render a second bogus `── project: <id> ──` header for the
            // same project. `Targets::selects` is membership, so dedup is purely a
            // rendering-honesty fix, not a behavior change.
            let mut seen = std::collections::HashSet::new();
            let deduped: Vec<String> = exact
                .into_iter()
                .filter(|id| seen.insert(id.to_string()))
                .map(|id| id.to_string())
                .collect();
            Ok(Targets::Subset(deduped))
        }
        (None, None) => Ok(Targets::One(active_project_id.to_string())),
    }
}

/// Whether `targets` resolves to exactly the single active project — the
/// no-regression fast path that dispatches down the UNCHANGED per-project route
/// (byte-identical to pre-012). Any other shape (`Subset`, `All`, or a single
/// NON-active project) is a cross-project read served from the working set.
fn targets_is_single_active(targets: &Targets, active_project_id: &str) -> bool {
    matches!(targets, Targets::One(id) if id == active_project_id)
}

/// Whether `targets` selects `project_id` — membership mirroring
/// `Targets::selects` (private to `view`) for the freshness refresh, which must
/// iterate only the targeted working-set entries.
fn targets_selects(targets: &Targets, project_id: &str) -> bool {
    match targets {
        Targets::One(id) => id == project_id,
        Targets::Subset(ids) => ids.iter().any(|id| id == project_id),
        Targets::All => true,
    }
}

/// Cross-project READ verbs. Edits, analyze_file_impact, orient, and
/// meta verbs are NEVER cross-project (they stay single-project on the active
/// project) — kept in one place so the read route (`execute_tool_call`) and the
/// freshness-refresh gate (`call_tool_handler`) agree by construction.
fn is_cross_project_read_verb(tool_name: &str) -> bool {
    matches!(
        tool_name,
        "search_symbols"
            | "search_text"
            | "search_knowledge"
            | "review_knowledge"
            | "find_references"
            | "search_files"
    )
}

/// Task 4 (outstanding-work hardening): the read/guidance verbs that accept ONE
/// optional `project` selector, resolved by `DaemonState::runtime_for_target`
/// in `call_tool_handler` before decode. Exactly the plan's parity table minus
/// the set-valued discovery verbs above (which own `project`/`projects` in
/// `execute_tool_call`) and minus `context_inventory` (session-scoped, no
/// selector). `search_files` is deliberately in BOTH sets: a lone `project`
/// routes here to the FULL single-project handler (resolve/coupling modes),
/// while `projects` fans out via the cross-project read route. Structural edits route the same way (Task 5): the selector is
/// batch-level only — each call stays one single-project transaction, and the
/// existing worktree/`working_directory` validation then runs against the
/// SELECTED project's repository, so an unrelated root rejects before preview
/// or apply.
pub(crate) fn single_project_routed_tool(tool_name: &str) -> bool {
    matches!(
        tool_name,
        "get_symbol"
            | "get_symbol_context"
            | "get_file_context"
            | "get_file_content"
            | "get_repo_map"
            | "search_files"
            | "find_dependents"
            | "diff_symbols"
            | "what_changed"
            | "analyze_file_impact"
            | "validate_file_syntax"
            | "explore"
            | "ask"
            | "conventions"
            | "edit_plan"
            | "investigation_suggest"
            | "replace_symbol_body"
            | "edit_within_symbol"
            | "insert_symbol"
            | "delete_symbol"
            | "batch_edit"
            | "batch_insert"
            | "batch_rename"
            | "symforge_edit"
            | "curate_knowledge"
    )
}

/// Resolve whether a tool call is a genuine CROSS-PROJECT read, returning the
/// targeted projects iff so (B2/D12). Returns `None` for every path that stays
/// single-project — a non-read verb, an unparseable peek, a resolve error, or a
/// `Targets` that is exactly the single active project — so callers leave the
/// byte-identical single-project route untouched (SC-4).
///
/// This is the SINGLE gate shared by both the read route in `execute_tool_call`
/// (which dispatches the cross-project search) and `call_tool_handler` (which
/// lazily refreshes the targeted working-set bases just before that dispatch).
/// Identical gating here guarantees the freshness refresh fires on exactly the
/// reads that read the working set, and never on the single-active fast path.
/// A genuine resolve error is surfaced by the read route's own `resolve_targets`
/// call; this gate swallows it (returns `None`) so the refresh never errors.
fn resolve_cross_project_targets(
    tool_name: &str,
    params: &serde_json::Value,
    active_project_id: &str,
) -> Option<Targets> {
    if !is_cross_project_read_verb(tool_name) {
        return None;
    }
    #[derive(serde::Deserialize)]
    struct CrossProjectPeek {
        #[serde(default)]
        project: Option<String>,
        #[serde(default)]
        projects: Option<Vec<String>>,
    }
    let peek: CrossProjectPeek =
        serde_json::from_value(params.clone()).unwrap_or(CrossProjectPeek {
            project: None,
            projects: None,
        });
    let targets = resolve_targets(
        peek.project.as_deref(),
        peek.projects.as_deref(),
        active_project_id,
    )
    .ok()?;
    if targets_is_single_active(&targets, active_project_id) {
        None
    } else {
        Some(targets)
    }
}

/// Validate that every explicitly-named target is actually OPEN in the working
/// set, returning a clear "project not open" error otherwise (FR-004). `All`
/// needs no check (it selects whatever is open). Unknown ids are a usage error,
/// not a silent empty result.
fn ensure_targets_open(targets: &Targets, working_set: &WorkingSet) -> Result<(), String> {
    let missing: Vec<&String> = match targets {
        Targets::One(id) => {
            if working_set.get(id).is_none() {
                vec![id]
            } else {
                Vec::new()
            }
        }
        Targets::Subset(ids) => ids
            .iter()
            .filter(|id| working_set.get(id).is_none())
            .collect(),
        Targets::All => Vec::new(),
    };
    if missing.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "project not open: {}. Open it in this session first with \
             index_folder(path=...) — the default spelling opens AND activates it; add=true opens additively.",
            missing
                .iter()
                .map(|id| format!("'{id}'"))
                .collect::<Vec<_>>()
                .join(", ")
        ))
    }
}

/// Default cap on the TOTAL number of rendered hits a cross-project read emits
/// across all targeted projects when the caller passes no `limit`. The
/// single-project paths bound themselves (search_symbols default 50, references
/// 20, text 50); the cross-project path fans out over N projects, so without a
/// shared cap a `projects:["*"]` query over many large projects could emit an
/// unbounded result. 200 is generous for a multi-project view yet hard-bounds the
/// output. The caller's `limit` overrides this (clamped to the hard ceiling).
const CROSS_PROJECT_DEFAULT_RESULT_CAP: usize = 200;

/// Absolute ceiling on the cross-project total hit count, even when the caller
/// passes a large `limit`. A cross-project read must never blow up the result no
/// matter what `limit` is requested.
const CROSS_PROJECT_MAX_RESULT_CAP: usize = 1000;

/// Resolve the effective total-hit cap for a cross-project read from the caller's
/// optional `limit`: `None` -> the default cap; `Some(l)` -> `l` clamped to
/// `[1, CROSS_PROJECT_MAX_RESULT_CAP]` (a zero or absurd limit cannot disable the
/// bound).
fn cross_project_result_cap(limit: Option<u32>) -> usize {
    match limit {
        Some(l) => (l as usize).clamp(1, CROSS_PROJECT_MAX_RESULT_CAP),
        None => CROSS_PROJECT_DEFAULT_RESULT_CAP,
    }
}

/// Apply the caller's optional `max_tokens` budget to an already-assembled
/// cross-project body, truncating at a line boundary and DISCLOSING the
/// truncation honestly (Principle III). Uses the project-wide ~4-bytes/token
/// approximation that the other budgeted formatters use. A `None` or zero budget
/// is a no-op. Returns the (possibly truncated) body.
fn apply_cross_project_token_budget(body: String, max_tokens: Option<u64>) -> String {
    let Some(max_tokens) = max_tokens.filter(|t| *t > 0) else {
        return body;
    };
    let max_bytes = (max_tokens as usize).saturating_mul(4);
    if max_bytes == 0 || body.len() <= max_bytes {
        return body;
    }
    // Truncate at the last newline that fits the byte budget so we never emit a
    // half-line, then disclose that the body was cut by the token budget. We scan
    // newline byte offsets directly (UTF-8 safe: `\n` is a single byte and never a
    // continuation byte, so `idx <= max_bytes` is always a valid char boundary —
    // no panic on multibyte match lines).
    let cut_end = body
        .bytes()
        .enumerate()
        .filter(|&(idx, b)| b == b'\n' && idx < max_bytes)
        .map(|(idx, _)| idx + 1)
        .next_back();
    let mut truncated = match cut_end {
        Some(end) => body[..end].to_string(),
        None => String::new(),
    };
    truncated.push_str(&format!(
        "... (truncated to fit max_tokens={max_tokens}; cross-project output is \
         token-bounded — raise max_tokens or query a single project for the full set)\n"
    ));
    truncated
}

/// Honest refusal of the cross-project params that are genuinely NOT supported
/// on the cross-project read path — as distinct from the scoping that IS now
/// honored. B1 threads `path_prefix`/`language`/noise/`limit` through the
/// engine's option-honoring `search_*_with_options` (so cross-project scoping
/// behaves identically to single-project; D11 + D14), and those are NO LONGER
/// refused here. What remains unsupported, and is therefore still refused
/// loudly rather than silently ignored:
/// * `search_text` `structural` — ast-grep runs a separate single-project
///   pipeline, not `search_text_with_options`, so it has no cross-project path;
/// * `find_references` `path`/`symbol_kind`/`direction` — single-project symbol
///   SELECTORS / implementations-mode direction, which have no cross-project
///   meaning and no option-honoring engine entry point.
///
/// Returns `Err(message)` for the FIRST still-unsupported param present, else
/// `Ok(())`. `kind`, `path_prefix`, and `language` are honored and not rejected.
fn reject_unsupported_cross_project_scoping(
    tool_name: &str,
    params: &serde_json::Value,
) -> anyhow::Result<()> {
    fn refuse(param: &str) -> anyhow::Result<()> {
        anyhow::bail!(
            "{param} scoping is not supported with cross-project targeting; \
             query a single project for scoped results."
        );
    }
    // A lenient peek of ONLY the still-unsupported fields; unrelated/invalid
    // sibling fields must not make this check fail (the real decode happens in
    // the per-tool branch). `null`/absent fields deserialize to `None`.
    #[derive(serde::Deserialize, Default)]
    struct ScopePeek {
        #[serde(default)]
        path: Option<String>,
        #[serde(default)]
        symbol_kind: Option<String>,
        #[serde(default)]
        direction: Option<String>,
        #[serde(default)]
        structural: Option<bool>,
        #[serde(default)]
        resolve: Option<bool>,
        #[serde(default)]
        changed_with: Option<String>,
        #[serde(default)]
        anchor_path: Option<String>,
        #[serde(default)]
        rank_by: Option<String>,
        #[serde(default)]
        current_file: Option<String>,
    }
    let peek: ScopePeek = serde_json::from_value(params.clone()).unwrap_or_default();
    let present = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.trim().is_empty());

    match tool_name {
        "search_text" => {
            if peek.structural == Some(true) {
                return refuse("structural");
            }
        }
        "find_references" => {
            if present(&peek.path) {
                return refuse("path");
            }
            if present(&peek.symbol_kind) {
                return refuse("symbol_kind");
            }
            if present(&peek.direction) {
                return refuse("direction");
            }
        }
        "search_files" => {
            // resolve/coupling/ranking modes are single-project pipelines:
            // refuse honestly instead of silently ignoring the mode.
            if peek.resolve == Some(true) {
                return refuse("resolve");
            }
            if present(&peek.changed_with) {
                return refuse("changed_with");
            }
            if present(&peek.anchor_path) {
                return refuse("anchor_path");
            }
            if present(&peek.rank_by) {
                return refuse("rank_by");
            }
            if present(&peek.current_file) {
                return refuse("current_file");
            }
        }
        _ => {}
    }
    Ok(())
}

/// Feature 012 (Phase 3): execute one of the three cross-project READ verbs
/// against the session's working set and format the attributed [`crate::live_index::view::ProjectHit`]
/// results with `── project: <id> ──` section headers (flat, no header, when a
/// single project is targeted). This is reached ONLY when `targets` is not the
/// single active project; the active-project path never enters here.
///
/// Read-only by construction: it calls the overlay-aware `WorkingSet` search
/// methods, which never mutate an overlay (the no-overlay-writes invariant).
///
/// SCOPING (B1): the cross-project path builds the SAME `SymbolSearchOptions`/
/// `TextSearchOptions` the single-project path builds (via
/// `search_symbols_options_from_input` / `search_text_options_from_input`) and
/// threads them through the engine's option-honoring `WorkingSet` search, so
/// `path_prefix`/`language`/noise/`limit` ARE honored cross-project (D11) and
/// each project's hits are `result_limit`-bounded and tier-ranked (D14). The
/// params that genuinely have no cross-project path are still REFUSED up front
/// ([`reject_unsupported_cross_project_scoping`]): `search_text` `structural`
/// and `find_references` `path`/`symbol_kind`/`direction`. The output is also
/// BOUNDED: a total-hit cap (caller `limit`, else
/// [`CROSS_PROJECT_DEFAULT_RESULT_CAP`]) and the caller's optional `max_tokens`
/// budget are applied by the formatters, which disclose any truncation.
fn execute_cross_project_read(
    tool_name: &str,
    params: serde_json::Value,
    targets: Targets,
    working_set: &WorkingSet,
) -> anyhow::Result<String> {
    ensure_targets_open(&targets, working_set).map_err(|message| anyhow::anyhow!("{message}"))?;

    // Honest refusal of the DEFERRED per-project derived-index scoping when
    // combined with cross-project targeting (rather than silently dropping it).
    reject_unsupported_cross_project_scoping(tool_name, &params)?;

    // Whether to render per-project section headers: a single targeted project
    // renders flat (one project's hits, no header); 2+ get headers.
    let multi = match &targets {
        Targets::One(_) => false,
        Targets::Subset(ids) => ids.len() > 1,
        Targets::All => working_set.len() > 1,
    };

    match tool_name {
        "search_symbols" => {
            let input: SearchSymbolsInput = decode_params(params)?;
            let query = input.query.as_deref().unwrap_or("").trim();
            if query.is_empty() {
                anyhow::bail!(
                    "cross-project search_symbols requires a non-empty query \
                     (browse mode is single-project only)."
                );
            }
            // Build the SAME options the single-project path builds, so cross-
            // project scoping (path_prefix, language, noise) + per-project
            // result_limit ranking behave identically (B1: D11 + D14). An unknown
            // language is an honest error, not a silent drop.
            let options = search_symbols_options_from_input(&input)
                .map_err(|message| anyhow::anyhow!(message))?;
            let cap = cross_project_result_cap(input.limit);
            let hits = working_set.search_symbols(&targets, query, input.kind.as_deref(), &options);
            let body = format_cross_project_symbols(&hits, query, multi, cap);
            Ok(apply_cross_project_token_budget(body, input.max_tokens))
        }
        "search_text" => {
            let input: SearchTextInput = decode_params(params)?;
            let regex = input.regex.unwrap_or(false);
            // Same options the single-project path builds (path_prefix, language,
            // noise, max_per_file, case/word, glob, ranked) so cross-project text
            // scoping is honored (B1: D11). `structural` was already refused above
            // (it runs a separate ast-grep pipeline).
            let mut options = search_text_options_from_input(&input)
                .map_err(|message| anyhow::anyhow!(message))?;
            // `context` (surrounding lines) is NOT rendered by the cross-project
            // text formatter, so drop it rather than compute-and-discard it or
            // imply it is honored. Rendering context / group_by / follow_refs
            // cross-project is a display concern tracked under A1b, not B1 scoping.
            options.context = None;
            let cap = cross_project_result_cap(input.limit);
            let results = working_set
                .search_text(
                    &targets,
                    input.query.as_deref(),
                    input.terms.as_deref(),
                    regex,
                    &options,
                )
                .map_err(|error| anyhow::anyhow!("text search failed: {error:?}"))?;
            let body = format_cross_project_text(&results, multi, cap);
            Ok(apply_cross_project_token_budget(body, input.max_tokens))
        }
        "find_references" => {
            let input: FindReferencesInput = decode_params(params)?;
            let name = input.name.trim();
            if name.is_empty() {
                anyhow::bail!("cross-project find_references requires a non-empty name.");
            }
            let kind_filter = match input.kind.as_deref() {
                Some("call") => Some(crate::domain::ReferenceKind::Call),
                Some("import") => Some(crate::domain::ReferenceKind::Import),
                Some("type_usage") => Some(crate::domain::ReferenceKind::TypeUsage),
                Some("macro_use") => Some(crate::domain::ReferenceKind::MacroUse),
                Some("value_use") => Some(crate::domain::ReferenceKind::ValueUse),
                _ => None,
            };
            let cap = cross_project_result_cap(input.limit);
            let hits = working_set.find_references(&targets, name, kind_filter, false);
            let body = format_cross_project_references(&hits, name, multi, cap);
            Ok(apply_cross_project_token_budget(body, input.max_tokens))
        }
        "search_files" => {
            let input: SearchFilesInput = decode_params(params)?;
            let query = input.query.trim();
            if query.is_empty() {
                anyhow::bail!("cross-project search_files requires a non-empty query.");
            }
            let path_scope = match input.path_prefix.as_deref().map(str::trim) {
                Some(prefix) if !prefix.is_empty() => {
                    crate::live_index::search::PathScope::Prefix(prefix.to_string())
                }
                _ => crate::live_index::search::PathScope::Any,
            };
            let cap = cross_project_result_cap(input.limit);
            // The same per-project bound the single-project path applies
            // (default 20, clamped to the engine's 1..=50); the global `cap`
            // then bounds the merged total.
            let per_project_limit = input.limit.unwrap_or(20).clamp(1, 50) as usize;
            let hits = working_set.search_files(
                &targets,
                query,
                per_project_limit,
                input.include_vendor.unwrap_or(false),
                input.include_personal_tooling.unwrap_or(false),
                &path_scope,
            );
            let body = format_cross_project_files(&hits, query, multi, cap);
            Ok(apply_cross_project_token_budget(body, input.max_tokens))
        }
        other => anyhow::bail!("'{other}' is not a cross-project read verb"),
    }
}

/// Search repository knowledge over one immutable generation captured from
/// every selected session project before any extraction or formatting begins.
/// Project IDs and sections are canonically ordered, and CCR budgeting is
/// applied once to the combined response so a multi-project call has one
/// reversible result envelope.
fn execute_cross_project_knowledge(
    mut input: SearchKnowledgeInput,
    targets: Targets,
    project_indexes: &HashMap<
        String,
        crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
    >,
    ccr_server: &SymForgeServer,
) -> anyhow::Result<String> {
    let mut selected_ids: Vec<String> = match targets {
        Targets::One(id) => vec![id],
        Targets::Subset(ids) => ids,
        Targets::All => project_indexes.keys().cloned().collect(),
    };
    selected_ids.sort();
    selected_ids.dedup();

    let missing: Vec<String> = selected_ids
        .iter()
        .filter(|id| !project_indexes.contains_key(*id))
        .cloned()
        .collect();
    if !missing.is_empty() {
        anyhow::bail!(
            "project not open: {}. Open it in this session first with \
             index_folder(path=...) — the default spelling opens AND activates it; add=true opens additively.",
            missing
                .iter()
                .map(|id| format!("'{id}'"))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }

    // Targeting is daemon/session metadata, not a per-project search input.
    input.project = None;
    input.projects = None;
    let max_tokens = input.max_tokens;

    // Capture every source root first. Pinning the WHOLE source-set Arc per
    // project (not just its current lane) keeps the response immutable — no
    // watcher publication after this point can split it between generations —
    // and lets `search_scoped` compose the P1 ref/worktree lanes when
    // `source_scope` is `local_refs`/`worktrees`/`all` (L-R09/L-G06). With
    // `source_scope` `None`/`current`, `search_scoped` delegates to
    // `search_current` on the captured current lane, so the default path stays
    // byte-identical.
    let captured: Vec<_> = selected_ids
        .iter()
        .map(|id| {
            let source_set = project_indexes
                .get(id)
                .expect("selected projects were validated")
                .data_plane()
                .published_source_set();
            (id.clone(), source_set)
        })
        .collect();

    let multi = captured.len() > 1;
    let mut sections = Vec::with_capacity(captured.len());
    for (project_id, source_set) in captured {
        let result = crate::protocol::knowledge_search::search_scoped(&source_set, &input);
        if multi {
            sections.push(format!("── project: {project_id} ──\n{result}"));
        } else {
            sections.push(result);
        }
    }
    let body = sections.join("\n\n");
    Ok(ccr_server.apply_ccr_budget("search_knowledge", body, max_tokens))
}

/// Review repository knowledge over one immutable generation captured from
/// every selected project. Per-source complete-plan hashes are computed before
/// any rendering budget and the top-level hash covers the canonical source set.
fn execute_cross_project_review(
    mut input: ReviewKnowledgeInput,
    targets: Targets,
    project_indexes: &HashMap<
        String,
        crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
    >,
    ccr_server: &SymForgeServer,
) -> anyhow::Result<String> {
    let mut selected_ids: Vec<String> = match targets {
        Targets::One(id) => vec![id],
        Targets::Subset(ids) => ids,
        Targets::All => project_indexes.keys().cloned().collect(),
    };
    selected_ids.sort();
    selected_ids.dedup();

    let missing: Vec<String> = selected_ids
        .iter()
        .filter(|id| !project_indexes.contains_key(*id))
        .cloned()
        .collect();
    if !missing.is_empty() {
        anyhow::bail!(
            "project not open: {}. Open it in this session first with \
             index_folder(path=...) — the default spelling opens AND activates it; add=true opens additively.",
            missing
                .iter()
                .map(|id| format!("'{id}'"))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }

    input.project = None;
    input.projects = None;
    let max_tokens = input.max_tokens;
    // Pin the WHOLE source-set Arc per project so `review_scoped` can compose
    // the P1 ref/worktree lanes under `source_scope`
    // `local_refs`/`worktrees`/`all` (L-R09/L-G06). A per-source
    // unavailable/empty lane is a typed section INSIDE `review_scoped`, not a
    // whole-scope failure; the outer `?` only surfaces a genuine whole-scope
    // error (e.g. `no_sources_in_scope`). With `source_scope` `None`/`current`,
    // `review_scoped` delegates to `review_current` on the captured current
    // lane, so the default multi-project top-level hash and per-project sections
    // stay byte-identical.
    let captured: Vec<_> = selected_ids
        .iter()
        .map(|id| {
            let source_set = project_indexes
                .get(id)
                .expect("selected projects were validated")
                .data_plane()
                .published_source_set();
            (id.clone(), source_set)
        })
        .collect();

    let mut plans = Vec::with_capacity(captured.len());
    for (project_id, source_set) in captured {
        let output = crate::protocol::knowledge_review::review_scoped(&source_set, &input)
            .map_err(anyhow::Error::msg)?;
        plans.push((project_id, output));
    }
    let top_result_hash = if plans.len() == 1 {
        plans[0].1.result_hash.clone()
    } else {
        crate::protocol::knowledge_review::combined_result_hash(
            &plans
                .iter()
                .map(|(_, output)| (output.source_key.clone(), output.review_hash.clone()))
                .collect::<Vec<_>>(),
        )
    };
    let multi = plans.len() > 1;
    let sections = plans
        .iter()
        .map(|(project_id, output)| {
            if multi {
                format!("── project: {project_id} ──\n{}", output.source_section)
            } else {
                output.source_section.clone()
            }
        })
        .collect::<Vec<_>>()
        .join("\n\n");
    let budget_sections = plans
        .iter()
        .map(|(project_id, output)| {
            if multi {
                format!(
                    "── project: {project_id} ──\n{}",
                    output.budget_source_section
                )
            } else {
                output.budget_source_section.clone()
            }
        })
        .collect::<Vec<_>>()
        .join("\n\n");
    let body = format!("top_result_hash={top_result_hash}\n{sections}");
    let budget_body = format!("top_result_hash={top_result_hash}\n{budget_sections}");
    Ok(ccr_server.apply_ccr_budget_with_summary("review_knowledge", body, budget_body, max_tokens))
}

/// Format cross-project file hits, grouped by project (`── project: <id> ──`
/// headers when `multi`). Each project's hits arrive already rank-ordered from
/// the per-project file search.
///
/// BOUNDED: at most `cap` hits are rendered across all projects (the shared
/// cross-project total cap); a surplus is dropped and disclosed honestly with
/// shown/total counts and the corrective hint.
fn format_cross_project_files(
    hits: &[crate::live_index::view::ProjectHit<crate::live_index::SearchFilesHit>],
    query: &str,
    multi: bool,
    cap: usize,
) -> String {
    if hits.is_empty() {
        return format!("No files matching '{query}' in the targeted project(s).");
    }
    let total = hits.len();
    let shown = total.min(cap);
    let mut out = String::new();
    if shown < total {
        out.push_str(&format!(
            "{shown} of {total} file matches across projects (truncated; cross-project results \
             are capped — pass a larger `limit` or query a single project for the full set)\n"
        ));
    } else {
        out.push_str(&format!("{total} file matches across projects\n"));
    }
    let mut current: Option<&str> = None;
    for ph in hits.iter().take(shown) {
        if multi && current != Some(ph.project_id.as_str()) {
            current = Some(ph.project_id.as_str());
            out.push_str(&format!(
                "\n\u{2500}\u{2500} project: {} \u{2500}\u{2500}\n",
                ph.project_id
            ));
        }
        let h = &ph.hit;
        match &h.metadata_reason {
            Some(reason) => out.push_str(&format!("  {} [metadata-only: {reason}]\n", h.path)),
            None => out.push_str(&format!("  {}\n", h.path)),
        }
    }
    out
}

/// Format cross-project symbol hits, grouped by project (`── project: <id> ──`
/// headers when `multi`). Within a project, hits arrive already tier-sorted from
/// the view search.
///
/// BOUNDED: at most `cap` hits are rendered across all projects (the shared
/// cross-project total cap). When `hits.len() > cap` the surplus is dropped and
/// the truncation is disclosed honestly (Principle III) with the shown/total
/// counts and the corrective hint. The cap is applied in working-set/tier order,
/// so the highest-ranked hits per project survive the cut.
fn format_cross_project_symbols(
    hits: &[crate::live_index::view::ProjectHit<crate::live_index::view::ViewSymbolHit>],
    query: &str,
    multi: bool,
    cap: usize,
) -> String {
    if hits.is_empty() {
        return format!("No symbols matching '{query}' in the targeted project(s).");
    }
    let total = hits.len();
    let shown = total.min(cap);
    let mut out = String::new();
    let mut current: Option<&str> = None;
    if shown < total {
        out.push_str(&format!(
            "{shown} of {total} matches across projects (truncated; cross-project results \
             are capped — pass a larger `limit` or query a single project for the full set)\n"
        ));
    } else {
        out.push_str(&format!("{total} matches across projects\n"));
    }
    for ph in hits.iter().take(shown) {
        if multi && current != Some(ph.project_id.as_str()) {
            current = Some(ph.project_id.as_str());
            out.push_str(&format!(
                "\n\u{2500}\u{2500} project: {} \u{2500}\u{2500}\n",
                ph.project_id
            ));
        }
        let h = &ph.hit;
        out.push_str(&format!(
            "  {}: {} {}  ({})\n",
            h.line, h.kind, h.name, h.path
        ));
    }
    out
}

/// Format cross-project text-search results, grouped by project. Each project's
/// `TextSearchResult` renders its files and per-line matches.
///
/// BOUNDED: at most `cap` per-line matches are rendered across all files in all
/// projects (the unbounded element here is the cumulative match-line count, not
/// the file count). Once `cap` lines have been emitted, the rest are dropped and
/// the truncation disclosed (shown/total + corrective hint). A project/file with
/// no remaining budget is skipped, so headers are only emitted for content that
/// is actually rendered.
fn format_cross_project_text(
    results: &[crate::live_index::view::ProjectHit<crate::live_index::search::TextSearchResult>],
    multi: bool,
    cap: usize,
) -> String {
    let total: usize = results.iter().map(|ph| ph.hit.total_matches).sum();
    if total == 0 {
        let excluded: usize = results
            .iter()
            .map(|ph| ph.hit.excluded_knowledge_files)
            .sum();
        return crate::protocol::format::append_excluded_knowledge_note(
            "No text matches in the targeted project(s).".to_string(),
            excluded,
        );
    }

    // Render into a body first while counting emitted match lines, so the header
    // can honestly state shown-vs-total once we know how many we actually wrote.
    let mut body = String::new();
    let mut shown = 0usize;
    'projects: for ph in results {
        if ph.hit.files.is_empty() {
            continue;
        }
        let mut header_written = false;
        for file in &ph.hit.files {
            if file.matches.is_empty() {
                continue;
            }
            if shown >= cap {
                break 'projects;
            }
            // Emit the project header lazily, only when this project contributes
            // at least one rendered line within budget.
            if multi && !header_written {
                body.push_str(&format!(
                    "\n\u{2500}\u{2500} project: {} \u{2500}\u{2500}\n",
                    ph.project_id
                ));
                header_written = true;
            }
            body.push_str(&format!("{}\n", file.path));
            for m in &file.matches {
                if shown >= cap {
                    break 'projects;
                }
                body.push_str(&format!("  {}: {}\n", m.line_number, m.line));
                shown += 1;
            }
        }
    }

    let mut out = String::new();
    if shown < total {
        out.push_str(&format!(
            "{shown} of {total} text matches across projects (truncated; cross-project results \
             are capped — pass a larger `limit` or query a single project for the full set)\n"
        ));
    } else {
        out.push_str(&format!("{total} text matches across projects\n"));
    }
    out.push_str(&body);
    out
}

/// Format cross-project reference hits, grouped by project.
///
/// BOUNDED: at most `cap` reference hits are rendered across all projects; the
/// surplus is dropped and the truncation disclosed (shown/total + corrective
/// hint), mirroring [`format_cross_project_symbols`].
fn format_cross_project_references(
    hits: &[crate::live_index::view::ProjectHit<(String, crate::domain::ReferenceRecord)>],
    name: &str,
    multi: bool,
    cap: usize,
) -> String {
    if hits.is_empty() {
        return format!("No references to '{name}' in the targeted project(s).");
    }
    let total = hits.len();
    let shown = total.min(cap);
    let mut out = String::new();
    let mut current: Option<&str> = None;
    if shown < total {
        out.push_str(&format!(
            "{shown} of {total} references across projects (truncated; cross-project results \
             are capped — pass a larger `limit` or query a single project for the full set)\n"
        ));
    } else {
        out.push_str(&format!("{total} references across projects\n"));
    }
    for ph in hits.iter().take(shown) {
        if multi && current != Some(ph.project_id.as_str()) {
            current = Some(ph.project_id.as_str());
            out.push_str(&format!(
                "\n\u{2500}\u{2500} project: {} \u{2500}\u{2500}\n",
                ph.project_id
            ));
        }
        let (path, reference) = &ph.hit;
        // `line_range` is zero-indexed in the engine; display 1-based.
        out.push_str(&format!(
            "  {}:{} [{:?}] {}\n",
            path,
            reference.line_range.0 + 1,
            reference.kind,
            reference.name
        ));
    }
    out
}

fn strip_cross_project_targeting(mut params: serde_json::Value) -> serde_json::Value {
    if let serde_json::Value::Object(ref mut object) = params {
        object.remove("project");
        object.remove("projects");
    }
    params
}

async fn execute_tool_call(
    runtime: SessionRuntime,
    tool_name: &str,
    mut params: serde_json::Value,
) -> anyhow::Result<String> {
    runtime.token_stats.record_tool_call(tool_name);

    // Feature 012 (Phase 3): cross-project READ route. For the three read verbs
    // ONLY, peek the `project`/`projects` params and resolve a `Targets`. When it
    // is the single active project (the default — both params omitted — or an
    // explicit `project=<active id>`), fall through to the UNCHANGED per-project
    // dispatch below (byte-identical no-regression). Any other target shape
    // (`Subset`, `All`, or a single non-active project) is served here from the
    // session's working set with attributed `── project: <id> ──` output. Edits,
    // analyze_file_impact, orient, and meta verbs are NEVER routed here — they
    // stay single-project on the active project (cross-project writes deferred).
    if is_cross_project_read_verb(tool_name) {
        #[derive(serde::Deserialize)]
        struct CrossProjectPeek {
            #[serde(default)]
            project: Option<String>,
            #[serde(default)]
            projects: Option<Vec<String>>,
        }
        // A lenient peek: unrelated/invalid sibling fields must NOT make the real
        // tool call fail here, so only the two targeting fields are extracted. A
        // genuine targeting CONTRACT violation (e.g. both params set) IS surfaced
        // as an error here — the freshness gate (`resolve_cross_project_targets`)
        // swallows that same error, so it never refreshes for an invalid call.
        let peek: CrossProjectPeek =
            serde_json::from_value(params.clone()).unwrap_or(CrossProjectPeek {
                project: None,
                projects: None,
            });
        let targets = resolve_targets(
            peek.project.as_deref(),
            peek.projects.as_deref(),
            &runtime.project_id,
        )
        .map_err(|message| anyhow::anyhow!("{message}"))?;
        if !targets_is_single_active(&targets, &runtime.project_id) {
            if tool_name == "search_knowledge" {
                let input = decode_params::<SearchKnowledgeInput>(params)?;
                return execute_cross_project_knowledge(
                    input,
                    targets,
                    &runtime.project_indexes,
                    &runtime.server,
                );
            }
            if tool_name == "review_knowledge" {
                let input = decode_params::<ReviewKnowledgeInput>(params)?;
                return execute_cross_project_review(
                    input,
                    targets,
                    &runtime.project_indexes,
                    &runtime.server,
                );
            }
            let working_set = runtime.working_set.read();
            return execute_cross_project_read(tool_name, params, targets, &working_set);
        }
        // else: single active project -> fall through to the unchanged path. The
        // worker is intentionally local-only and refuses any `project`/`projects`
        // field, so erase the already-resolved targeting hint before dispatch.
        params = strip_cross_project_targeting(params);
    }

    // Use the cached server from ProjectInstance (cloned cheaply via Arc internals)
    // instead of constructing a new SymForgeServer per tool call.
    let server = runtime.server;

    match tool_name {
        "get_symbol" => Ok(server
            .get_symbol(Parameters(decode_params::<GetSymbolInput>(params)?))
            .await),
        "get_repo_map" => Ok(server
            .get_repo_map(Parameters(decode_params::<GetRepoMapInput>(params)?))
            .await),
        "get_file_context" => Ok(server
            .get_file_context(Parameters(decode_params::<GetFileContextInput>(params)?))
            .await),
        "get_symbol_context" => Ok(server
            .get_symbol_context(Parameters(decode_params::<GetSymbolContextInput>(params)?))
            .await),
        "analyze_file_impact" => Ok(server
            .analyze_file_impact(Parameters(decode_params::<AnalyzeFileImpactInput>(params)?))
            .await),
        "search_symbols" => Ok(server
            .search_symbols(Parameters(decode_params::<SearchSymbolsInput>(params)?))
            .await),
        "search_text" => Ok(server
            .search_text(Parameters(decode_params::<SearchTextInput>(params)?))
            .await),
        "search_knowledge" => Ok(server
            .search_knowledge(Parameters(decode_params::<SearchKnowledgeInput>(params)?))
            .await),
        "review_knowledge" => Ok(server
            .review_knowledge(Parameters(decode_params::<ReviewKnowledgeInput>(params)?))
            .await),
        "curate_knowledge" => Ok(server
            .curate_knowledge(Parameters(decode_params::<CurateKnowledgeInput>(params)?))
            .await),
        "trace_symbol" => {
            let tp: TraceSymbolInput = decode_params(params)?;
            // Convert: trace_symbol's None sections = "all" = empty vec in get_symbol_context
            let sections = tp.sections.unwrap_or_default();
            let output = server
                .get_symbol_context(Parameters(GetSymbolContextInput {
                    project: None,
                    name: tp.name,
                    file: None,
                    path: Some(tp.path),
                    symbol_kind: tp.kind,
                    symbol_line: tp.symbol_line,
                    verbosity: tp.verbosity,
                    bundle: None,
                    sections: Some(sections),
                    max_tokens: None,
                    estimate: None,
                }))
                .await;
            Ok(format!("{TRACE_SYMBOL_ALIAS_DEPRECATION}\n\n{output}"))
        }
        "inspect_match" => Ok(server
            .inspect_match(Parameters(decode_params::<InspectMatchInput>(params)?))
            .await),
        "search_files" => Ok(server
            .search_files(Parameters(decode_params::<SearchFilesInput>(params)?))
            .await),
        "health" => {
            // SF-STRESS-010: forward the quarantine paging window so the daemon
            // (which owns the authoritative index in production) renders the
            // requested registry slice instead of silently ignoring args.
            let input: HealthInput = decode_params(params)?;
            Ok(server.health_for_daemon_session(
                runtime.project_id.clone(),
                runtime.session_id.clone(),
                runtime.canonical_root.clone(),
                crate::protocol::format::QuarantineWindow::from_args(
                    input.quarantine_offset.map(|n| n as usize),
                    input.quarantine_limit.map(|n| n as usize),
                ),
            ))
        }
        "health_compact" => Ok(server.health_compact_for_daemon_session(
            runtime.project_id.clone(),
            runtime.session_id.clone(),
            runtime.canonical_root.clone(),
        )),
        "index_folder" => Ok(server
            .index_folder(Parameters(decode_params::<IndexFolderInput>(params)?))
            .await),
        "what_changed" => Ok(server
            .what_changed(Parameters(decode_params::<WhatChangedInput>(params)?))
            .await),
        "get_file_content" => Ok(server
            .get_file_content(Parameters(decode_params::<GetFileContentInput>(params)?))
            .await),
        "find_references" => Ok(server
            .find_references(Parameters(decode_params::<FindReferencesInput>(params)?))
            .await),
        "find_dependents" => Ok(server
            .find_dependents(Parameters(decode_params::<FindDependentsInput>(params)?))
            .await),
        "explore" => Ok(server
            .explore(Parameters(decode_params::<ExploreInput>(params)?))
            .await),
        "diff_symbols" => Ok(server
            .diff_symbols(Parameters(decode_params::<DiffSymbolsInput>(params)?))
            .await),
        "replace_symbol_body" => Ok(server
            .replace_symbol_body(Parameters(decode_params::<ReplaceSymbolBodyInput>(params)?))
            .await),
        "insert_symbol" => Ok(server
            .insert_symbol(Parameters(decode_params::<InsertSymbolInput>(params)?))
            .await),
        "delete_symbol" => Ok(server
            .delete_symbol(Parameters(decode_params::<DeleteSymbolInput>(params)?))
            .await),
        "edit_within_symbol" => Ok(server
            .edit_within_symbol(Parameters(decode_params::<EditWithinSymbolInput>(params)?))
            .await),
        "batch_edit" => Ok(server
            .batch_edit(Parameters(decode_params::<BatchEditInput>(params)?))
            .await),
        "batch_rename" => Ok(server
            .batch_rename(Parameters(decode_params::<BatchRenameInput>(params)?))
            .await),
        "batch_insert" => Ok(server
            .batch_insert(Parameters(decode_params::<BatchInsertInput>(params)?))
            .await),
        "validate_file_syntax" => Ok(server
            .validate_file_syntax(Parameters(decode_params::<ValidateFileSyntaxInput>(
                params,
            )?))
            .await),
        "conventions" => Ok(server.conventions().await),
        "edit_plan" => Ok(server
            .edit_plan(Parameters(decode_params::<EditPlanInput>(params)?))
            .await),
        "investigation_suggest" => Ok(server
            .investigation_suggest(Parameters(decode_params::<InvestigationInput>(params)?))
            .await),
        "context_inventory" => Ok(server.context_inventory().await),
        "symforge_retrieve" => Ok(server
            .symforge_retrieve(Parameters(decode_params::<SymforgeRetrieveInput>(params)?))
            .await),
        "ask" => Ok(server
            .ask(Parameters(decode_params::<SmartQueryInput>(params)?))
            .await),
        "checkpoint_now" => Ok(server
            .checkpoint_now(Parameters(decode_params::<CheckpointNowInput>(params)?))
            .await),
        "detect_impact" => Ok(server
            .detect_impact(Parameters(decode_params::<DetectImpactInput>(params)?))
            .await),
        // D-015-012 backward-compat alias: CBM's `detect_changes` -> `detect_impact`.
        "detect_changes" => {
            let output = server
                .detect_impact(Parameters(decode_params::<DetectImpactInput>(params)?))
                .await;
            Ok(format!("{DETECT_CHANGES_ALIAS_DEPRECATION}\n\n{output}"))
        }
        // TR-01 / FR-006: the front-end `status` tool proxies here so the readout
        // reflects the DAEMON's populated index (the one that actually serves
        // queries), not the empty front-end index. `status_for_daemon_session`
        // renders from this daemon server's own index/ledger/durable store and
        // does not re-apply the surface-env gate (the front-end owns that).
        "status" => Ok(server
            .status_for_daemon_session(&decode_params::<crate::stel::StelStatusRequest>(params)?)),
        other => anyhow::bail!("unknown tool '{other}'"),
    }
}

fn sidecar_state_for_runtime(runtime: &SessionRuntime) -> SidecarState {
    SidecarState {
        index: crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(
            runtime.index.shared(),
        ),
        token_stats: Arc::clone(&runtime.token_stats),
        repo_root: Some(runtime.canonical_root.clone()),
        symbol_cache: Arc::clone(&runtime.symbol_cache),
    }
}

fn decode_params<T>(params: serde_json::Value) -> anyhow::Result<T>
where
    T: serde::de::DeserializeOwned,
{
    serde_json::from_value(params).context("invalid tool parameters")
}

fn bad_request(error: anyhow::Error) -> (axum::http::StatusCode, String) {
    (axum::http::StatusCode::BAD_REQUEST, error.to_string())
}

fn internal_error(error: tokio::task::JoinError) -> (axum::http::StatusCode, String) {
    (
        axum::http::StatusCode::INTERNAL_SERVER_ERROR,
        error.to_string(),
    )
}

fn canonical_project_root(root: &Path) -> anyhow::Result<PathBuf> {
    root.canonicalize()
        .with_context(|| format!("failed to canonicalize project root {}", root.display()))
}

pub(crate) fn project_key(root: &Path) -> String {
    crate::discovery::project_id_for_canonical_root(root).0
}

pub(crate) fn normalized_path_text(path_text: &str, windows: bool) -> String {
    if windows {
        path_text.replace('\\', "/")
    } else {
        path_text.to_string()
    }
}

pub(crate) fn normalized_path_string(path: &Path) -> String {
    normalized_path_text(&dunce::simplified(path).to_string_lossy(), cfg!(windows))
}

fn process_control_state_dir() -> io::Result<&'static ControlStateDir> {
    paths::process_control_state_placement()
        .directory()
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                "process control state is unavailable",
            )
        })
}

fn daemon_dir_for(control_state_dir: &ControlStateDir) -> io::Result<PathBuf> {
    paths::ensure_control_state_dir(control_state_dir)?;
    let dir = paths::control_state_path(control_state_dir, "daemon");
    std::fs::create_dir_all(&dir)?;
    Ok(dir)
}

fn write_daemon_port_file_at(control_state_dir: &ControlStateDir, port: u16) -> io::Result<()> {
    let path = daemon_dir_for(control_state_dir)?.join(daemon_port_file_name());
    std::fs::write(&path, port.to_string()).map_err(|e| {
        io::Error::new(
            e.kind(),
            format!("writing daemon port file at {}: {}", path.display(), e),
        )
    })
}

fn write_daemon_pid_file_at(control_state_dir: &ControlStateDir, pid: u32) -> io::Result<()> {
    let path = daemon_dir_for(control_state_dir)?.join(daemon_pid_file_name());
    std::fs::write(&path, pid.to_string()).map_err(|e| {
        io::Error::new(
            e.kind(),
            format!("writing daemon pid file at {}: {}", path.display(), e),
        )
    })
}

fn read_daemon_pid_file_at(control_state_dir: &ControlStateDir) -> io::Result<u32> {
    let contents = read_daemon_runtime(
        &daemon_dir_for(control_state_dir)?,
        &daemon_pid_file_name(),
        LEGACY_DAEMON_PID_FILE,
    )?;
    contents
        .trim()
        .parse::<u32>()
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}

pub(crate) fn read_daemon_port_file() -> io::Result<u16> {
    read_daemon_port_file_at(process_control_state_dir()?)
}

/// This process's pid when it is a daemon that is NO LONGER the recorded one —
/// an ORPHAN: still alive, still answering everyone already connected, but
/// undiscoverable, so its index silently diverges from the daemon new clients
/// reach.
///
/// Orphans are routine, not exotic. `stop_incompatible_recorded_daemon_at`
/// cleans up the runtime files whether or not the incompatible daemon actually
/// died — the safety gate refuses on a pid/executable mismatch, and
/// `terminate_process` can simply fail — so the survivor keeps serving with no
/// record pointing at it. Upgrading symforge is the common trigger, because the
/// version check makes the running daemon "incompatible"; a session that
/// updates several times can accumulate several orphans, each holding a full
/// index.
///
/// Callers cannot otherwise tell which instance answered them, which is what
/// makes this worth disclosing: an orphan's replies are internally consistent
/// and confidently wrong about the world.
///
/// `None` for the recorded daemon and for every non-daemon process.
pub(crate) fn unrecorded_daemon_pid() -> Option<u32> {
    if !DAEMON_BOUND.load(std::sync::atomic::Ordering::Acquire) {
        return None;
    }
    let me = std::process::id();
    let recorded = process_control_state_dir()
        .ok()
        .and_then(|dir| read_daemon_pid_file_at(dir).ok());
    match recorded {
        Some(pid) if pid == me => None,
        // Either another daemon owns the record, or the record is gone
        // entirely (the cleanup-regardless path above). Both mean new clients
        // cannot reach us.
        _ => Some(me),
    }
}

fn read_daemon_port_file_at(control_state_dir: &ControlStateDir) -> io::Result<u16> {
    let contents = read_daemon_runtime(
        &daemon_dir_for(control_state_dir)?,
        &daemon_port_file_name(),
        LEGACY_DAEMON_PORT_FILE,
    )?;
    contents
        .trim()
        .parse::<u16>()
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}

#[cfg(test)]
fn cleanup_daemon_files_at(control_state_dir: &ControlStateDir) {
    cleanup_daemon_runtime_files_at(control_state_dir);
    if let Ok(dir) = daemon_dir_for(control_state_dir) {
        let _ = std::fs::remove_file(dir.join(daemon_start_lock_file_name()));
        let _ = std::fs::remove_file(dir.join(LEGACY_DAEMON_START_LOCK_FILE));
    }
}

/// Shutdown-side cleanup that removes a runtime file ONLY when its content
/// still identifies THIS daemon. A dying daemon's graceful shutdown can race a
/// successor that already wrote fresh port/token/pid files into the same
/// `daemon_dir()`; unconditional removal here deletes the successor's files,
/// leaving clients tokenless (401) or daemon-less — the 2026-07-11 fork-bomb
/// incident's inner trigger. Startup cleanup stays unconditional (there is no
/// live owner to protect before the new files are written).
fn cleanup_daemon_runtime_files_if_owner_at(
    control_state_dir: &ControlStateDir,
    port: u16,
    pid: u32,
    token: &str,
) {
    if let Ok(dir) = daemon_dir_for(control_state_dir) {
        let owns = |path: &std::path::Path, expected: &str| {
            std::fs::read_to_string(path)
                .map(|contents| contents.trim() == expected)
                .unwrap_or(false)
        };
        let port_path = dir.join(daemon_port_file_name());
        if owns(&port_path, &port.to_string()) {
            let _ = std::fs::remove_file(&port_path);
        }
        let pid_path = dir.join(daemon_pid_file_name());
        if owns(&pid_path, &pid.to_string()) {
            let _ = std::fs::remove_file(&pid_path);
        }
        let token_path = dir.join(daemon_token_file_name());
        if owns(&token_path, token) {
            let _ = std::fs::remove_file(&token_path);
        }
        // Legacy untagged names are never written by current builds; removing
        // them can only clear stale artifacts.
        let _ = std::fs::remove_file(dir.join(LEGACY_DAEMON_PORT_FILE));
        let _ = std::fs::remove_file(dir.join(LEGACY_DAEMON_PID_FILE));
    }
}

fn cleanup_daemon_runtime_files_at(control_state_dir: &ControlStateDir) {
    if let Ok(dir) = daemon_dir_for(control_state_dir) {
        let _ = std::fs::remove_file(dir.join(daemon_port_file_name()));
        let _ = std::fs::remove_file(dir.join(daemon_pid_file_name()));
        // Remove the auth-token file too so a stale token from a previous daemon
        // can never be presented to (or mistaken for) a newly spawned daemon.
        let _ = std::fs::remove_file(dir.join(daemon_token_file_name()));
        let _ = std::fs::remove_file(dir.join(LEGACY_DAEMON_PORT_FILE));
        let _ = std::fs::remove_file(dir.join(LEGACY_DAEMON_PID_FILE));
    }
}

#[allow(unsafe_code)] // Unix process signaling requires libc::kill; Windows uses taskkill.
pub(crate) fn terminate_process(pid: u32) -> io::Result<()> {
    #[cfg(windows)]
    {
        let status = crate::process_util::hidden_command("taskkill")
            .args(["/PID", &pid.to_string(), "/T", "/F"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()?;
        // Treat "process not found" (exit code 128) as success (idempotent)
        if status.success() || status.code() == Some(128) {
            Ok(())
        } else {
            Err(io::Error::other(format!(
                "taskkill exited with status {status}"
            )))
        }
    }

    #[cfg(not(windows))]
    {
        let result = unsafe { libc::kill(pid as i32, libc::SIGTERM) };
        if result == 0 {
            // Signal sent — poll briefly for exit
            for _ in 0..10 {
                std::thread::sleep(std::time::Duration::from_millis(100));
                if unsafe { libc::kill(pid as i32, 0) } != 0 {
                    return Ok(());
                }
            }
            Ok(()) // Sent signal, process may still be shutting down
        } else {
            let errno = std::io::Error::last_os_error();
            if errno.raw_os_error() == Some(libc::ESRCH) {
                Ok(()) // Already dead — idempotent success
            } else {
                Err(errno)
            }
        }
    }
}

fn unix_seconds(time: SystemTime) -> u64 {
    time.duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsString;
    use std::path::{Path, PathBuf};
    use std::sync::atomic::AtomicUsize;
    use std::time::Duration;

    use once_cell::sync::Lazy;
    use tempfile::TempDir;
    use tokio::sync::{Mutex, MutexGuard};

    static ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    #[test]
    fn normalized_path_text_treats_backslash_as_separator_only_on_windows() {
        let path_text = "/tmp/symforge-literal\\component";

        assert_eq!(
            normalized_path_text(path_text, false),
            path_text,
            "Unix path text must preserve a literal backslash"
        );
        assert_eq!(
            normalized_path_text(path_text, true),
            "/tmp/symforge-literal/component",
            "Windows path text must retain forward-slash wire compatibility"
        );
    }

    #[test]
    fn executable_identity_preserves_literal_backslash_on_unix_policy() {
        let literal = "/work/symforge\\helper";
        let nested = "/work/symforge/helper";

        assert_ne!(
            stable_path_identity_for_platform(literal, false),
            stable_path_identity_for_platform(nested, false),
            "distinct Unix executable paths must not share one stable identity"
        );
        assert_ne!(
            daemon_executable_file_name_for_platform(literal, false),
            daemon_executable_file_name_for_platform(nested, false),
            "a Unix backslash remains part of the executable file name"
        );
        assert_eq!(
            stable_path_identity_for_platform(literal, true),
            stable_path_identity_for_platform(nested, true),
            "Windows separator compatibility must remain intact"
        );
    }

    #[cfg(unix)]
    #[test]
    fn normalized_path_string_preserves_literal_backslash_components() {
        let path = Path::new("/tmp/symforge-literal\\component");

        assert_eq!(
            normalized_path_string(path),
            path.to_string_lossy(),
            "a Unix backslash is a filename byte, not a path separator"
        );
        assert_ne!(
            normalized_path_string(path),
            "/tmp/symforge-literal/component",
            "distinct Unix roots must not collapse onto one wire identity"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn daemon_session_open_refuses_non_utf8_roots_before_transport() {
        use std::os::unix::ffi::OsStringExt as _;

        let parent = TempDir::new().expect("non-UTF-8 project parent");
        let root = parent
            .path()
            .join(std::ffi::OsString::from_vec(vec![b'a', 0xff, b'b']));
        std::fs::create_dir_all(&root).expect("create non-UTF-8 project root");
        let control = TempDir::new().expect("isolated daemon control root");
        // ponytail: match instead of expect_err — DaemonSessionClient has no Debug impl,
        // and this cfg(unix) body only ever compiles on Linux CI.
        let error = match connect_or_spawn_session_at(
            &root,
            "non-utf8-root-test",
            Some(std::process::id()),
            &test_control_state(control.path()),
        )
        .await
        {
            Ok(_) => panic!("lossy project identity must be refused before daemon discovery"),
            Err(error) => error,
        };

        assert!(
            error.to_string().contains("not valid UTF-8"),
            "the refusal must identify the non-reversible root encoding: {error:#}"
        );
    }

    /// Every structural-edit surface must be single-project routed. The compact
    /// `symforge_edit` facade was omitted from this list while the legacy edit
    /// tools were covered, so its `project` selector was accepted and ignored:
    /// an edit aimed at an opened sibling project fell back to the session home
    /// and mutated the wrong repository when paths/symbols overlapped.
    #[test]
    fn every_structural_edit_tool_is_single_project_routed() {
        for tool in [
            "replace_symbol_body",
            "edit_within_symbol",
            "insert_symbol",
            "delete_symbol",
            "batch_edit",
            "batch_insert",
            "batch_rename",
            "symforge_edit",
        ] {
            assert!(
                single_project_routed_tool(tool),
                "{tool} accepts a `project` selector but is not single-project routed"
            );
        }
    }

    fn project_dir(name: &str) -> TempDir {
        let dir = TempDir::with_prefix(name).expect("temp dir");
        std::fs::create_dir_all(dir.path().join("src")).expect("src dir");
        dir
    }

    fn test_control_state(home: &Path) -> ControlStateDir {
        ControlStateDir::new(home.to_path_buf())
    }

    fn test_daemon_path(home: &Path, file_name: impl AsRef<Path>) -> PathBuf {
        daemon_dir_for(&test_control_state(home))
            .expect("create test daemon control-state directory")
            .join(file_name)
    }

    async fn spawn_test_daemon(bind_host: &str, home: &Path) -> anyhow::Result<DaemonHandle> {
        let control_state_dir = test_control_state(home);
        spawn_daemon_at(bind_host, &control_state_dir).await
    }

    fn test_daemon_state(home: &Path) -> DaemonState {
        DaemonState::with_token_at(establish_daemon_auth_token(), test_control_state(home))
    }

    async fn env_lock() -> MutexGuard<'static, ()> {
        ENV_LOCK.lock().await
    }

    /// Build a reqwest client that authenticates every request against the now
    /// fail-closed daemon by attaching the daemon's established token as a
    /// default `Authorization: Bearer` header. The daemon ALWAYS has a token
    /// (generated when no env pin is set), so functional tests that exercise the
    /// real handshake must present it — `authorize_daemon_request` is strict.
    fn authed_client(handle: &DaemonHandle) -> reqwest::Client {
        let token = handle.state.auth_token.clone();
        let headers = bearer_headers(&token);
        reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .expect("build authed reqwest client")
    }

    fn bearer_headers(token: &str) -> HeaderMap {
        let mut headers = header::HeaderMap::new();
        let mut value =
            header::HeaderValue::from_str(&format!("Bearer {token}")).expect("valid bearer header");
        value.set_sensitive(true);
        headers.insert(header::AUTHORIZATION, value);
        headers
    }

    #[tokio::test]
    async fn daemon_idle_shutdown_env_parsing() {
        let _guard = env_lock().await;
        // Unset: an explicitly managed daemon remains persistent.
        {
            let _env = EnvVarGuard::unset(DAEMON_IDLE_SHUTDOWN_ENV);
            assert_eq!(daemon_idle_shutdown_from_env(), None);
        }
        // Explicit 0 disables idle shutdown entirely.
        {
            let _env = EnvVarGuard::set_str(DAEMON_IDLE_SHUTDOWN_ENV, "0");
            assert_eq!(daemon_idle_shutdown_from_env(), None);
        }
        // Sub-minimum values clamp up to 60s.
        {
            let _env = EnvVarGuard::set_str(DAEMON_IDLE_SHUTDOWN_ENV, "5");
            assert_eq!(
                daemon_idle_shutdown_from_env(),
                Some(Duration::from_secs(60))
            );
        }
        // Garbage falls back to the default rather than disabling the guard.
        {
            let _env = EnvVarGuard::set_str(DAEMON_IDLE_SHUTDOWN_ENV, "soon");
            assert_eq!(
                daemon_idle_shutdown_from_env(),
                Some(Duration::from_secs(DEFAULT_DAEMON_IDLE_SHUTDOWN_SECS))
            );
        }
    }

    /// Commit `bytes` at `rel` into `repository`'s working tree + HEAD. Mirrors the
    /// local_ref_scout test helper; used to give the reconcile a real tree to scout.
    fn ref_lane_commit(
        repository: &git2::Repository,
        root: &Path,
        rel: &str,
        bytes: &[u8],
        message: &str,
    ) {
        let full = root.join(rel);
        if let Some(parent) = full.parent() {
            std::fs::create_dir_all(parent).expect("mkdir");
        }
        std::fs::write(&full, bytes).expect("write file");
        let mut index = repository.index().expect("index");
        index
            .add_all(["*"], git2::IndexAddOption::DEFAULT, None)
            .expect("stage");
        index.write().expect("write index");
        let tree_id = index.write_tree().expect("write tree");
        let tree = repository.find_tree(tree_id).expect("find tree");
        let signature =
            git2::Signature::now("SymForge Test", "symforge@example.invalid").expect("signature");
        let parent = repository
            .head()
            .ok()
            .and_then(|head| head.peel_to_commit().ok());
        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
        repository
            .commit(
                Some("HEAD"),
                &signature,
                &signature,
                message,
                &tree,
                &parents,
            )
            .expect("commit");
    }

    /// L-G05/L-G07/L-V04: with the gate ON, opening/reloading a project publishes a
    /// P1 `symforge:git-ref:` lane for a bare local branch via the detached
    /// reconcile spawn.
    #[tokio::test]
    async fn local_ref_lanes_gate_on_publishes_bare_branch_lane() {
        let _env = env_lock().await;
        let _gate = EnvVarGuard::set_str(LOCAL_REF_LANES_ENV, "1");

        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        let repository = git2::Repository::init(root).expect("init repo");
        ref_lane_commit(
            &repository,
            root,
            "src/lib.rs",
            b"pub fn a() {}\n",
            "initial",
        );
        let head_commit = repository
            .head()
            .expect("head")
            .peel_to_commit()
            .expect("peel");
        repository
            .branch("bare-lane", &head_commit, false)
            .expect("bare branch");

        let index: SharedIndex = Arc::new(crate::live_index::SharedIndexHandle::new(
            LiveIndex::from_source_files(HashMap::new()),
        ));

        let task = spawn_local_ref_reconcile(Arc::clone(&index), root.to_path_buf())
            .expect("gate ON must spawn the reconcile task");
        task.await.expect("reconcile task completes");

        let set = index.published_source_set();
        assert!(
            set.sources
                .keys()
                .any(|id| id.as_str().starts_with("symforge:git-ref:")),
            "gate ON publishes at least one git-ref lane: {:?}",
            set.sources.keys().map(|id| id.as_str()).collect::<Vec<_>>()
        );
    }

    /// L-V02: with the gate OFF (default), the reconcile is never spawned and no
    /// `symforge:git-ref:` lane appears — the current-only path is unchanged.
    #[tokio::test]
    async fn local_ref_lanes_gate_off_publishes_no_ref_lane() {
        let _env = env_lock().await;
        let _gate = EnvVarGuard::unset(LOCAL_REF_LANES_ENV);

        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        let repository = git2::Repository::init(root).expect("init repo");
        ref_lane_commit(
            &repository,
            root,
            "src/lib.rs",
            b"pub fn a() {}\n",
            "initial",
        );
        let head_commit = repository
            .head()
            .expect("head")
            .peel_to_commit()
            .expect("peel");
        repository
            .branch("bare-lane", &head_commit, false)
            .expect("bare branch");

        let index: SharedIndex = Arc::new(crate::live_index::SharedIndexHandle::new(
            LiveIndex::from_source_files(HashMap::new()),
        ));
        let before = index.published_source_set().registry_generation;

        assert!(
            spawn_local_ref_reconcile(Arc::clone(&index), root.to_path_buf()).is_none(),
            "gate OFF must not spawn a reconcile task"
        );

        let set = index.published_source_set();
        assert!(
            !set.sources
                .keys()
                .any(|id| id.as_str().starts_with("symforge:git-ref:")),
            "gate OFF publishes no git-ref lane"
        );
        assert_eq!(
            set.registry_generation, before,
            "gate OFF leaves the published source map untouched"
        );
    }

    /// The env gate parses `1`/`true`/`on` (case-insensitive) as ON and everything
    /// else — including unset — as OFF.
    #[tokio::test]
    async fn local_ref_lanes_env_gate_parsing() {
        let _guard = env_lock().await;
        {
            let _env = EnvVarGuard::unset(LOCAL_REF_LANES_ENV);
            assert!(!local_ref_lanes_enabled(), "unset is OFF");
        }
        for on in ["1", "true", "on", "TRUE", "On", " on "] {
            let _env = EnvVarGuard::set_str(LOCAL_REF_LANES_ENV, on);
            assert!(local_ref_lanes_enabled(), "{on:?} is ON");
        }
        for off in ["0", "false", "off", "no", "", "2"] {
            let _env = EnvVarGuard::set_str(LOCAL_REF_LANES_ENV, off);
            assert!(!local_ref_lanes_enabled(), "{off:?} is OFF");
        }
    }

    #[tokio::test(start_paused = true)]
    async fn daemon_idle_shutdown_waits_for_authenticated_activity_then_notifies() {
        let _guard = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let _idle = EnvVarGuard::set_str(DAEMON_IDLE_SHUTDOWN_ENV, "60");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let state = Arc::clone(&handle.state);
        tokio::task::yield_now().await;

        // Do not backdate before the in-flight GET: paused-time auto-advance can
        // fire the 15 s reaper interval while last_activity_at is still stale.
        authed_client(&handle)
            .get(format!("http://127.0.0.1:{}/v1/projects", handle.port))
            .send()
            .await
            .expect("authenticated request")
            .error_for_status()
            .expect("authenticated status");

        tokio::time::advance(Duration::from_secs(15)).await;
        // Reaper tick is driven by advance above. Duration::ZERO observes the
        // Notify without a 1 ms auto-advance window (virtual clock, not wall).
        assert!(
            tokio::time::timeout(Duration::ZERO, state.idle_shutdown.notified())
                .await
                .is_err(),
            "authenticated activity must defer idle shutdown"
        );

        state
            .last_activity_at
            .store(now_epoch_millis().saturating_sub(60_001), Ordering::Relaxed);
        tokio::time::advance(Duration::from_secs(15)).await;
        // Permit must already be stored: reaper runs during advance, idle check
        // uses wall-clock now_epoch_millis() against the backdated stamp above.
        state.idle_shutdown.notified().await;

        handle.reaper_task.abort();
        let _ = handle.shutdown_tx.send(());
        handle.server_task.await.expect("daemon server task");
    }

    #[tokio::test(start_paused = true)]
    async fn daemon_idle_shutdown_waits_for_in_flight_authenticated_request() {
        let _guard = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let _idle = EnvVarGuard::set_str(DAEMON_IDLE_SHUTDOWN_ENV, "60");

        let handle = spawn_daemon("127.0.0.1").await.expect("spawn daemon");
        let state = Arc::clone(&handle.state);
        tokio::task::yield_now().await;

        let activity = authorize_daemon_request(&state, &bearer_headers(&state.auth_token))
            .expect("authenticated request guard");
        state
            .last_activity_at
            .store(now_epoch_millis().saturating_sub(60_001), Ordering::Relaxed);

        tokio::time::advance(Duration::from_secs(15)).await;
        tokio::task::yield_now().await;
        assert!(
            tokio::time::timeout(Duration::from_millis(1), state.idle_shutdown.notified())
                .await
                .is_err(),
            "idle shutdown must not fire while an authenticated handler is still in flight"
        );

        drop(activity);
        assert_eq!(
            state.active_authenticated_requests.load(Ordering::Relaxed),
            0
        );

        handle.reaper_task.abort();
        let _ = handle.shutdown_tx.send(());
        handle.server_task.await.expect("daemon server task");
    }

    #[test]
    fn project_instance_load_consumes_exported_team_artifact() {
        // A teammate who just `git clone`d has `.symforge/index.bin.zst` (the
        // exported team artifact) but no local `index.bin`. The daemon's real
        // per-project bootstrap (`ProjectInstance::load`) must consume that
        // artifact — the whole point of exporting it — instead of a cold full
        // discovery+parse scan.
        let tmp = TempDir::new().expect("tempdir");
        std::fs::write(tmp.path().join("main.rs"), b"fn main() { helper(); }\n").unwrap();
        std::fs::write(tmp.path().join("helper.rs"), b"pub fn helper() {}\n").unwrap();

        // Build a fresh index and export the Best-tier team artifact. No
        // `index.bin` is written — only `index.bin.zst` + `artifact.json`.
        let fresh = live_index::LiveIndex::load(tmp.path()).expect("cold load");
        {
            let guard = fresh.read();
            let root = dunce::canonicalize(tmp.path()).expect("canonical root");
            let placement = crate::domain::StatePlacement::ProjectLocal {
                directory: crate::domain::ProjectStateDir::new(root.join(".symforge")),
            };
            live_index::persist::export_artifact(
                &guard,
                &root,
                crate::domain::SourceAccessMode::NormalProject,
                &placement,
                &crate::domain::CapabilityStatus::Available,
            )
            .expect("export artifact");
        }
        assert!(
            !tmp.path().join(".symforge").join("index.bin").exists(),
            "only the .zst team artifact should exist for the clone scenario"
        );
        assert!(
            tmp.path().join(".symforge").join("index.bin.zst").exists(),
            "the exported team artifact must be present"
        );

        // The real daemon bootstrap must restore FROM the artifact.
        let project = ProjectInstance::load(tmp.path()).expect("project load");
        {
            let guard = project.index.data_plane().read();
            assert_eq!(
                guard.load_source(),
                crate::live_index::store::IndexLoadSource::SnapshotRestore,
                "daemon bootstrap must consume the team artifact (SnapshotRestore), \
                 not fall back to a cold full scan (FreshLoad)"
            );
        }
        let root = dunce::canonicalize(tmp.path()).expect("canonical root");
        let placement = crate::domain::StatePlacement::ProjectLocal {
            directory: crate::domain::ProjectStateDir::new(root.join(".symforge")),
        };
        let snapshot =
            live_index::persist::load_snapshot(tmp.path(), &placement).expect("snapshot");
        let snapshot_mtimes = snapshot
            .files
            .iter()
            .map(|(path, file)| (path.clone(), file.mtime_secs))
            .collect();
        live_index::persist::block_on_background_verify_for_test(
            project.index.data_plane().clone(),
            tmp.path(),
            snapshot_mtimes,
        );
        let guard = project.index.data_plane().read();
        assert!(
            guard.get_file("main.rs").is_some(),
            "the artifact-restored index must serve the indexed files after verify completes"
        );
    }

    #[test]
    fn failed_project_instance_load_retires_its_admission() {
        let tmp = TempDir::new().expect("tempdir");
        let canonical_root = dunce::canonicalize(tmp.path()).expect("canonical root");
        let root_id = crate::discovery::project_id_for_canonical_root(&canonical_root);
        let state_placement = StatePlacement::ProjectLocal {
            directory: crate::domain::ProjectStateDir::new(canonical_root.join(".symforge")),
        };
        let admission = live_index::index_lifecycle::activation::admit_project_with_outcome(
            live_index::index_lifecycle::process_runtime::SurfaceKind::Daemon,
            &canonical_root,
            &root_id.0,
            SourceAccessMode::NormalProject,
            &state_placement,
        )
        .expect("admit daemon project");

        let key = live_index::index_lifecycle::registry::ProjectKey::new(root_id.0.clone());
        assert!(
            live_index::index_lifecycle::activation::process_project_registry()
                .live(&key)
                .is_ok(),
            "precondition: daemon admission is live before bootstrap cleanup"
        );

        cleanup_failed_daemon_admission(&root_id.0, admission);
        assert!(
            matches!(
                live_index::index_lifecycle::activation::process_project_registry().live(&key),
                Err(live_index::index_lifecycle::registry::RegistryRefusal::NotAdmitted)
            ),
            "a failed bootstrap must not leave a live lifecycle admission behind"
        );
    }

    #[test]
    fn joined_live_failed_project_load_retires_after_last_failed_holder() {
        let tmp = TempDir::new().expect("tempdir");
        let canonical_root = dunce::canonicalize(tmp.path()).expect("canonical root");
        let root_id = crate::discovery::project_id_for_canonical_root(&canonical_root);
        let state_placement = StatePlacement::ProjectLocal {
            directory: crate::domain::ProjectStateDir::new(canonical_root.join(".symforge")),
        };
        let first = live_index::index_lifecycle::activation::admit_project_with_outcome(
            live_index::index_lifecycle::process_runtime::SurfaceKind::Daemon,
            &canonical_root,
            &root_id.0,
            SourceAccessMode::NormalProject,
            &state_placement,
        )
        .expect("first daemon admission");
        let second = live_index::index_lifecycle::activation::admit_project_with_outcome(
            live_index::index_lifecycle::process_runtime::SurfaceKind::Daemon,
            &canonical_root,
            &root_id.0,
            SourceAccessMode::NormalProject,
            &state_placement,
        )
        .expect("second daemon admission joins the live lifecycle slot");
        assert!(
            !second.cleanup_candidate(),
            "precondition: second opener joined a slot already installed as live"
        );

        let key = live_index::index_lifecycle::registry::ProjectKey::new(root_id.0.clone());
        cleanup_failed_daemon_admission(&root_id.0, first);
        assert!(
            live_index::index_lifecycle::activation::process_project_registry()
                .live(&key)
                .is_ok(),
            "the first failed holder must not retire while another opener still holds the slot"
        );

        cleanup_failed_daemon_admission(&root_id.0, second);
        assert!(
            matches!(
                live_index::index_lifecycle::activation::process_project_registry().live(&key),
                Err(live_index::index_lifecycle::registry::RegistryRefusal::NotAdmitted)
            ),
            "the last failed holder must retire the lifecycle slot even after joining it live"
        );
    }

    #[test]
    fn daemon_sessions_share_one_project_curation_coordinator() {
        let tmp = TempDir::new().expect("tempdir");
        std::fs::write(tmp.path().join("main.rs"), b"fn main() {}\n").unwrap();
        let slot = ProjectSlot::new(ProjectInstance::load(tmp.path()).expect("project load"));

        let left = slot.server_for_session();
        let right = slot.server_for_session();

        assert!(
            Arc::ptr_eq(&left.curation_coordinator, &right.curation_coordinator),
            "all daemon sessions for one project must serialize through one curation coordinator"
        );
    }

    #[test]
    fn constant_time_eq_accepts_equal_and_rejects_unequal() {
        // Equal slices accept.
        assert!(constant_time_eq(b"sekret-token", b"sekret-token"));
        assert!(constant_time_eq(b"", b""));

        // Length mismatch rejects (and does not panic on zip of unequal lens).
        assert!(!constant_time_eq(b"short", b"longer-token"));
        assert!(!constant_time_eq(b"longer-token", b"short"));

        // Same length, differing content rejects — including a mismatch only in
        // the very last byte, which a short-circuiting `==` would reveal late.
        assert!(!constant_time_eq(b"sekret-token", b"sekret-tokeX"));
        assert!(!constant_time_eq(b"sekret-token", b"Xekret-token"));
    }

    #[test]
    fn constant_time_eq_has_no_early_out_on_first_mismatch() {
        // A correct constant-time compare must inspect the WHOLE slice even when
        // the first byte already differs. We verify there is no early return by
        // constructing two inputs that differ in byte 0 but are otherwise equal:
        // the XOR-fold accumulator must still incorporate every later byte. If
        // the implementation returned early on byte 0, flipping a later byte
        // would be unobservable; here we assert it is correctly still unequal.
        let base = vec![0u8; 64];
        let mut differ_first = base.clone();
        differ_first[0] = 1;
        assert!(!constant_time_eq(&base, &differ_first));

        // Identical except the final byte — must also reject, proving the loop
        // reaches the end rather than stopping at the first equal prefix.
        let mut differ_last = base.clone();
        differ_last[63] = 1;
        assert!(!constant_time_eq(&base, &differ_last));

        // Fully equal long slice still accepts after folding all bytes.
        assert!(constant_time_eq(&base, &base.clone()));
    }

    #[test]
    fn connection_surface_header_resolves_profile_and_ignores_junk() {
        use crate::protocol::surface_probe::{CONNECTION_SURFACE_HEADER, SurfaceProfile};

        // Absent header (older adapter / direct client) -> None -> env fallback.
        let mut headers = HeaderMap::new();
        assert_eq!(connection_surface_from_headers(&headers), None);

        // Canonical labels resolve to their profile.
        headers.insert(CONNECTION_SURFACE_HEADER, "compact".parse().unwrap());
        assert_eq!(
            connection_surface_from_headers(&headers),
            Some(SurfaceProfile::Compact)
        );
        headers.insert(CONNECTION_SURFACE_HEADER, "full".parse().unwrap());
        assert_eq!(
            connection_surface_from_headers(&headers),
            Some(SurfaceProfile::Full)
        );

        // Non-canonical value is ignored (falls back to env), never echoed.
        headers.insert(CONNECTION_SURFACE_HEADER, "garbage".parse().unwrap());
        assert_eq!(connection_surface_from_headers(&headers), None);
    }

    #[test]
    fn authorize_daemon_request_constant_time_token_check() {
        fn state_with_token(token: &str) -> SharedDaemonState {
            Arc::new(DaemonState::with_token(token.to_string()))
        }

        fn raw_auth_headers(value: &str) -> HeaderMap {
            let mut headers = HeaderMap::new();
            headers.insert(
                header::AUTHORIZATION,
                header::HeaderValue::from_str(value).expect("valid header value"),
            );
            headers
        }

        let state = state_with_token("the-real-token-value");

        // Correct token accepts.
        assert!(
            authorize_daemon_request(&state, &raw_auth_headers("Bearer the-real-token-value"))
                .is_ok()
        );
        assert_eq!(
            state.active_authenticated_requests.load(Ordering::Relaxed),
            0,
            "successful auth guard should decrement on drop"
        );

        // Wrong token (same length) still 401s — fail-closed preserved.
        assert!(
            matches!(
                authorize_daemon_request(&state, &raw_auth_headers("Bearer the-real-token-WRONG")),
                Err(StatusCode::UNAUTHORIZED)
            ),
            "wrong token must 401"
        );

        // Empty token still 401s.
        assert!(
            matches!(
                authorize_daemon_request(&state, &raw_auth_headers("Bearer ")),
                Err(StatusCode::UNAUTHORIZED)
            ),
            "empty token must 401"
        );

        // Missing Authorization header still 401s.
        assert!(
            matches!(
                authorize_daemon_request(&state, &HeaderMap::new()),
                Err(StatusCode::UNAUTHORIZED)
            ),
            "missing Authorization must 401"
        );

        // Wrong scheme still 401s.
        assert!(
            matches!(
                authorize_daemon_request(&state, &raw_auth_headers("Basic the-real-token-value")),
                Err(StatusCode::UNAUTHORIZED)
            ),
            "wrong scheme must 401"
        );
    }

    async fn wait_for_path_absent(path: &Path) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
        while path.exists() {
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
    }

    async fn spawn_fake_health_server(
        health: DaemonHealth,
    ) -> (u16, tokio::sync::oneshot::Sender<()>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind fake daemon");
        let port = listener.local_addr().expect("listener addr").port();
        let app = Router::new().route(
            "/health",
            get({
                let health = health.clone();
                move || {
                    let health = health.clone();
                    async move { Json(health) }
                }
            }),
        );
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            let shutdown = async move {
                let _ = shutdown_rx.await;
            };
            let _ = axum::serve(listener, app)
                .with_graceful_shutdown(shutdown)
                .await;
        });
        (port, shutdown_tx)
    }

    struct EnvVarGuard {
        key: &'static str,
        previous: Option<OsString>,
    }

    #[allow(unsafe_code)] // test-only env guard serializes process env mutation.
    impl EnvVarGuard {
        fn set(key: &'static str, value: &std::path::Path) -> Self {
            let previous = std::env::var_os(key);
            // SAFETY: called only in single-threaded test context; no concurrent env readers.
            unsafe {
                std::env::set_var(key, value);
            }
            Self { key, previous }
        }

        fn set_str(key: &'static str, value: &str) -> Self {
            let previous = std::env::var_os(key);
            // SAFETY: called only in single-threaded test context; no concurrent env readers.
            unsafe {
                std::env::set_var(key, value);
            }
            Self { key, previous }
        }

        fn unset(key: &'static str) -> Self {
            let previous = std::env::var_os(key);
            // SAFETY: called only in single-threaded test context; no concurrent env readers.
            unsafe {
                std::env::remove_var(key);
            }
            Self { key, previous }
        }
    }

    #[allow(unsafe_code)] // test-only env guard restores serialized process env mutation.
    impl Drop for EnvVarGuard {
        fn drop(&mut self) {
            match &self.previous {
                // SAFETY: called only in single-threaded test context; no concurrent env readers.
                Some(previous) => unsafe {
                    std::env::set_var(self.key, previous);
                },
                // SAFETY: called only in single-threaded test context; no concurrent env readers.
                None => unsafe {
                    std::env::remove_var(self.key);
                },
            }
        }
    }

    struct CwdGuard {
        previous: PathBuf,
    }

    impl CwdGuard {
        fn set(path: &Path) -> Self {
            let previous = std::env::current_dir().expect("current dir");
            std::env::set_current_dir(path).expect("set current dir");
            Self { previous }
        }
    }

    impl Drop for CwdGuard {
        fn drop(&mut self) {
            if std::env::set_current_dir(&self.previous).is_err() {
                std::env::set_current_dir(env!("CARGO_MANIFEST_DIR"))
                    .expect("manifest dir must be a valid cwd fallback");
            }
        }
    }

    #[tokio::test]
    async fn test_daemon_bind_policy_rejects_non_loopback_without_opt_in() {
        let _env_lock = env_lock().await;
        let _bind_guard = EnvVarGuard::set_str(DAEMON_BIND_ENV, "0.0.0.0");
        let _allow_guard = EnvVarGuard::unset(DAEMON_ALLOW_NON_LOOPBACK_ENV);

        let error = resolve_daemon_bind_host("127.0.0.1")
            .expect_err("non-loopback bind must require explicit opt-in");
        let message = error.to_string();
        assert!(
            message.contains("refusing non-loopback daemon bind"),
            "unexpected bind rejection: {message}"
        );
        assert!(
            message.contains(DAEMON_ALLOW_NON_LOOPBACK_ENV),
            "rejection should name the explicit opt-in env var: {message}"
        );
    }

    #[tokio::test]
    async fn test_daemon_bind_policy_allows_non_loopback_with_explicit_opt_in() {
        let _env_lock = env_lock().await;
        let _bind_guard = EnvVarGuard::set_str(DAEMON_BIND_ENV, "0.0.0.0");
        let _allow_guard = EnvVarGuard::set_str(DAEMON_ALLOW_NON_LOOPBACK_ENV, "1");

        let resolved = resolve_daemon_bind_host("127.0.0.1")
            .expect("explicit opt-in should allow non-loopback bind");
        assert_eq!(resolved, "0.0.0.0");
    }

    #[test]
    fn test_open_same_root_reuses_project_instance() {
        let project = project_dir("symforge-daemon-a");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(100),
            })
            .expect("first session");
        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().join(".").display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(200),
            })
            .expect("second session");

        assert_eq!(first.project_id, second.project_id);
        assert_ne!(first.session_id, second.session_id);

        let projects = state.list_projects();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].session_count, 2);
    }

    /// Feature 020 Slice 4, T030 (C4b): daemon bootstrap flows through the
    /// activation machine and the process project registry — a project open
    /// ADMITS through `plan_admission`/`execute_plan` and installs a live
    /// slot charged to the daemon surface's capacity owner, and the process
    /// machine has been driven to `PreventiveV1Open` before serving. (The C1
    /// machine oracle pins that a fresh machine starts `LegacyOpen`, so the
    /// mode observed here is bootstrap's doing, not a default.)
    #[test]
    fn project_open_admits_through_the_process_activation_registry() {
        use crate::live_index::index_lifecycle::activation::{
            ActivationCut, ActivationMode, process_project_registry,
        };
        use crate::live_index::index_lifecycle::registry::ProjectKey;

        let project = project_dir("symforge-daemon-admission");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(400),
            })
            .expect("open session");

        let live = process_project_registry()
            .live(&ProjectKey::new(&opened.project_id))
            .expect("the opened project holds a live admission slot");
        assert!(
            live.capacity_owner().expect("live slot").is_some(),
            "the admission is charged to the daemon surface's capacity owner"
        );
        assert_eq!(
            ActivationCut::process().mode(),
            ActivationMode::PreventiveV1Open,
            "bootstrap drives the startup ceremony before serving"
        );
    }

    /// Feature 020 Slice 4, T030 (C4c): the dispatch neck refuses a retired
    /// admission. Stopping a project's registry slot (what the eviction and
    /// retarget stop path does) makes `runtime_for_target` refuse instead of
    /// serving the retired index; the live slot resolving first is the
    /// accepting control in the same test.
    #[test]
    fn retired_admission_slot_refuses_dispatch_at_the_runtime_neck() {
        use crate::live_index::index_lifecycle::activation::process_project_registry;
        use crate::live_index::index_lifecycle::registry::ProjectKey;

        let project = project_dir("symforge-daemon-retired-neck");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(401),
            })
            .expect("open session");

        assert!(
            state.runtime_for_target(&opened.session_id, None).is_ok(),
            "a live admission slot resolves at the neck"
        );

        // Retire the admission out from under the daemon maps — the race the
        // typed branch closes (the stop path ran; the maps have not yet been
        // swept, or a stale runtime is dispatching between the two).
        process_project_registry()
            .stop(&ProjectKey::new(&opened.project_id))
            .expect("stop the live slot");
        let Err(refused) = state.runtime_for_target(&opened.session_id, None) else {
            panic!("a retired admission slot must refuse dispatch at the neck");
        };
        assert!(
            refused.contains("retired"),
            "the refusal names the retirement: {refused}"
        );
    }

    #[test]
    fn test_open_distinct_roots_creates_distinct_projects() {
        let project_a = project_dir("symforge-daemon-b");
        let project_b = project_dir("symforge-daemon-c");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: None,
            })
            .expect("first project");
        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project_b.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: None,
            })
            .expect("second project");

        assert_ne!(first.project_id, second.project_id);
        assert_eq!(state.list_projects().len(), 2);
        assert_eq!(state.health().session_count, 2);
    }

    /// Test-only: pull the single interned `Arc<IndexBase>` a session's working
    /// set was seeded with (Feature 012, Phase 0/1). Panics if the session or its
    /// seeded entry is missing — both are invariants the open path guarantees.
    fn session_seeded_base(state: &DaemonState, session_id: &str) -> Arc<IndexBase> {
        let sessions = state.sessions.read();
        let session = sessions.get(session_id).expect("session present");
        let working_set = session.working_set.read();
        assert_eq!(
            working_set.len(),
            1,
            "Phase 1 seeds exactly one working-set entry"
        );
        let entry = working_set
            .get(&session.active_project_id)
            .expect("seeded entry for the active project");
        Arc::clone(&entry.base)
    }

    // ── Feature 012 Phase 0 — base interning shares one Arc<IndexBase> (SC-002) ──
    #[test]
    fn test_open_same_root_twice_shares_interned_base() {
        let project = project_dir("symforge-daemon-base-intern");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(11),
            })
            .expect("first session");
        let second = state
            .open_project_session(OpenProjectRequest {
                // Same logical root via a `.` component -> same canonical root,
                // same BaseKey -> MUST intern to the same Arc<IndexBase>.
                project_root: project.path().join(".").display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(22),
            })
            .expect("second session");

        assert_eq!(
            first.project_id, second.project_id,
            "same canonical root -> same project"
        );

        let base_first = session_seeded_base(&state, &first.session_id);
        let base_second = session_seeded_base(&state, &second.session_id);

        // SC-002: two opens on the same (root, commit) share ONE base allocation.
        assert!(
            Arc::ptr_eq(&base_first, &base_second),
            "two sessions on the same (root, commit) must share one Arc<IndexBase>"
        );
        // The intern table holds exactly one base for the single key.
        assert_eq!(
            state.bases.read().len(),
            1,
            "one canonical root -> one interned base"
        );
    }

    // ── Feature 012 Phase 0 — distinct roots intern distinct bases ──────────────
    #[test]
    fn test_open_distinct_roots_intern_distinct_bases() {
        let project_a = project_dir("symforge-daemon-base-distinct-a");
        let project_b = project_dir("symforge-daemon-base-distinct-b");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: None,
            })
            .expect("project a session");
        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project_b.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: None,
            })
            .expect("project b session");

        let base_a = session_seeded_base(&state, &first.session_id);
        let base_b = session_seeded_base(&state, &second.session_id);

        assert!(
            !Arc::ptr_eq(&base_a, &base_b),
            "distinct roots must NOT share a base"
        );
        assert_ne!(
            base_a.key, base_b.key,
            "distinct roots -> distinct BaseKeys"
        );
        assert_eq!(
            state.bases.read().len(),
            2,
            "two roots -> two interned bases"
        );
    }

    // ── Feature 012f — bases-table orphan GC (SC-002-safe) ──────────────────────
    //
    // A genuine commit-advance interns the snapshot under a NEW BaseKey and swaps
    // the working-set entry, leaving the OLD key referenced only by the map: an
    // orphan that grows the table unbounded on a long-lived multi-commit daemon.
    // The GC evicts orphans (strong_count == 1) and MUST NOT evict a base a live
    // working set still holds (strong_count > 1) — evicting it would let a later
    // intern mint a SECOND Arc per key (the SC-002 violation).
    #[test]
    fn test_gc_orphaned_bases_evicts_orphan_keeps_live() {
        use crate::live_index::store::LiveIndex;
        use crate::live_index::view::{CommitId, WorkingSet};

        let state = DaemonState::new();
        let root = "/synthetic/gc-root";

        // OLD-commit base: interned, then no longer referenced by any working set
        // (simulating the entry-swap a commit-advance performs). Map-only Arc.
        let orphan_key = BaseKey::new(root, CommitId::Sha("old-commit".to_string()));
        state.bases.write().insert(
            orphan_key.clone(),
            Arc::new(IndexBase::new(
                orphan_key.clone(),
                Arc::new(LiveIndex::empty_live_index()),
                1,
            )),
        );

        // NEW-commit base: interned AND held by a live working set (the post-advance
        // state). The working-set entry stores a CLONE of the SAME map Arc, so the
        // map value's strong_count is > 1 — the liveness signal the GC relies on.
        let live_key = BaseKey::new(root, CommitId::Sha("new-commit".to_string()));
        let live_base = Arc::new(IndexBase::new(
            live_key.clone(),
            Arc::new(LiveIndex::empty_live_index()),
            2,
        ));
        state
            .bases
            .write()
            .insert(live_key.clone(), Arc::clone(&live_base));
        let working_set = Arc::new(RwLock::new(WorkingSet::new()));
        working_set.write().add("proj", Arc::clone(&live_base));
        // Drop our local strong ref so ONLY the map + the working-set entry hold the
        // live base (strong_count == 2). Without this, our local clone would mask a
        // buggy GC that relies on an accidental extra ref.
        drop(live_base);

        // Non-vacuity: BEFORE the sweep the orphan IS in the table (the leak the GC
        // closes) and both keys are present.
        {
            let bases = state.bases.read();
            assert!(
                bases.contains_key(&orphan_key),
                "precondition: orphan must be present before GC (proves the leak)"
            );
            assert_eq!(bases.len(), 2, "precondition: both bases interned");
            assert_eq!(
                Arc::strong_count(bases.get(&orphan_key).unwrap()),
                1,
                "orphan must be map-only (the eviction signal)"
            );
            assert_eq!(
                Arc::strong_count(bases.get(&live_key).unwrap()),
                2,
                "live base is held by map + working-set entry"
            );
        }

        state.gc_orphaned_bases();

        let bases = state.bases.read();
        // Orphan evicted.
        assert!(
            !bases.contains_key(&orphan_key),
            "GC must evict the orphaned (map-only) base"
        );
        // SC-002 guard: the still-referenced base survives — evicting it would let a
        // later intern mint a second Arc for this key.
        assert!(
            bases.contains_key(&live_key),
            "GC must NOT evict a base a live working set still references"
        );
        assert_eq!(bases.len(), 1, "only the orphan is removed");
        // The surviving map value is STILL the SAME Arc the working-set entry holds.
        let table_live = bases.get(&live_key).unwrap();
        let ws = working_set.read();
        let entry = ws.get("proj").expect("live entry present");
        assert!(
            Arc::ptr_eq(table_live, &entry.base),
            "SC-002: survivor is the same shared Arc the working set holds"
        );
    }

    // ── Feature 012f — close_session sweeps last-holder orphans (the parallel
    //    orphan path the commit-advance trigger misses) ─────────────────────────
    //
    // Opening the only session on a root interns its base (map + working-set =
    // strong_count 2). Closing that last session drops the working_set, leaving
    // the base map-only — an orphan the GC must reclaim from close_session.
    #[test]
    fn test_close_last_session_gcs_orphaned_base() {
        let project = project_dir("symforge-daemon-close-gc");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: None,
            })
            .expect("session");

        // Precondition: the open interned exactly one base, held by map + session.
        assert_eq!(
            state.bases.read().len(),
            1,
            "open interns one base for the root"
        );

        state
            .close_session(&opened.session_id)
            .expect("close the only session");

        // The last (only) session closed -> its working_set dropped -> the base is
        // a map-only orphan -> close_session's GC sweep reclaims it.
        assert_eq!(
            state.bases.read().len(),
            0,
            "close_session must GC the base no session references anymore"
        );
    }

    // ── Feature 012 Phase 3 — resolve_targets contract (FR-004 / SC-001) ─────────
    #[test]
    fn test_resolve_targets_contract() {
        let active = "project-active";

        // Both omitted -> One(active) -> today's behavior.
        assert_eq!(
            resolve_targets(None, None, active).unwrap(),
            Targets::One(active.to_string())
        );

        // A single explicit id (the active one) -> One(active) (still the fast path).
        assert_eq!(
            resolve_targets(Some(active), None, active).unwrap(),
            Targets::One(active.to_string())
        );

        // A single explicit OTHER id -> One(other) (cross-project, single target).
        assert_eq!(
            resolve_targets(Some("project-other"), None, active).unwrap(),
            Targets::One("project-other".to_string())
        );

        // ["*"] -> All.
        assert_eq!(
            resolve_targets(None, Some(&["*".to_string()]), active).unwrap(),
            Targets::All
        );

        // An explicit subset -> Subset.
        assert_eq!(
            resolve_targets(
                None,
                Some(&["project-a".to_string(), "project-b".to_string()]),
                active
            )
            .unwrap(),
            Targets::Subset(vec!["project-a".to_string(), "project-b".to_string()])
        );

        // Mutually exclusive -> error.
        assert!(
            resolve_targets(Some("project-a"), Some(&["project-b".to_string()]), active).is_err()
        );

        // Empty projects -> error (no silent All).
        assert!(resolve_targets(None, Some(&[]), active).is_err());

        // A filesystem path in `project=` -> corrective error pointing at add:true.
        let err = resolve_targets(Some("E:/project/symforge"), None, active).unwrap_err();
        assert!(
            err.contains("index_folder") && err.contains("add"),
            "path-in-project error must point at index_folder(add:true): {err}"
        );
        assert!(resolve_targets(Some("/abs/path"), None, active).is_err());

        // A path inside `projects=` -> error too.
        assert!(resolve_targets(None, Some(&["src/lib.rs".to_string()]), active).is_err());

        // Empty/whitespace project id -> error.
        assert!(resolve_targets(Some("   "), None, active).is_err());

        assert_eq!(
            resolve_targets(Some("project-other "), None, active).unwrap(),
            Targets::One("project-other ".to_string()),
            "nonblank selector bytes are identity-bearing"
        );
        assert_eq!(
            resolve_targets(None, Some(&["project-other ".to_string()]), active).unwrap(),
            Targets::Subset(vec!["project-other ".to_string()])
        );
    }

    #[test]
    fn strict_daemon_selector_decode_rejects_lossy_or_ambiguous_json() {
        for malformed in [
            serde_json::json!({"project": 7}),
            serde_json::json!({"projects": "project-b"}),
            serde_json::json!({"projects": ["project-b", 7]}),
            serde_json::json!({"projects": []}),
            serde_json::json!({"projects": [""]}),
            serde_json::json!({"projects": ["*", "project-b"]}),
            serde_json::json!({"project": "project-a", "projects": ["project-b"]}),
        ] {
            assert!(
                strict_daemon_project_selectors(&malformed).is_err(),
                "malformed selectors must fail before runtime selection: {malformed}"
            );
        }

        assert_eq!(
            strict_daemon_project_selectors(&serde_json::json!({
                "project": "project-b "
            }))
            .expect("exact scalar selector"),
            (Some("project-b ".to_string()), None)
        );
        assert_eq!(
            strict_daemon_project_selectors(&serde_json::json!({
                "projects": ["project-a ", "project-b"]
            }))
            .expect("exact set selector"),
            (
                None,
                Some(vec!["project-a ".to_string(), "project-b".to_string()])
            )
        );
    }

    #[test]
    fn daemon_private_route_pin_is_exact_allowlisted_and_conflict_free() {
        fn pinned(value: serde_json::Value) -> serde_json::Value {
            let mut params = serde_json::json!({});
            params
                .as_object_mut()
                .expect("object fixture")
                .insert(PRIVATE_PROJECT_ROUTE_PIN.to_string(), value);
            params
        }

        for tool_name in [
            "inspect_match",
            "checkpoint_now",
            "detect_impact",
            "conventions",
            "health",
            "health_compact",
            "status",
            "context_inventory",
        ] {
            let mut params = pinned(serde_json::json!("project-active"));
            assert_eq!(
                take_private_project_route_pin(tool_name, &mut params)
                    .expect("allowlisted private route pin"),
                Some("project-active".to_string())
            );
            assert!(
                params.get(PRIVATE_PROJECT_ROUTE_PIN).is_none(),
                "the internal marker must be removed before typed decoding"
            );
        }

        for (tool_name, mut params) in [
            ("index_folder", pinned(serde_json::json!("project-active"))),
            ("inspect_match", pinned(serde_json::json!("   "))),
            (
                "inspect_match",
                pinned(serde_json::json!(" project-active")),
            ),
            ("checkpoint_now", pinned(serde_json::json!(7))),
            ("detect_impact", {
                let mut params = pinned(serde_json::json!("project-active"));
                params
                    .as_object_mut()
                    .expect("object fixture")
                    .insert("project".to_string(), serde_json::Value::Null);
                params
            }),
            ("conventions", {
                let mut params = pinned(serde_json::json!("project-active"));
                params
                    .as_object_mut()
                    .expect("object fixture")
                    .insert("projects".to_string(), serde_json::json!([]));
                params
            }),
        ] {
            assert!(
                take_private_project_route_pin(tool_name, &mut params).is_err(),
                "invalid private pin must fail closed for {tool_name}: {params}"
            );
        }
    }

    #[test]
    fn test_targets_is_single_active() {
        let active = "project-active";
        assert!(targets_is_single_active(
            &Targets::One(active.to_string()),
            active
        ));
        assert!(!targets_is_single_active(
            &Targets::One("project-other".to_string()),
            active
        ));
        assert!(!targets_is_single_active(&Targets::All, active));
        assert!(!targets_is_single_active(
            &Targets::Subset(vec![active.to_string()]),
            active
        ));
    }

    // ── Feature 012 Phase 2 — set_active_project / remove_project_from_session ───
    #[test]
    fn test_set_active_and_remove_project_management() {
        let project_a = project_dir("symforge-mgmt-a");
        let project_b = project_dir("symforge-mgmt-b");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");
        let state = DaemonState::new();

        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "mgmt".to_string(),
                pid: None,
            })
            .expect("open A");
        let active_a = opened.project_id.clone();

        // Additively open B in the same session.
        state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("additive open B");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        // Working set now holds both; A is still active.
        {
            let sessions = state.sessions.read();
            let session = sessions.get(&opened.session_id).expect("session");
            let ws = session.working_set.read();
            assert_eq!(ws.len(), 2, "working set holds A and B");
            assert_eq!(session.active_project_id, active_a, "A still active");
            assert!(ws.get(&active_a).is_some());
            assert!(ws.get(&project_b_id).is_some());
        }

        // Cannot activate a project that is not open.
        assert!(
            !state.set_active_project(&opened.session_id, "project-not-open"),
            "activating a non-open project must fail"
        );
        // Activate B (it is open).
        assert!(
            state.set_active_project(&opened.session_id, &project_b_id),
            "activating an open project must succeed"
        );
        assert_eq!(
            state
                .sessions
                .read()
                .get(&opened.session_id)
                .unwrap()
                .active_project_id,
            project_b_id,
            "B is now active"
        );

        // Cannot remove the ACTIVE project (B).
        assert!(
            !state.remove_project_from_session(&opened.session_id, &project_b_id),
            "removing the active project must be refused"
        );
        // Remove A (now non-active) -> succeeds and drops it from the working set.
        assert!(
            state.remove_project_from_session(&opened.session_id, &active_a),
            "removing a non-active open project must succeed"
        );
        {
            let sessions = state.sessions.read();
            let ws = sessions.get(&opened.session_id).unwrap().working_set.read();
            assert_eq!(ws.len(), 1, "only B remains");
            assert!(ws.get(&active_a).is_none(), "A removed");
            assert!(ws.get(&project_b_id).is_some(), "B remains");
        }
        // A had only this session -> it should be torn down as a project.
        assert!(
            !state
                .list_projects()
                .iter()
                .any(|p| p.project_id == active_a),
            "project A removed after its last session reference dropped"
        );

        let _ = state.close_session(&opened.session_id);
    }

    // ── Feature 012 Phase 2 — additive open keeps active project + adds to WS ────
    #[test]
    fn test_index_folder_additive_keeps_active_and_adds_to_working_set() {
        let project_a = project_dir("symforge-additive-a");
        let project_b = project_dir("symforge-additive-b");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");
        let state = DaemonState::new();

        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "additive".to_string(),
                pid: None,
            })
            .expect("open A");
        let active_a = opened.project_id.clone();

        let output = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("additive open B");
        assert!(
            output.contains("added to working set"),
            "additive open should report working-set addition: {output}"
        );

        let sessions = state.sessions.read();
        let session = sessions.get(&opened.session_id).expect("session");
        // Active project UNCHANGED (still A) — additive does not retarget.
        assert_eq!(session.active_project_id, active_a, "A still active");
        let ws = session.working_set.read();
        assert_eq!(ws.len(), 2, "working set has A and B after additive open");
        // Both overlays remain EMPTY (no-overlay-writes invariant).
        for entry in ws.iter() {
            assert_eq!(
                entry.overlay.delta_count(),
                0,
                "no overlay write on additive open (project {})",
                entry.project_id
            );
        }
    }

    /// Task 4 resolver: omission -> home; explicit id -> target; unique display
    /// name -> target; unknown -> deterministic candidates; ambiguous display
    /// name -> deterministic ambiguity error naming the ids.
    #[test]
    fn test_runtime_for_target_resolution_contract() {
        let project_a = project_dir("symforge-resolver-home-a");
        let parent_one = TempDir::new().expect("parent one");
        let parent_two = TempDir::new().expect("parent two");
        // Two OPEN projects with the SAME display name under different parents.
        let same_name_one = parent_one.path().join("samename");
        let same_name_two = parent_two.path().join("samename");
        for root in [&same_name_one, &same_name_two] {
            std::fs::create_dir_all(root.join("src")).expect("create src");
            std::fs::write(root.join("src").join("lib.rs"), "fn f() {}\n").expect("write src");
        }
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "resolver".to_string(),
                pid: None,
            })
            .expect("open home A");
        for root in [&same_name_one, &same_name_two] {
            state
                .index_folder_for_session(
                    &opened.session_id,
                    IndexFolderInput {
                        path: root.display().to_string(),
                        idempotency_key: None,
                        // Additive: this test asserts the RESOLVER contract
                        // (omission -> active), not activation — keep home A
                        // active by not default-opening.
                        add: Some(true),
                        allow_protected_root: None,
                    },
                )
                .expect("open same-name project");
        }
        let id_one = project_key(&canonical_project_root(&same_name_one).expect("canonical 1"));
        let id_two = project_key(&canonical_project_root(&same_name_two).expect("canonical 2"));

        // Omission -> the ACTIVE project (home A; the same-name siblings were
        // opened additively, which never activates).
        let home = state
            .runtime_for_target(&opened.session_id, None)
            .expect("home runtime");
        assert_eq!(home.project_id, opened.project_id);
        // Explicit id -> that project.
        let by_id = state
            .runtime_for_target(&opened.session_id, Some(&id_one))
            .expect("runtime by id");
        assert_eq!(by_id.project_id, id_one);
        // Unique display name -> home project's name resolves to home.
        let by_name = state
            .runtime_for_target(&opened.session_id, Some(&opened.project_name))
            .expect("runtime by unique name");
        assert_eq!(by_name.project_id, opened.project_id);
        // Ambiguous display name -> deterministic error naming both ids.
        let ambiguous = match state.runtime_for_target(&opened.session_id, Some("samename")) {
            Err(message) => message,
            Ok(_) => panic!("ambiguous name must not resolve"),
        };
        assert!(
            ambiguous.contains("ambiguous")
                && ambiguous.contains(&id_one)
                && ambiguous.contains(&id_two),
            "ambiguity error must name candidates: {ambiguous}"
        );
        // Unknown selector -> candidates, no load.
        let unknown = match state.runtime_for_target(&opened.session_id, Some("nope")) {
            Err(message) => message,
            Ok(_) => panic!("unknown selector must not resolve"),
        };
        assert!(
            unknown.contains("not open") && unknown.contains(&opened.project_id),
            "unknown-selector error must list open projects: {unknown}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn client_selector_resolution_preserves_trailing_space_project_names() {
        let parent = TempDir::new().expect("parent");
        let home = parent.path().join("repo");
        let sibling = parent.path().join("repo ");
        std::fs::create_dir(&home).expect("home");
        std::fs::create_dir(&sibling).expect("sibling");
        let home = home.canonicalize().expect("canonical home");
        let sibling = sibling.canonicalize().expect("canonical sibling");
        let home_id = project_key(&home);
        let sibling_id = project_key(&sibling);
        let client = DaemonSessionClient::new_for_test(
            "http://127.0.0.1:1".to_string(),
            home_id,
            "session-id".to_string(),
            "repo".to_string(),
        )
        .with_project_root(home);
        client.record_opened_root(sibling.clone());

        let selected = client
            .opened_project_for_selector(Some("repo "))
            .expect("exact trailing-space name must resolve");
        assert_eq!(selected.0, sibling_id);
        assert_eq!(selected.1, sibling);
        assert!(!selected.2);
    }

    // ── Locked contract — default open ACTIVATES the target, keeps the working set ───
    #[test]
    fn test_default_index_folder_open_activates_and_keeps_working_set() {
        let project_a = project_dir("symforge-reseed-a");
        let project_b = project_dir("symforge-reseed-b");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");
        let state = DaemonState::new();

        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "reseed".to_string(),
                pid: None,
            })
            .expect("open A");
        let active_a = opened.project_id.clone();

        let output = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("open B");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        assert!(
            output.contains(&format!("project_id={project_b_id}")),
            "receipt must identify the opened project: {output}"
        );
        assert!(
            output.contains("checkpoint=written"),
            "successful daemon reload must report its checkpoint: {output}"
        );

        let sessions = state.sessions.read();
        let session = sessions.get(&opened.session_id).expect("session");
        assert_eq!(
            session.active_project_id, project_b_id,
            "default index_folder must ACTIVATE the opened project (locked contract)"
        );
        let ws = session.working_set.read();
        assert_eq!(ws.len(), 2, "default open must keep A and add B");
        assert!(
            ws.get(&active_a).is_some(),
            "home project A must stay in the working set (activation is non-destructive)"
        );
        let entry = ws
            .get(&project_b_id)
            .expect("working set gains newly opened project B");
        assert_eq!(
            entry.overlay.delta_count(),
            0,
            "opened-project overlay must be empty"
        );
        assert!(
            entry.overlay.is_valid_against(&entry.base),
            "re-seeded overlay fenced to its base"
        );
    }

    #[test]
    fn daemon_index_folder_reconciles_existing_root_gitignore() {
        let home = project_dir("symforge-hygiene-home");
        let target = project_dir("symforge-hygiene-target");
        std::fs::create_dir(target.path().join(".git")).expect("create git metadata marker");
        std::fs::write(target.path().join(".gitignore"), b"target/\r\n")
            .expect("write root gitignore");
        std::fs::write(
            target.path().join("src").join("lib.rs"),
            "fn indexed() {}\n",
        )
        .expect("write target source");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: home.path().display().to_string(),
                client_name: "gitignore-hygiene".to_string(),
                pid: None,
            })
            .expect("open home");

        let receipt = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: target.path().display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("open target");

        assert!(
            receipt.contains("gitignore_hygiene=effective changed=true"),
            "daemon indexing must report the hygiene mutation: {receipt}"
        );
        assert_eq!(
            std::fs::read(target.path().join(".gitignore")).expect("read reconciled gitignore"),
            b"target/\r\n/.symforge/\r\n",
            "daemon indexing must preserve existing bytes and newline style"
        );
    }

    // ── Feature 012 Phase 0/1/2 — multi-threaded lock stress (critique #4) ───────
    //
    // The mandated `--test-threads=1` suite CANNOT surface a deadlock on the new
    // `bases -> projects -> sessions` hot path, so THIS test spins REAL OS threads
    // that hammer the lock acquisition order concurrently. Threads churn:
    //   * `open_project_session` (intern_base -> projects.write -> sessions.write),
    //   * `session_runtime` (projects.read -> sessions.read, the hot read path),
    //   * `index_folder_for_session` BOTH ways — the destructive `needs_reassign`
    //     RETARGET (alternating target roots: projects.write mid-function juggling
    //     + working-set re-seed + sessions.write) AND the additive `add:true` path
    //     (load/activate + additive session_ids join + intern + working_set.add) —
    //     this file's trickiest lock juggling, now under contention,
    //   * `close_session` (projects.write -> sessions.write),
    //   * `health` / `list_projects` (independent reads),
    // over a SHARED pool of roots so the SAME BaseKey is interned from many threads
    // (the contended path) AND distinct roots are interned (table growth). A
    // lock-order inversion would deadlock; a panic in any thread is propagated by
    // `join().expect(..)`. The test passing == no deadlock and no panic under load.
    #[test]
    fn test_concurrent_session_lifecycle_no_deadlock_or_panic() {
        use std::sync::Arc as StdArc;

        // A shared pool of roots: same roots reused across threads force repeated
        // interning of identical BaseKeys; the per-thread index adds fresh roots.
        let shared_roots: Vec<TempDir> = (0..4)
            .map(|i| project_dir(&format!("symforge-stress-shared-{i}")))
            .collect();
        let shared_root_paths: StdArc<Vec<String>> = StdArc::new(
            shared_roots
                .iter()
                .map(|d| d.path().display().to_string())
                .collect(),
        );

        let state = StdArc::new(DaemonState::new());

        const THREADS: usize = 8;
        const ITERS: usize = 40;

        let mut handles = Vec::with_capacity(THREADS);
        for t in 0..THREADS {
            let state = StdArc::clone(&state);
            let shared_root_paths = StdArc::clone(&shared_root_paths);
            // Each thread also owns a private root so distinct-root interning and
            // project churn (load -> activate -> remove on last close) is exercised.
            let private_root = project_dir(&format!("symforge-stress-private-{t}"));
            let private_path = private_root.path().display().to_string();
            // A second per-thread root to retarget/additively-open INTO under
            // contention (forces `needs_reassign` retarget + add:true paths).
            let retarget_root = project_dir(&format!("symforge-stress-retarget-{t}"));
            let retarget_path = retarget_root.path().display().to_string();
            handles.push(std::thread::spawn(move || {
                // Keep the TempDirs alive for the whole thread body.
                let _private_root = private_root;
                let _retarget_root = retarget_root;
                for i in 0..ITERS {
                    // Alternate between a shared root (contended intern of the same
                    // BaseKey) and this thread's private root (table growth/churn).
                    let root = if i % 2 == 0 {
                        shared_root_paths[(t + i) % shared_root_paths.len()].clone()
                    } else {
                        private_path.clone()
                    };

                    // D17 (atomic open, fail-never): `open_project_session` now
                    // ensures the project AND registers the session under a single
                    // `projects.write()` hold (recovering by reload if a concurrent
                    // `close_session` removed it), so the former "was removed between
                    // check and session registration" race CANNOT occur. Open MUST
                    // succeed under contention — a failure is a real regression, not
                    // a tolerated benign race. (A lock-order inversion would instead
                    // HANG at join and never reach this assert.)
                    let opened = state
                        .open_project_session(OpenProjectRequest {
                            project_root: root.clone(),
                            client_name: "stress".to_string(),
                            pid: Some((t * 1000 + i) as u32),
                        })
                        .expect(
                            "open_project_session must succeed under contention (D17 fail-never)",
                        );

                    // Hot read path: resolves the active project via the new field.
                    // (May be `None` if a concurrent close already tore the project
                    // down — also benign and not a deadlock.)
                    let _ = state.session_runtime(&opened.session_id);

                    // Independent reads exercised concurrently with writers.
                    let _ = state.health();
                    let _ = state.list_projects();
                    let _ = state.list_sessions(&opened.project_id);

                    // Feature 012 — exercise the trickiest lock juggling under
                    // contention. Alternate the two `index_folder_for_session`
                    // code paths so both run concurrently across threads:
                    //   * even i -> destructive RETARGET (add: None) into the
                    //     per-thread retarget root: projects.write mid-function
                    //     juggling + working-set re-seed + sessions.write;
                    //   * odd  i -> ADDITIVE add:true into the same root: additive
                    //     session_ids join + intern + working_set.add.
                    // Both can legitimately fail loud (e.g. the session was closed
                    // by a concurrent worker, or the open lost the benign race);
                    // those errors are tolerated — only a deadlock (hang at join)
                    // or a panic is a failure here.
                    let _ = state.index_folder_for_session(
                        &opened.session_id,
                        IndexFolderInput {
                            path: retarget_path.clone(),
                            idempotency_key: None,
                            add: Some(i % 2 == 1),
                            allow_protected_root: None,
                        },
                    );

                    // Close: projects.write -> sessions.write (the order under test).
                    let _ = state.close_session(&opened.session_id);
                }
            }));
        }

        for handle in handles {
            // A deadlock would hang here (caught by the harness/CI timeout); a panic
            // in any worker is surfaced as a test failure via expect.
            handle.join().expect("stress worker thread panicked");
        }

        // Keep the shared TempDirs alive until all threads have joined.
        drop(shared_roots);

        // After every session is closed, no projects or sessions should remain.
        assert_eq!(
            state.health().session_count,
            0,
            "all sessions closed after the stress loop"
        );
        assert!(
            state.list_projects().is_empty(),
            "all projects removed after their last session closed"
        );
    }

    #[tokio::test]
    async fn test_index_folder_for_session_refuses_sensitive_root() {
        let _guard = env_lock().await;
        let state_home = TempDir::new().expect("private user-local state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        // Regression: the daemon path historically never called the sensitive
        // -path guard, so a daemon-routed `index_folder` on a system root could
        // index system files and drive a reload into a denial-of-service.
        let project = project_dir("symforge-daemon-sensitive");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: None,
            })
            .expect("session");

        let fixture = TempDir::new().expect("protected-root fixture parent");
        let sensitive = fixture.path().join("System32");
        std::fs::create_dir(&sensitive).expect("create modeled protected root");
        std::fs::write(
            sensitive.join("lib.rs"),
            "pub fn protected_daemon_symbol() {}\n",
        )
        .expect("write protected source");

        let result = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: sensitive.display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("refusal must be a clean Ok response, never an Err or panic");
        assert!(
            result.contains("protected_root_requires_explicit_override"),
            "daemon path must refuse the modeled protected root, got: {result}"
        );

        // The session must remain bound to the original project (no reassign).
        let projects = state.list_projects();
        assert_eq!(
            projects.len(),
            1,
            "refusal must not create a project for the sensitive root"
        );

        let indexed = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: sensitive.display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: Some(true),
                },
            )
            .expect("direct protected authority should produce a clean result");
        assert!(
            indexed.contains("Indexed 1 files"),
            "daemon override should index the exact protected root: {indexed}"
        );
        assert!(!sensitive.join(".symforge").exists());
        let canonical = sensitive.canonicalize().unwrap();
        assert!(
            state_home
                .path()
                .join("projects")
                .join(project_key(&canonical))
                .is_dir(),
            "explicit protected daemon state should be user-local"
        );
    }

    #[tokio::test]
    async fn protected_membership_is_per_session_and_requires_each_direct_override() {
        let _guard = env_lock().await;
        let state_home = TempDir::new().expect("private user-local state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        let home_a = project_dir("symforge-protected-session-a");
        let home_b = project_dir("symforge-protected-session-b");
        let state = DaemonState::new();
        let session_a = state
            .open_project_session(OpenProjectRequest {
                project_root: home_a.path().display().to_string(),
                client_name: "protected-a".to_string(),
                pid: None,
            })
            .expect("open session A");
        let session_b = state
            .open_project_session(OpenProjectRequest {
                project_root: home_b.path().display().to_string(),
                client_name: "protected-b".to_string(),
                pid: None,
            })
            .expect("open session B");

        let fixture = TempDir::new().expect("protected-root fixture parent");
        let protected = fixture.path().join("System32");
        std::fs::create_dir(&protected).expect("create modeled protected root");
        std::fs::write(
            protected.join("lib.rs"),
            "pub fn protected_session_symbol() {}\n",
        )
        .expect("write protected source");
        let protected_id = project_key(&protected.canonicalize().unwrap());

        let opened_a = state
            .index_folder_for_session(
                &session_a.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("session A direct protected open");
        assert!(opened_a.contains("Indexed 1 files"), "{opened_a}");

        let protected_name = {
            let projects = state.projects.read();
            let slot = projects.get(&protected_id).expect("shared protected slot");
            slot.metadata.read().project_name.clone()
        };
        {
            let sessions = state.sessions.read();
            assert!(
                sessions
                    .get(&session_a.session_id)
                    .unwrap()
                    .working_set
                    .read()
                    .get(&protected_id)
                    .is_some(),
                "the directly authorized session must gain membership"
            );
            assert!(
                sessions
                    .get(&session_b.session_id)
                    .unwrap()
                    .working_set
                    .read()
                    .get(&protected_id)
                    .is_none(),
                "another session must not inherit protected membership"
            );
        }
        assert!(
            !state.set_active_project(&session_b.session_id, &protected_id),
            "a global project id must not grant session membership"
        );
        assert!(
            state
                .runtime_for_target(&session_b.session_id, Some(&protected_id))
                .is_err(),
            "a protected project id must not address another session's membership"
        );
        assert!(
            state
                .runtime_for_target(&session_b.session_id, Some(&protected_name))
                .is_err(),
            "a protected project alias must not address another session's membership"
        );

        let refused_b = state
            .index_folder_for_session(
                &session_b.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("missing override is a typed refusal");
        assert!(
            refused_b.contains("protected_root_requires_explicit_override"),
            "{refused_b}"
        );
        assert!(
            state
                .runtime_for_target(&session_b.session_id, Some(&protected_id))
                .is_err(),
            "a refused request must not attach protected membership"
        );

        let opened_b = state
            .index_folder_for_session(
                &session_b.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("session B direct protected open");
        assert!(opened_b.contains("Indexed 1 files"), "{opened_b}");
        assert!(
            state
                .runtime_for_target(&session_b.session_id, Some(&protected_id))
                .is_ok(),
            "session B gains membership only after its own direct override"
        );
        let projects = state.projects.read();
        let protected_slot = projects.get(&protected_id).expect("one protected slot");
        let protected_meta = protected_slot.metadata.read();
        assert_eq!(protected_meta.session_ids.len(), 2);
        assert!(protected_meta.session_ids.contains(&session_a.session_id));
        assert!(protected_meta.session_ids.contains(&session_b.session_id));
    }

    #[tokio::test]
    async fn l_r11_second_session_cannot_reach_protected_project_via_wildcard_or_ref_mapping() {
        // L-R11 (tasks.md:667; source-binding-and-state.md:64-90 test 16;
        // repository-mental-model.md test 9): a second session cannot address an
        // explicit-protected project/worktree through a wildcard (`projects=["*"]`),
        // a subset selector, or any ref/worktree source mapping. Every cross-project
        // read resolves ONLY against the SESSION's own `project_indexes`, which
        // `runtime_for_target` builds from `session.servers` (the session's own
        // opened projects). The id/alias vector is proven by
        // `protected_membership_is_per_session_and_requires_each_direct_override`;
        // this closes the wildcard/subset/dispatcher vector and the direct-override
        // grant. No addressing guard predicate exists or is needed: the session-
        // scoped `project_indexes` capture IS the enforcement chokepoint.
        let _guard = env_lock().await;
        let state_home = TempDir::new().expect("private user-local state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        let home_a = project_dir("symforge-l-r11-session-a");
        let home_b = project_dir("symforge-l-r11-session-b");
        let state = DaemonState::new();
        let session_a = state
            .open_project_session(OpenProjectRequest {
                project_root: home_a.path().display().to_string(),
                client_name: "l-r11-a".to_string(),
                pid: None,
            })
            .expect("open session A");
        let session_b = state
            .open_project_session(OpenProjectRequest {
                project_root: home_b.path().display().to_string(),
                client_name: "l-r11-b".to_string(),
                pid: None,
            })
            .expect("open session B");

        // A modeled protected root with a knowledge document, so the source mappings
        // L-R11 guards against actually exist to be (un)addressable.
        let fixture = TempDir::new().expect("protected-root fixture parent");
        let protected = fixture.path().join("System32");
        std::fs::create_dir(&protected).expect("create modeled protected root");
        std::fs::write(
            protected.join("guide.md"),
            "# Protected Guide\n\nThe orbital lattice resonates across the protected source.\n",
        )
        .expect("write protected knowledge doc");
        let protected_id = project_key(&protected.canonicalize().unwrap());

        // Session A directly opens the protected root; session B never does.
        let opened_a = state
            .index_folder_for_session(
                &session_a.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("session A direct protected open");
        assert!(opened_a.contains("Indexed"), "{opened_a}");

        let query = || SearchKnowledgeInput {
            query: "orbital lattice".to_string(),
            path_prefix: None,
            source_scope: None,
            authority_scope: None,
            // The dispatcher switches on the `Targets` argument, not these fields.
            project: None,
            projects: None,
            limit: None,
            max_tokens: None,
        };

        // Session B's runtime is the ONLY source a cross-project read resolves
        // against. The raw `projects=["*"]` param resolves to `Targets::All`, which
        // the dispatcher expands from `project_indexes.keys()` — session B's own
        // projects only.
        let runtime_b = state
            .runtime_for_target(&session_b.session_id, None)
            .expect("session B home runtime");
        assert!(
            matches!(
                resolve_targets(None, Some(&["*".to_string()]), &runtime_b.project_id),
                Ok(Targets::All)
            ),
            "projects=[\"*\"] must resolve to Targets::All"
        );
        assert!(
            !runtime_b.project_indexes.contains_key(&protected_id),
            "projects=[\"*\"] (Targets::All = project_indexes.keys()) must NOT include \
             another session's protected project"
        );

        // Wildcard: silently scoped to session B's own projects — never errors AND
        // never covers the protected source.
        let wildcard = execute_cross_project_knowledge(
            query(),
            Targets::All,
            &runtime_b.project_indexes,
            &runtime_b.server,
        )
        .expect("wildcard over session B's own projects succeeds");
        assert!(
            !wildcard.contains(protected_id.as_str()),
            "the protected project must not appear in a second session's wildcard scope: {wildcard}"
        );

        // Explicit id and subset selectors naming the protected project are refused
        // with "project not open": a project id / ref-worktree mapping cannot inherit
        // another session's protected membership.
        for targets in [
            Targets::One(protected_id.clone()),
            Targets::Subset(vec![protected_id.clone()]),
        ] {
            let refused = execute_cross_project_knowledge(
                query(),
                targets,
                &runtime_b.project_indexes,
                &runtime_b.server,
            )
            .expect_err("a protected project the session never opened is not addressable");
            assert!(
                refused.to_string().contains("project not open"),
                "{refused}"
            );
        }

        // The direct-override path is the ONLY way in: session B issues its OWN exact
        // `index_folder(allow_protected_root=true)`.
        let opened_b = state
            .index_folder_for_session(
                &session_b.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("session B direct protected open");
        assert!(opened_b.contains("Indexed"), "{opened_b}");

        let runtime_b2 = state
            .runtime_for_target(&session_b.session_id, None)
            .expect("session B home runtime after its own override");
        assert!(
            runtime_b2.project_indexes.contains_key(&protected_id),
            "session B gains wildcard-addressable membership only after its own direct override"
        );
        execute_cross_project_knowledge(
            query(),
            Targets::One(protected_id.clone()),
            &runtime_b2.project_indexes,
            &runtime_b2.server,
        )
        .expect("session B can address the protected project after its own direct override");
    }

    /// Build one `PublishedSourceSet` carrying a healthy current worktree lane AND
    /// a P1 `symforge:git-ref:` lane whose knowledge document exists ONLY on the ref
    /// lane. Shapes the fixture the two `search_scoped`/`review_scoped` unit tests
    /// already prove, but wired for the daemon cross-project entry points. The temp
    /// roots are returned so the caller keeps them alive.
    fn cross_project_current_and_ref_lanes() -> (TempDir, TempDir, SharedIndex) {
        // Current worktree lane: "quantum meridian" only.
        let current_dir = tempfile::tempdir().expect("current tempdir");
        let current_repo = git2::Repository::init(current_dir.path()).expect("init current repo");
        ref_lane_commit(
            &current_repo,
            current_dir.path(),
            "docs/current.md",
            b"# Current\n\nThe quantum meridian anchors only the current worktree.\n",
            "current worktree doc",
        );
        let index = LiveIndex::load(current_dir.path()).expect("load current worktree lane");

        // P1 git-ref lane: "orbital lattice" only, built from a separate repo's HEAD
        // tree and published onto the SAME handle (current lane left untouched).
        let ref_dir = tempfile::tempdir().expect("ref tempdir");
        let ref_repo = git2::Repository::init(ref_dir.path()).expect("init ref repo");
        ref_lane_commit(
            &ref_repo,
            ref_dir.path(),
            "docs/reflane.md",
            b"# Ref Lane\n\nThe orbital lattice resonates only on the ref lane.\n",
            "ref lane doc",
        );
        live_index::local_ref_scout::ingest_and_publish_local_ref(
            &index,
            &ref_repo,
            "HEAD",
            crate::domain::index::RepositoryId::new("repo-cross-scope"),
            &live_index::local_ref_scout::LocalRefScoutBudget::default(),
        )
        .expect("publish P1 ref lane");

        assert!(
            index
                .published_source_set()
                .sources
                .keys()
                .any(|id| id.as_str().starts_with("symforge:git-ref:")),
            "a P1 git-ref lane must exist for the scope-composition test to be meaningful"
        );

        (current_dir, ref_dir, index)
    }

    /// [L-R09/L-G06] A multi-project `search_knowledge` with
    /// `source_scope=local_refs`/`all` composes each selected project's P1 git-ref
    /// lanes. Before the fix the cross-project path captured only the current lane
    /// (`search_current`) and silently dropped every ref lane; now it captures the
    /// whole source-set Arc and calls `search_scoped`. The default (`None`) scope
    /// stays current-lane only, byte-identical to before.
    #[tokio::test]
    async fn cross_project_search_source_scope_composes_local_ref_lane() {
        use crate::protocol::search_tools::KnowledgeSourceScope;

        let _guard = env_lock().await;
        let _gate = EnvVarGuard::set_str(LOCAL_REF_LANES_ENV, "1");

        let (current_dir, _ref_dir, index) = cross_project_current_and_ref_lanes();
        let project_indexes: HashMap<
            String,
            crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
        > = HashMap::from([(
            "proj-cross-scope".to_string(),
            crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(Arc::clone(
                &index,
            )),
        )]);
        let server = SymForgeServer::new(
            Arc::clone(&index),
            "proj-cross-scope".to_string(),
            Arc::new(parking_lot::Mutex::new(WatcherInfo::default())),
            Some(current_dir.path().to_path_buf()),
            None,
        );

        let query = |term: &str, scope: Option<KnowledgeSourceScope>| SearchKnowledgeInput {
            query: term.to_string(),
            path_prefix: None,
            source_scope: scope,
            authority_scope: None,
            project: None,
            projects: None,
            limit: None,
            max_tokens: None,
        };

        // local_refs composes the P1 ref lane: the ref-only document is now visible.
        let refs = execute_cross_project_knowledge(
            query("orbital lattice", Some(KnowledgeSourceScope::LocalRefs)),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("local_refs cross-project search");
        assert!(
            refs.contains("docs/reflane.md"),
            "local_refs must compose the P1 ref lane: {refs}"
        );

        // `all` composes the ref lane too.
        let all = execute_cross_project_knowledge(
            query("orbital lattice", Some(KnowledgeSourceScope::All)),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("all cross-project search");
        assert!(
            all.contains("docs/reflane.md"),
            "all must compose the P1 ref lane: {all}"
        );

        // A Subset selector composes the ref lane exactly like All.
        let subset = execute_cross_project_knowledge(
            query("orbital lattice", Some(KnowledgeSourceScope::LocalRefs)),
            Targets::Subset(vec!["proj-cross-scope".to_string()]),
            &project_indexes,
            &server,
        )
        .expect("subset local_refs cross-project search");
        assert!(
            subset.contains("docs/reflane.md"),
            "subset local_refs must compose the P1 ref lane: {subset}"
        );

        // Default (source_scope=None) stays current-lane only: the ref-only document
        // is invisible (the pre-fix behavior, now the ONLY difference from scoped).
        let default_ref_term = execute_cross_project_knowledge(
            query("orbital lattice", None),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("default cross-project search");
        assert!(
            !default_ref_term.contains("docs/reflane.md"),
            "default scope must not compose the ref lane: {default_ref_term}"
        );

        // ...and the default scope still performs a genuine current-lane search.
        let default_current_term = execute_cross_project_knowledge(
            query("quantum meridian", None),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("default current-lane search");
        assert!(
            default_current_term.contains("docs/current.md"),
            "default scope must search the current lane: {default_current_term}"
        );
    }

    /// [L-R09/L-G06] The same fix for `review_knowledge`: cross-project review now
    /// captures the whole source-set Arc and calls `review_scoped`, so
    /// `source_scope=local_refs`/`all` compose the P1 ref lanes. A per-source
    /// missing-document readiness is a typed section inside `review_scoped`, not a
    /// whole-scope failure; the default (`None`) scope stays current-lane only.
    #[tokio::test]
    async fn cross_project_review_source_scope_composes_local_ref_lane() {
        use crate::protocol::search_tools::{KnowledgeSourceScope, ReviewKnowledgeMode};

        let _guard = env_lock().await;
        let _gate = EnvVarGuard::set_str(LOCAL_REF_LANES_ENV, "1");

        let (current_dir, _ref_dir, index) = cross_project_current_and_ref_lanes();
        let project_indexes: HashMap<
            String,
            crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
        > = HashMap::from([(
            "proj-cross-scope".to_string(),
            crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(Arc::clone(
                &index,
            )),
        )]);
        let server = SymForgeServer::new(
            Arc::clone(&index),
            "proj-cross-scope".to_string(),
            Arc::new(parking_lot::Mutex::new(WatcherInfo::default())),
            Some(current_dir.path().to_path_buf()),
            None,
        );

        let review = |path: &str, scope: Option<KnowledgeSourceScope>| ReviewKnowledgeInput {
            mode: ReviewKnowledgeMode::Document,
            path: Some(path.to_string()),
            path_prefix: None,
            source_scope: scope,
            project: None,
            projects: None,
            limit: None,
            max_tokens: None,
        };

        // local_refs composes the ref lane: the ref-only document is reviewable and
        // the composed response keeps the top-level hash envelope.
        let refs = execute_cross_project_review(
            review("docs/reflane.md", Some(KnowledgeSourceScope::LocalRefs)),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("local_refs cross-project review");
        assert!(
            refs.contains("docs/reflane.md"),
            "local_refs review must compose the P1 ref lane: {refs}"
        );
        assert!(
            refs.contains("top_result_hash="),
            "composed review preserves the top-level hash envelope: {refs}"
        );

        // `all` composes the ref lane too; the current lane's missing-document
        // readiness folds into a typed per-source section, NOT a whole-scope failure.
        let all = execute_cross_project_review(
            review("docs/reflane.md", Some(KnowledgeSourceScope::All)),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("all cross-project review (per-source readiness is not a scope failure)");
        assert!(
            all.contains("docs/reflane.md"),
            "all review must compose the P1 ref lane: {all}"
        );

        // Default (source_scope=None) is current-lane only: a ref-only document is
        // invisible, so document-mode review over the current lane finds nothing.
        let default_ref_doc = execute_cross_project_review(
            review("docs/reflane.md", None),
            Targets::All,
            &project_indexes,
            &server,
        );
        assert!(
            default_ref_doc.is_err(),
            "default scope must not reach the ref-only document: {default_ref_doc:?}"
        );

        // ...and default review still serves the current lane's own document.
        let default_current_doc = execute_cross_project_review(
            review("docs/current.md", None),
            Targets::All,
            &project_indexes,
            &server,
        )
        .expect("default current-lane review");
        assert!(
            default_current_doc.contains("docs/current.md"),
            "default review must serve the current lane: {default_current_doc}"
        );
    }

    /// [L-R11] The wildcard/ref-mapping protection holds through the REAL
    /// tool-dispatch entry point (`execute_tool_call`), not only the
    /// `execute_cross_project_knowledge` helper the sibling test drives. A
    /// `search_knowledge` call for session B peeks `project`/`projects`, resolves a
    /// `Targets` via `resolve_targets`, and dispatches into
    /// `execute_cross_project_knowledge` against SESSION B's own `project_indexes`.
    /// So `projects=["*"]` silently scopes to session B's projects and
    /// `project=<protected_id>` is refused — session B reaches session A's
    /// ExplicitProtected project ONLY after its own direct
    /// `index_folder(allow_protected_root=true)`. This is the dispatch chain
    /// `execute_tool_call` → `resolve_targets` → `execute_cross_project_knowledge`;
    /// the freshness gate (`call_tool_handler`) merely resolves the same session-
    /// scoped runtime beforehand and cannot widen it.
    #[tokio::test]
    async fn l_r11_tool_dispatch_blocks_wildcard_and_ref_mapping_for_second_session() {
        let _guard = env_lock().await;
        let state_home = TempDir::new().expect("private user-local state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        let home_a = project_dir("symforge-l-r11-dispatch-a");
        let home_b = project_dir("symforge-l-r11-dispatch-b");
        let state = DaemonState::new();
        let session_a = state
            .open_project_session(OpenProjectRequest {
                project_root: home_a.path().display().to_string(),
                client_name: "l-r11-dispatch-a".to_string(),
                pid: None,
            })
            .expect("open session A");
        let session_b = state
            .open_project_session(OpenProjectRequest {
                project_root: home_b.path().display().to_string(),
                client_name: "l-r11-dispatch-b".to_string(),
                pid: None,
            })
            .expect("open session B");

        // A modeled protected root with a distinctive knowledge document.
        let fixture = TempDir::new().expect("protected-root fixture parent");
        let protected = fixture.path().join("System32");
        std::fs::create_dir(&protected).expect("create modeled protected root");
        std::fs::write(
            protected.join("guide.md"),
            "# Protected Guide\n\nThe orbital lattice resonates across the protected source.\n",
        )
        .expect("write protected knowledge doc");
        let protected_id = project_key(&protected.canonicalize().unwrap());

        // Session A directly opens the protected root; session B never does.
        state
            .index_folder_for_session(
                &session_a.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("session A direct protected open");

        // Wildcard via the REAL dispatch: silently scoped to session B's own
        // projects — never errors AND never reaches the protected source.
        let runtime_b = state
            .runtime_for_target(&session_b.session_id, None)
            .expect("session B runtime");
        let wildcard = execute_tool_call(
            runtime_b,
            "search_knowledge",
            serde_json::json!({ "query": "orbital lattice", "projects": ["*"] }),
        )
        .await
        .expect("wildcard over session B's own projects succeeds");
        assert!(
            !wildcard.contains(protected_id.as_str()),
            "projects=[\"*\"] must not reach another session's protected project: {wildcard}"
        );
        assert!(
            !wildcard.contains("guide.md"),
            "the protected document must not leak into session B's wildcard scope: {wildcard}"
        );

        // Explicit `project=<protected_id>` through the dispatch: refused with
        // "project not open" — an id/ref mapping cannot inherit A's membership.
        let runtime_b = state
            .runtime_for_target(&session_b.session_id, None)
            .expect("session B runtime");
        let refused = execute_tool_call(
            runtime_b,
            "search_knowledge",
            serde_json::json!({ "query": "orbital lattice", "project": protected_id.clone() }),
        )
        .await
        .expect_err("a protected project session B never opened is not addressable");
        assert!(
            refused.to_string().contains("project not open"),
            "{refused}"
        );

        // The direct-override path is the ONLY way in: session B issues its OWN
        // index_folder(allow_protected_root=true), then the dispatch resolves it.
        state
            .index_folder_for_session(
                &session_b.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("session B direct protected open");
        let runtime_b = state
            .runtime_for_target(&session_b.session_id, None)
            .expect("session B runtime after its own override");
        let after = execute_tool_call(
            runtime_b,
            "search_knowledge",
            serde_json::json!({ "query": "orbital lattice", "project": protected_id.clone() }),
        )
        .await
        .expect("session B can address the protected project after its own direct override");
        assert!(
            after.contains("guide.md"),
            "session B now sees the protected document it opened directly: {after}"
        );
    }

    #[tokio::test]
    async fn protected_membership_is_not_inherited_by_reconnect_alias_or_restart() {
        let _guard = env_lock().await;
        let state_home = TempDir::new().expect("private user-local state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        let home = project_dir("symforge-protected-restart-home");
        let fixture = TempDir::new().expect("protected-root fixture parent");
        let protected = fixture.path().join("System32");
        std::fs::create_dir(&protected).expect("create modeled protected root");
        std::fs::write(
            protected.join("lib.rs"),
            "pub fn protected_restart_symbol() {}\n",
        )
        .expect("write protected source");
        let protected_id = project_key(&protected.canonicalize().unwrap());
        let protected_state = state_home.path().join("projects").join(&protected_id);

        let state = DaemonState::new();
        let authorized = state
            .open_project_session(OpenProjectRequest {
                project_root: home.path().display().to_string(),
                client_name: "protected-authorized".to_string(),
                pid: None,
            })
            .expect("open authorized session home");
        let opened = state
            .index_folder_for_session(
                &authorized.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("direct protected open");
        assert!(opened.contains("Indexed 1 files"), "{opened}");
        assert!(protected_state.join("index.bin").is_file());

        let reconnect = state.open_project_session(OpenProjectRequest {
            project_root: protected.display().to_string(),
            client_name: "protected-reconnect".to_string(),
            pid: None,
        });
        assert!(
            reconnect.is_err(),
            "reconnect metadata must not inherit direct protected authority"
        );
        {
            let projects = state.projects.read();
            let slot = projects.get(&protected_id).expect("live protected slot");
            let metadata = slot.metadata.read();
            assert_eq!(metadata.session_ids.len(), 1);
            assert!(metadata.session_ids.contains(&authorized.session_id));
        }

        assert!(state.close_session(&authorized.session_id).is_some());
        assert!(
            state.list_projects().is_empty(),
            "closing the last session must remove the live protected slot"
        );
        drop(state);
        assert!(
            protected_state.join("index.bin").is_file(),
            "persisted protected state remains available but dormant"
        );

        let restarted = DaemonState::new();
        let fresh = restarted
            .open_project_session(OpenProjectRequest {
                project_root: home.path().display().to_string(),
                client_name: "protected-after-restart".to_string(),
                pid: None,
            })
            .expect("open normal session after restart");
        assert!(
            restarted
                .list_projects()
                .iter()
                .all(|project| project.project_id != protected_id),
            "persisted protected state must not auto-attach after restart"
        );
        assert!(
            !restarted.set_active_project(&fresh.session_id, &protected_id),
            "a persisted project id must not grant membership after restart"
        );
        assert!(
            restarted
                .runtime_for_target(&fresh.session_id, Some("System32"))
                .is_err(),
            "a persisted protected display alias must remain dormant after restart"
        );
        assert!(
            restarted
                .open_project_session(OpenProjectRequest {
                    project_root: protected.display().to_string(),
                    client_name: "protected-reconnect-after-restart".to_string(),
                    pid: None,
                })
                .is_err(),
            "reconnect after restart must still refuse protected membership"
        );

        let refused = restarted
            .index_folder_for_session(
                &fresh.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("missing override is a typed refusal");
        assert!(
            refused.contains("protected_root_requires_explicit_override"),
            "{refused}"
        );
        assert!(
            restarted
                .list_projects()
                .iter()
                .all(|project| project.project_id != protected_id),
            "refusal must leave persisted protected state dormant"
        );

        let reopened = restarted
            .index_folder_for_session(
                &fresh.session_id,
                IndexFolderInput {
                    path: protected.display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("fresh direct override after restart");
        assert!(reopened.contains("Indexed 1 files"), "{reopened}");
        assert!(
            restarted
                .runtime_for_target(&fresh.session_id, Some(&protected_id))
                .is_ok(),
            "fresh direct override must reactivate the dormant protected state"
        );
    }

    #[tokio::test]
    async fn index_folder_replay_reestablishes_live_binding_or_returns_live_postcondition_unavailable()
     {
        let _guard = env_lock().await;
        let state_home = TempDir::new().expect("private replay state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        let home = project_dir("symforge-replay-home");
        let target = project_dir("symforge-replay-target");
        let other = project_dir("symforge-replay-other");
        std::fs::write(target.path().join("src").join("one.rs"), "fn one() {}\n")
            .expect("write first target source");
        std::fs::write(other.path().join("src").join("other.rs"), "fn other() {}\n")
            .expect("write other target source");
        let target_id = project_key(&canonical_project_root(target.path()).unwrap());
        let other_id = project_key(&canonical_project_root(other.path()).unwrap());
        let state = test_daemon_state(state_home.path());
        let session = state
            .open_project_session(OpenProjectRequest {
                project_root: home.path().display().to_string(),
                client_name: "replay".to_string(),
                pid: None,
            })
            .expect("open replay home");
        let key = "b-r27-replay";

        let first_receipt = {
            let _limit = EnvVarGuard::set("SYMFORGE_MAX_INDEX_FILES", Path::new("100"));
            state
                .index_folder_for_session(
                    &session.session_id,
                    IndexFolderInput {
                        path: target.path().display().to_string(),
                        idempotency_key: Some(key.to_string()),
                        add: Some(true),
                        allow_protected_root: None,
                    },
                )
                .expect("first replay execution")
        };
        assert!(first_receipt.contains("Indexed 1 files"), "{first_receipt}");
        assert!(state.remove_project_from_session(&session.session_id, &target_id));
        std::fs::write(target.path().join("src").join("two.rs"), "fn two() {}\n")
            .expect("write second target source");

        let unavailable = {
            let _limit = EnvVarGuard::set("SYMFORGE_MAX_INDEX_FILES", Path::new("1"));
            state
                .index_folder_for_session(
                    &session.session_id,
                    IndexFolderInput {
                        path: target.path().display().to_string(),
                        idempotency_key: Some(key.to_string()),
                        add: Some(true),
                        allow_protected_root: None,
                    },
                )
                .expect("replay failure is a successful typed tool result")
        };
        assert!(unavailable.contains("applied=false"), "{unavailable}");
        assert!(
            unavailable.contains("outcome=live_postcondition_unavailable"),
            "{unavailable}"
        );
        assert!(
            unavailable.contains(&first_receipt),
            "typed failure must preserve the immutable historical receipt: {unavailable}"
        );
        assert!(
            state
                .runtime_for_target(&session.session_id, Some(&target_id))
                .is_err(),
            "failed replay must not claim or attach a live binding"
        );

        let restored = {
            let _limit = EnvVarGuard::set("SYMFORGE_MAX_INDEX_FILES", Path::new("100"));
            state
                .index_folder_for_session(
                    &session.session_id,
                    IndexFolderInput {
                        path: target.path().display().to_string(),
                        idempotency_key: Some(key.to_string()),
                        add: Some(true),
                        allow_protected_root: None,
                    },
                )
                .expect("replay restores live postcondition")
        };
        assert_eq!(
            restored, first_receipt,
            "stored receipt must remain immutable"
        );
        assert!(
            state
                .runtime_for_target(&session.session_id, Some(&target_id))
                .is_ok(),
            "stored success may return only after live membership is restored"
        );
        assert!(state.remove_project_from_session(&session.session_id, &target_id));

        let override_conflict = state
            .index_folder_for_session(
                &session.session_id,
                IndexFolderInput {
                    path: target.path().display().to_string(),
                    idempotency_key: Some(key.to_string()),
                    add: Some(true),
                    allow_protected_root: Some(true),
                },
            )
            .expect("override change is a deterministic tool-level conflict");
        assert!(
            override_conflict.contains("Idempotency conflict"),
            "{override_conflict}"
        );
        assert!(
            state
                .runtime_for_target(&session.session_id, Some(&target_id))
                .is_err(),
            "override conflict must happen before live attachment"
        );

        let path_conflict = state
            .index_folder_for_session(
                &session.session_id,
                IndexFolderInput {
                    path: other.path().display().to_string(),
                    idempotency_key: Some(key.to_string()),
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("path change is a deterministic tool-level conflict");
        assert!(
            path_conflict.contains("Idempotency conflict"),
            "{path_conflict}"
        );
        assert!(
            state
                .runtime_for_target(&session.session_id, Some(&other_id))
                .is_err(),
            "path conflict must happen before loading or attaching the other project"
        );
    }

    #[tokio::test]
    async fn post_bind_state_write_failure_degrades_durability_not_live_readiness() {
        let _guard = env_lock().await;
        let project = project_dir("symforge-post-bind-state-failure");
        std::fs::write(
            project.path().join("src").join("main.rs"),
            "fn main() { println!(\"still live\"); }\n",
        )
        .expect("write queryable source");
        let state = DaemonState::new();
        let session = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "durability-oracle".to_string(),
                pid: None,
            })
            .expect("bind and publish project before failing state writes");
        let slot = state
            .projects
            .read()
            .get(&session.project_id)
            .cloned()
            .expect("bound project slot");
        let (canonical_root, placement, publication_before, watcher_info) = {
            let project = slot.metadata.read();
            (
                project.canonical_root.clone(),
                project.state_placement.clone(),
                project.index.data_plane().published_generation(),
                Arc::clone(&project.watcher_info),
            )
        };
        let state_dir = match &placement {
            StatePlacement::ProjectLocal { directory }
            | StatePlacement::UserLocal { directory, .. } => directory.as_path().to_path_buf(),
            StatePlacement::MemoryOnly { failures } => {
                panic!("fixture requires durable placement, got memory-only: {failures:?}")
            }
        };
        let before = state
            .project_health(&session.project_id)
            .expect("health before state failure");
        assert_eq!(before.index_state, "Ready");
        assert_eq!(
            before.durability,
            crate::domain::CapabilityStatus::Available
        );
        assert_eq!(
            before.capabilities.checkpoint,
            crate::domain::CapabilityStatus::Available
        );

        std::fs::remove_dir_all(&state_dir).expect("remove writable state directory");
        std::fs::write(&state_dir, b"state owner became unwritable")
            .expect("replace state directory with a blocking file");
        let checkpoint = execute_tool_call(
            state
                .session_runtime(&session.session_id)
                .expect("session runtime before checkpoint"),
            "checkpoint_now",
            serde_json::json!({ "verify_after_write": true }),
        )
        .await
        .expect("checkpoint failure remains a typed tool response");
        assert!(
            checkpoint.contains("Checkpoint failed"),
            "state write must fail in the fixture: {checkpoint}"
        );

        let after = state
            .project_health(&session.project_id)
            .expect("health after state failure");
        assert_eq!(after.project_id, before.project_id);
        assert_eq!(after.canonical_root, before.canonical_root);
        assert_eq!(after.index_state, "Ready");
        assert_eq!(
            after.durability,
            crate::domain::CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        );
        assert_eq!(
            after.capabilities.checkpoint,
            crate::domain::CapabilityStatus::Unavailable {
                reason: crate::domain::CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        );
        assert_eq!(
            after.capabilities.repository_curation,
            crate::domain::CapabilityStatus::Unavailable {
                reason:
                    crate::domain::CapabilityUnavailableReason::DurableMutationReplayUnavailable,
            }
        );

        {
            let project = slot.metadata.read();
            assert_eq!(project.canonical_root, canonical_root);
            assert_eq!(project.state_placement, placement);
            let publication_after = project.index.data_plane().published_generation();
            assert!(
                publication_after.publication_generation
                    >= publication_before.publication_generation,
                "derived-only background publication may advance but never rewind"
            );
            assert_eq!(
                publication_after.content_generation, publication_before.content_generation,
                "failed durability must not mutate live content identity"
            );
            assert_eq!(
                publication_after.project_generation,
                publication_before.project_generation
            );
            assert_eq!(publication_after.source, publication_before.source);
            assert_eq!(
                publication_after.source_version,
                publication_before.source_version
            );
            assert_eq!(
                publication_after
                    .manifest
                    .as_ref()
                    .map(|manifest| &manifest.digest),
                publication_before
                    .manifest
                    .as_ref()
                    .map(|manifest| &manifest.digest)
            );
            assert!(Arc::ptr_eq(&project.watcher_info, &watcher_info));
        }
        let query = execute_tool_call(
            state
                .session_runtime(&session.session_id)
                .expect("session runtime after checkpoint failure"),
            "get_file_content",
            serde_json::json!({ "path": "src/main.rs" }),
        )
        .await
        .expect("live query after state failure");
        assert!(
            query.contains("still live"),
            "live query regressed: {query}"
        );
    }

    #[tokio::test]
    async fn reindex_preserves_resolved_placement_until_new_project_instance() {
        let _guard = env_lock().await;
        let project = project_dir("symforge-placement-lifetime");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn placement_lifetime() {}\n",
        )
        .expect("write source");
        let project_state = project.path().join(".symforge");
        std::fs::write(&project_state, b"block project-local state")
            .expect("install project-local blocker");

        let home = TempDir::new().expect("isolated user-local state");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", home.path());
        let state = DaemonState::with_token_and_control_state(
            "placement-lifetime-token".to_string(),
            Some(ControlStateDir::new(home.path().to_path_buf())),
        );
        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "placement-lifetime-first".to_string(),
                pid: None,
            })
            .expect("open with user-local fallback");
        let first_slot = state
            .projects
            .read()
            .get(&first.project_id)
            .cloned()
            .expect("first project slot");
        let (canonical_root, first_placement) = {
            let project = first_slot.metadata.read();
            (
                project.canonical_root.clone(),
                project.state_placement.clone(),
            )
        };
        let first_state_dir = match &first_placement {
            StatePlacement::UserLocal { directory, .. } => directory.as_path().to_path_buf(),
            other => panic!("blocked project-local state must fall back, got {other:?}"),
        };
        assert!(first_state_dir.starts_with(home.path()));

        std::fs::remove_file(&project_state).expect("make project-local state available");
        let output = state
            .index_folder_for_session(
                &first.session_id,
                IndexFolderInput {
                    path: project.path().display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("reindex same live project");
        assert!(
            output.starts_with("Indexed "),
            "unexpected receipt: {output}"
        );
        let same_slot = state
            .projects
            .read()
            .get(&first.project_id)
            .cloned()
            .expect("same live project slot");
        assert!(Arc::ptr_eq(&first_slot, &same_slot));
        assert_eq!(
            same_slot.metadata.read().state_placement,
            first_placement,
            "same live ProjectInstance must keep its resolved owner"
        );
        assert!(
            !project_state.exists(),
            "same live ProjectInstance must not re-run placement or probe/create a new owner"
        );

        drop(same_slot);
        drop(first_slot);
        let closed = state
            .close_session(&first.session_id)
            .expect("close first project instance");
        assert!(closed.project_removed);

        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "placement-lifetime-second".to_string(),
                pid: None,
            })
            .expect("construct fresh project instance");
        let second_slot = state
            .projects
            .read()
            .get(&second.project_id)
            .cloned()
            .expect("fresh project slot");
        match &second_slot.metadata.read().state_placement {
            StatePlacement::ProjectLocal { directory } => {
                assert_eq!(directory.as_path(), canonical_root.join(".symforge"));
                assert_ne!(directory.as_path(), first_state_dir);
            }
            other => panic!("fresh instance must recover project-local durability, got {other:?}"),
        }
        assert!(project_state.is_dir());
        assert!(
            state
                .close_session(&second.session_id)
                .expect("close fresh project instance")
                .project_removed
        );
    }

    #[tokio::test]
    async fn cold_start_capacity_refusal_stays_nonready_with_typed_freshness() {
        let _guard = env_lock().await;
        let _entry_limit = EnvVarGuard::set("SYMFORGE_MAX_INDEX_FILES", Path::new("1"));
        let project = project_dir("symforge-capacity-refusal");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn one() {}\n",
        )
        .expect("write first source");
        std::fs::write(project.path().join("README.md"), "# second catalog entry\n")
            .expect("write second source");

        let control = TempDir::new().expect("isolated daemon control state");
        let state = DaemonState::with_token_and_control_state(
            "capacity-refusal-token".to_string(),
            Some(ControlStateDir::new(control.path().to_path_buf())),
        );
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "capacity-refusal-client".to_string(),
                pid: None,
            })
            .expect("typed capacity refusal must keep the daemon responsive");
        let slot = state
            .projects
            .read()
            .get(&opened.project_id)
            .cloned()
            .expect("non-ready project slot remains registered");
        let project = slot.metadata.read();

        assert!(!project.index.data_plane().read().is_ready());
        assert!(
            project.index.data_plane().scout_plan().is_none(),
            "no partial plan may publish"
        );
        assert!(matches!(
            project.index.data_plane().freshness_status().as_ref(),
            crate::domain::FreshnessStatus::Degraded {
                last_valid_content_generation: 0,
                reason_codes,
            } if reason_codes == &[crate::domain::FreshnessReason::CatalogEntryCapacityExceeded]
        ));
        drop(project);

        let health = state
            .project_health(&opened.project_id)
            .expect("registered non-ready project health");
        assert!(matches!(
            health.freshness,
            crate::domain::FreshnessStatus::Degraded {
                last_valid_content_generation: 0,
                ref reason_codes,
            } if reason_codes == &[crate::domain::FreshnessReason::CatalogEntryCapacityExceeded]
        ));
        assert!(
            state
                .close_session(&opened.session_id)
                .expect("close capacity-refusal session")
                .project_removed
        );
    }

    #[test]
    fn test_open_project_session_refuses_sensitive_root() {
        // Regression: `open_project_session` performs a full `LiveIndex::load`
        // with no guard of its own. A session-open on a sensitive root must be
        // refused cleanly (an `Err`, never a panic, never a load) before any IO.
        let state = DaemonState::new();

        // A sensitive system root that exists and canonicalizes on this host.
        #[cfg(windows)]
        let sensitive = r"C:\Windows";
        #[cfg(unix)]
        let sensitive = "/etc";

        let result = state.open_project_session(OpenProjectRequest {
            project_root: sensitive.to_string(),
            client_name: "claude".to_string(),
            pid: None,
        });

        let err = result.expect_err("sensitive root must be refused, not opened");
        let msg = err.to_string();
        assert!(
            msg.contains("Refused to open session for sensitive system path"),
            "open_project_session must refuse sensitive root `{sensitive}`, got: {msg}"
        );

        // The refusal must not have created any project.
        assert!(
            state.list_projects().is_empty(),
            "refusal must not create a project for the sensitive root"
        );
    }

    // ── Feature 012 Phase 2 — close_session reaps ALL referenced projects ────────
    //
    // The advertised multi-project leak fix: a session that additively opened a
    // SECOND project references BOTH (active A + additive B). Closing it must
    // detach from EVERY referenced project and tear down each whose session set
    // then empties — not just the active one. A leak would leave B in the project
    // map (and its watcher running) forever. This runs under a multi-thread Tokio
    // runtime so `activate()` actually spawns real watcher tasks (sync tests get
    // `None` watchers), letting us assert teardown via each project's `stop_token`.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_close_session_reaps_all_working_set_projects_and_watchers() {
        let project_a = project_dir("symforge-reap-a");
        let project_b = project_dir("symforge-reap-b");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");
        let state = DaemonState::new();

        // Open a session bound to A, then additively open B into its working set.
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "reap".to_string(),
                pid: None,
            })
            .expect("open A");
        let active_a = opened.project_id.clone();
        state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: None,
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("additive open B");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        // Both projects are open and the session references BOTH (active + additive).
        assert_eq!(
            state.list_projects().len(),
            2,
            "A and B both open before close"
        );

        // Capture each project's watcher stop_token BEFORE closing so we can prove
        // the teardown path (abort_watcher_task -> stop_token = true) ran for BOTH.
        // Under the multi-thread runtime, activate()/reload() spawned real watchers.
        let (token_a, token_b, watcher_a_live, watcher_b_live) = {
            let projects = state.projects.read();
            let a_slot = projects.get(&active_a).expect("A loaded");
            let b_slot = projects.get(&project_b_id).expect("B loaded");
            let a = a_slot.metadata.read();
            let b = b_slot.metadata.read();
            (
                Arc::clone(&a.stop_token),
                Arc::clone(&b.stop_token),
                a.watcher_task.is_some(),
                b.watcher_task.is_some(),
            )
        };
        assert!(
            watcher_a_live && watcher_b_live,
            "both projects must have a live watcher task before close \
             (A: {watcher_a_live}, B: {watcher_b_live})"
        );
        assert!(
            !token_a.load(Ordering::Acquire) && !token_b.load(Ordering::Acquire),
            "watcher stop tokens must be unset (false) while the projects are live"
        );

        // Close the only session.
        let closed = state
            .close_session(&opened.session_id)
            .expect("close session");
        // Wire contract: reported fields describe the ACTIVE project (A).
        assert_eq!(
            closed.project_id, active_a,
            "reported pid is the active project A"
        );
        assert_eq!(closed.remaining_sessions, 0);
        assert!(closed.project_removed, "active project A reaped");

        // BOTH projects reaped (the leak fix): the map is empty, not just A gone.
        assert!(
            state.list_projects().is_empty(),
            "close_session must reap BOTH A and B, leaving no open project: {:?}",
            state.list_projects()
        );

        // BOTH watchers torn down: each project's stop_token was flipped true by
        // abort_watcher_task during reaping (the additive sibling B included).
        assert!(
            token_a.load(Ordering::Acquire),
            "A's watcher stop_token must be set after close (watcher torn down)"
        );
        assert!(
            token_b.load(Ordering::Acquire),
            "B's watcher stop_token must be set after close (additive sibling watcher torn down)"
        );
    }

    #[test]
    fn test_close_session_removes_project_when_last_session_leaves() {
        let project = project_dir("symforge-daemon-d");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: None,
            })
            .expect("first session");
        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: None,
            })
            .expect("second session");

        let close_first = state
            .close_session(&first.session_id)
            .expect("close first session");
        assert_eq!(close_first.remaining_sessions, 1);
        assert!(!close_first.project_removed);
        assert_eq!(state.list_projects().len(), 1);

        let close_second = state
            .close_session(&second.session_id)
            .expect("close second session");
        assert_eq!(close_second.remaining_sessions, 0);
        assert!(close_second.project_removed);
        assert!(state.list_projects().is_empty());
    }

    #[test]
    fn test_close_session_handles_orphan_session_record_without_panic() {
        let state = DaemonState::new();
        let session_id = "stale-session".to_string();
        state.sessions.write().insert(
            session_id.clone(),
            SessionRecord {
                session_id: session_id.clone(),
                active_project_id: "missing-project".to_string(),
                home_project_id: "missing-project".to_string(),
                working_set: Arc::new(RwLock::new(WorkingSet::new())),
                servers: HashMap::new(),
                client_name: "codex".to_string(),
                pid: Some(777),
                opened_at: SystemTime::now(),
                last_seen_at: AtomicU64::new(now_epoch_millis()),
            },
        );

        let closed = state
            .close_session(&session_id)
            .expect("orphan session should still close");
        assert_eq!(closed.session_id, session_id);
        assert_eq!(closed.project_id, "orphan");
        assert_eq!(closed.remaining_sessions, 0);
        assert!(!closed.project_removed);
        assert!(state.close_session(&closed.session_id).is_none());
    }

    #[test]
    fn test_heartbeat_updates_known_session() {
        let project = project_dir("symforge-daemon-e");
        let state = DaemonState::new();

        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(123),
            })
            .expect("session");

        let known = state.heartbeat(&opened.session_id);
        let unknown = state.heartbeat("missing-session");

        assert!(known.known_session);
        assert!(!unknown.known_session);
    }

    #[test]
    fn test_project_health_and_sessions_expose_instance_metadata() {
        let project = project_dir("symforge-daemon-f");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(111),
            })
            .expect("first session");
        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(222),
            })
            .expect("second session");

        let health = state
            .project_health(&first.project_id)
            .expect("project health should exist");
        assert_eq!(health.project_id, first.project_id);
        assert_eq!(health.session_count, 2);
        assert_eq!(health.index_state, "Ready");

        let sessions = state
            .list_sessions(&first.project_id)
            .expect("session list should exist");
        assert_eq!(sessions.len(), 2);
        assert_eq!(sessions[0].project_id, first.project_id);
        assert!(
            sessions
                .iter()
                .any(|session| session.client_name == "claude")
        );
        assert!(
            sessions
                .iter()
                .any(|session| session.client_name == "codex")
        );
        assert!(sessions.iter().any(|session| session.pid == Some(111)));
        assert!(sessions.iter().any(|session| session.pid == Some(222)));
        assert_ne!(first.session_id, second.session_id);
    }

    #[test]
    fn test_sessions_on_same_project_do_not_share_context_cache() {
        let project = project_dir("symforge-session-state-isolation");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn shared_project() {}\n",
        )
        .expect("write source");
        let state = DaemonState::new();

        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "first".to_string(),
                pid: None,
            })
            .expect("first session");
        let second = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "second".to_string(),
                pid: None,
            })
            .expect("second session");

        let first_runtime = state
            .session_runtime(&first.session_id)
            .expect("first runtime");
        let second_runtime = state
            .session_runtime(&second.session_id)
            .expect("second runtime");

        first_runtime
            .server
            .session_context
            .record_file_content_fetch("src/lib.rs", 42, 100, "deadbeefcafe");
        assert!(
            first_runtime
                .server
                .session_context
                .try_file_content_cache_hit("src/lib.rs", 42, false)
                .is_some(),
            "the originating session should observe its own cache entry"
        );
        assert!(
            second_runtime
                .server
                .session_context
                .try_file_content_cache_hit("src/lib.rs", 42, false)
                .is_none(),
            "a second session on the same project must not inherit the first session's cache"
        );
        assert!(!Arc::ptr_eq(
            &first_runtime.server.session_context,
            &second_runtime.server.session_context,
        ));
        assert!(!Arc::ptr_eq(
            &first_runtime.server.ccr_store,
            &second_runtime.server.ccr_store,
        ));
        assert!(!Arc::ptr_eq(
            &first_runtime.server.stel_ledger,
            &second_runtime.server.stel_ledger,
        ));
        assert!(Arc::ptr_eq(
            first_runtime.index.data_plane(),
            second_runtime.index.data_plane(),
        ));
        assert!(Arc::ptr_eq(
            &first_runtime.token_stats,
            &second_runtime.token_stats,
        ));
    }

    /// Issue #585: on a daemon connection every producing tool stores its CCR
    /// blob in the daemon-side session server, so `symforge_retrieve` must be
    /// daemon-routed and redeem from THAT store. The adapter-side handler used
    /// to answer from its own empty store, making every advertised handle
    /// irredeemable.
    #[tokio::test]
    async fn symforge_retrieve_redeems_from_the_session_runtime_store() {
        let project = project_dir("symforge-retrieve-session-store");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn redeemable() {}\n",
        )
        .expect("write source");
        let state = Arc::new(DaemonState::new());
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "retriever".to_string(),
                pid: None,
            })
            .expect("session");

        let stored_body = "── symforge get_symbol ──\npub fn redeemable() {}\n";
        let handle = {
            let runtime = state
                .runtime_for_target(&opened.session_id, None)
                .expect("session runtime");
            runtime
                .server
                .ccr_store
                .lock()
                .insert("get_symbol", stored_body.to_string(), None)
        };

        // The daemon-private route pin must be accepted for this tool; the
        // adapter synthesizes it for every selector-less daemon call.
        let mut pinned = serde_json::json!({
            "hash": handle,
            crate::daemon::PRIVATE_PROJECT_ROUTE_PIN: opened.project_id.clone(),
        });
        assert_eq!(
            take_private_project_route_pin("symforge_retrieve", &mut pinned)
                .expect("the pin is legal for symforge_retrieve"),
            Some(opened.project_id.clone()),
        );

        let runtime = state
            .runtime_for_target(&opened.session_id, None)
            .expect("session runtime");
        let body = execute_tool_call(runtime, "symforge_retrieve", pinned)
            .await
            .expect("daemon-side retrieve dispatch");
        assert_eq!(
            body, stored_body,
            "the daemon dispatch must round-trip the session store's exact bytes"
        );

        let runtime = state
            .runtime_for_target(&opened.session_id, None)
            .expect("session runtime");
        let miss = execute_tool_call(
            runtime,
            "symforge_retrieve",
            serde_json::json!({ "hash": "0123456789ab" }),
        )
        .await
        .expect("a miss is a message, not a dispatch error");
        assert!(
            miss.contains("stale or expired"),
            "an unknown handle must keep the honest miss message: {miss}"
        );
    }

    #[test]
    fn test_project_b_reads_while_project_a_reloads() {
        let project_a = project_dir("symforge-slot-isolation-a");
        let project_b = project_dir("symforge-slot-isolation-b");
        std::fs::write(
            project_a.path().join("src").join("lib.rs"),
            "pub fn project_a() {}\n",
        )
        .expect("write A");
        std::fs::write(
            project_b.path().join("src").join("lib.rs"),
            "pub fn project_b() {}\n",
        )
        .expect("write B");

        let state = Arc::new(DaemonState::new());
        let opened_a = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "a".to_string(),
                pid: None,
            })
            .expect("open A");
        let opened_b = state
            .open_project_session(OpenProjectRequest {
                project_root: project_b.path().display().to_string(),
                client_name: "b".to_string(),
                pid: None,
            })
            .expect("open B");
        let root_a = canonical_project_root(project_a.path()).expect("canonical A");
        let slot_a = state
            .projects
            .read()
            .get(&opened_a.project_id)
            .cloned()
            .expect("A slot");

        let (reload_entered_tx, reload_entered_rx) = std::sync::mpsc::sync_channel(1);
        let (release_reload_tx, release_reload_rx) = std::sync::mpsc::sync_channel(1);
        let reload = std::thread::spawn(move || {
            slot_a.reload_with(&root_a, |index, root| {
                reload_entered_tx.send(()).expect("signal reload entered");
                release_reload_rx.recv().expect("release reload");
                index.reload(root)
            })
        });
        reload_entered_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("A reload should enter its mutation lane");

        let state_for_read = Arc::clone(&state);
        let session_b = opened_b.session_id.clone();
        let project_b_id = opened_b.project_id.clone();
        let (read_done_tx, read_done_rx) = std::sync::mpsc::sync_channel(1);
        let reader = std::thread::spawn(move || {
            let runtime = state_for_read.session_runtime(&session_b).is_some();
            let health = state_for_read.project_health(&project_b_id).is_some();
            let sessions = state_for_read.list_sessions(&project_b_id).is_some();
            read_done_tx
                .send((runtime, health, sessions))
                .expect("report B reads");
        });
        assert_eq!(
            read_done_rx
                .recv_timeout(Duration::from_secs(1))
                .expect("project B reads must not wait for project A reload"),
            (true, true, true)
        );

        release_reload_tx.send(()).expect("release A reload");
        reload
            .join()
            .expect("A reload thread")
            .expect("A reload result");
        reader.join().expect("B reader thread");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn daemon_reload_latches_gap_when_abort_bypasses_watcher_tail() {
        let project = project_dir("symforge-daemon-abort-gap");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn daemon_abort_gap() {}\n",
        )
        .expect("write source");

        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "daemon-abort-gap".to_string(),
                pid: None,
            })
            .expect("open project");
        let slot = state
            .projects
            .read()
            .get(&opened.project_id)
            .cloned()
            .expect("project slot");
        {
            let mut project = slot.metadata.write();
            let existing = project
                .watcher_task
                .take()
                .expect("tokio-backed activation must install a watcher task");
            existing.abort();
            project.stop_token = Arc::new(AtomicBool::new(false));
            project.watcher_task = Some(tokio::spawn(std::future::pending::<()>()));
        }

        let root = canonical_project_root(project.path()).expect("canonical project");
        let latched = |slot: &ProjectSlot| {
            let project = slot.metadata.read();
            let freshness = project.index.shared().freshness_status();
            matches!(
                freshness.as_ref(),
                crate::domain::FreshnessStatus::Degraded { reason_codes, .. }
                    if reason_codes.contains(&crate::domain::FreshnessReason::WatcherUnavailable)
            )
        };

        // Positive control first: the FAILED reload is the hole. The abort
        // already ran, the retained index keeps serving, and nothing covered
        // the root until the replacement watcher started.
        let error = slot
            .reload_with(&root, |_index, _root| anyhow::bail!("rebuild refused"))
            .expect_err("the injected rebuild failure must propagate");
        assert!(
            error.to_string().contains("rebuild refused"),
            "unexpected error: {error}"
        );
        assert!(
            latched(&slot),
            "daemon abort skips the watcher's cooperative tail, so a failed reload must latch the gap itself"
        );
        assert!(
            slot.metadata.read().watcher_task.is_some(),
            "a failed reload must still install a replacement watcher"
        );

        // Negative control on a fresh slot: a SUCCESSFUL reload is a full
        // re-scan that supersedes anything the aborted observer missed, so it
        // must NOT latch -- `WatcherUnavailable` would 503 every sidecar read
        // of a project that was just rebuilt from scratch.
        let fresh = DaemonState::new();
        let reopened = fresh
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "daemon-abort-gap-success".to_string(),
                pid: None,
            })
            .expect("open project again");
        let fresh_slot = fresh
            .projects
            .read()
            .get(&reopened.project_id)
            .cloned()
            .expect("fresh project slot");
        assert!(
            !latched(&fresh_slot),
            "precondition: a freshly opened project must start un-latched"
        );
        fresh_slot
            .reload_with(&root, |index, root| index.reload(root))
            .expect("successful reload");
        assert!(
            !latched(&fresh_slot),
            "a successful reload is a full re-scan and must not report WatcherUnavailable"
        );

        fresh_slot.stop();
        slot.stop();
    }

    /// Feature 020 Slice 0 causal control for design defect 2.4 — project
    /// loading is not single-flight.
    ///
    /// `ensure_project_slot_for_session_with` reads the project map, runs the
    /// complete load OUTSIDE the map lock, and only then calls
    /// `entry.or_insert`. Concurrent first opens of one root therefore each
    /// build a full `ProjectInstance`; `or_insert` keeps one and drops the rest
    /// after they have already paid their I/O, parse, and memory cost.
    ///
    /// The waste leaves no other trace: the loser is never activated, so it
    /// starts no watcher and appears in no listing or health response. That is
    /// why the loader is counted here rather than asserted about indirectly.
    /// The closure is production's own — `ProjectInstance::load`, exactly as
    /// `ensure_project_slot_for_session` supplies it — so this counts real
    /// loads, not a stand-in.
    ///
    /// One uncontended first open — N sessions racing a missing slot with no
    /// concurrent detach — must cost exactly one cold load.
    #[test]
    fn concurrent_first_open_performs_exactly_one_cold_load() {
        let project = project_dir("symforge-slot-single-flight");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn single_flight() {}\n",
        )
        .expect("write source");
        let canonical_root = project.path().to_path_buf();
        let state = Arc::new(DaemonState::new());
        let project_id = "project-single-flight";

        const RACERS: usize = 4;
        let loads = Arc::new(AtomicUsize::new(0));
        let start = Arc::new(std::sync::Barrier::new(RACERS));
        let racers: Vec<_> = (0..RACERS)
            .map(|racer| {
                let state = Arc::clone(&state);
                let loads = Arc::clone(&loads);
                let start = Arc::clone(&start);
                let root = canonical_root.clone();
                std::thread::spawn(move || {
                    start.wait();
                    state.ensure_project_slot_for_session_with(
                        &format!("session-{racer}"),
                        project_id,
                        || {
                            loads.fetch_add(1, Ordering::AcqRel);
                            ProjectInstance::load(&root)
                        },
                    )
                })
            })
            .collect();

        let slots: Vec<_> = racers
            .into_iter()
            .map(|racer| racer.join().expect("racer thread").expect("slot"))
            .collect();

        for slot in &slots {
            assert!(
                Arc::ptr_eq(slot, &slots[0]),
                "precondition: every racer must join the one authoritative slot"
            );
        }
        assert_eq!(
            loads.load(Ordering::Acquire),
            1,
            "{RACERS} concurrent first opens of one root must perform exactly one \
             cold load; every extra load is a complete project index built, paid \
             for, and discarded by `or_insert`"
        );
    }

    #[test]
    fn test_same_project_reads_prior_generation_during_reload() {
        let project = project_dir("symforge-slot-same-project");
        let source = project.path().join("src").join("lib.rs");
        std::fs::write(&source, "pub fn prior_generation() {}\n").expect("write prior");
        let state = Arc::new(DaemonState::new());
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "same-project".to_string(),
                pid: None,
            })
            .expect("open project");
        let prior = Arc::clone(
            &state
                .session_runtime(&opened.session_id)
                .expect("prior runtime")
                .index
                .data_plane()
                .read(),
        );
        std::fs::write(&source, "pub fn next_generation() {}\n").expect("write next");

        let slot = state
            .projects
            .read()
            .get(&opened.project_id)
            .cloned()
            .expect("project slot");
        let root = canonical_project_root(project.path()).expect("canonical project");
        let (first_entered_tx, first_entered_rx) = std::sync::mpsc::sync_channel(1);
        let (release_first_tx, release_first_rx) = std::sync::mpsc::sync_channel(1);
        let first_slot = Arc::clone(&slot);
        let first_root = root.clone();
        let first_reload = std::thread::spawn(move || {
            first_slot.reload_with(&first_root, |index, root| {
                first_entered_tx.send(()).expect("signal first reload");
                release_first_rx.recv().expect("release first reload");
                index.reload(root)
            })
        });
        first_entered_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("first reload should enter");

        let (second_entered_tx, second_entered_rx) = std::sync::mpsc::sync_channel(1);
        let second_reload = std::thread::spawn(move || {
            slot.reload_with(&root, |index, root| {
                second_entered_tx.send(()).expect("signal second reload");
                index.reload(root)
            })
        });
        assert!(
            second_entered_rx
                .recv_timeout(Duration::from_millis(150))
                .is_err(),
            "same-project reloads must serialize on the mutation lane"
        );

        let during = Arc::clone(
            &state
                .session_runtime(&opened.session_id)
                .expect("runtime during reload")
                .index
                .data_plane()
                .read(),
        );
        assert!(
            Arc::ptr_eq(&prior, &during),
            "reads must retain the prior published index while reload builds"
        );

        release_first_tx.send(()).expect("release first reload");
        first_reload
            .join()
            .expect("first reload thread")
            .expect("first reload result");
        second_entered_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("second reload should enter after first finishes");
        second_reload
            .join()
            .expect("second reload thread")
            .expect("second reload result");

        let after = Arc::clone(
            &state
                .session_runtime(&opened.session_id)
                .expect("runtime after reload")
                .index
                .data_plane()
                .read(),
        );
        assert!(
            !Arc::ptr_eq(&prior, &after),
            "successful reload must atomically publish a new index generation"
        );
    }

    #[tokio::test]
    async fn test_spawn_daemon_serves_project_and_session_endpoints() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-http");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let daemon_health = client
            .get(format!("{base_url}/health"))
            .send()
            .await
            .expect("health request")
            .error_for_status()
            .expect("health status")
            .json::<DaemonHealth>()
            .await
            .expect("health body");
        assert_eq!(daemon_health.project_count, 0);
        assert_eq!(daemon_health.session_count, 0);
        assert_eq!(daemon_health.daemon_version, env!("CARGO_PKG_VERSION"));
        // Fail-closed: the daemon always establishes a token, so auth is always
        // required even when no env pin was set (this test sets none).
        assert!(daemon_health.auth_required);
        assert!(!daemon_health.executable_path.is_empty());

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(4242),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let project_health = client
            .get(format!(
                "{base_url}/v1/projects/{}/health",
                opened.project_id
            ))
            .send()
            .await
            .expect("project health request")
            .error_for_status()
            .expect("project health status")
            .json::<ProjectHealth>()
            .await
            .expect("project health body");
        assert_eq!(project_health.project_id, opened.project_id);
        assert_eq!(project_health.session_count, 1);
        assert_eq!(project_health.index_state, "Ready");

        let sessions = client
            .get(format!(
                "{base_url}/v1/projects/{}/sessions",
                opened.project_id
            ))
            .send()
            .await
            .expect("sessions request")
            .error_for_status()
            .expect("sessions status")
            .json::<Vec<SessionSummary>>()
            .await
            .expect("sessions body");
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].session_id, opened.session_id);
        assert_eq!(sessions[0].client_name, "codex");
        assert_eq!(sessions[0].pid, Some(4242));

        let heartbeat = client
            .post(format!(
                "{base_url}/v1/sessions/{}/heartbeat",
                opened.session_id
            ))
            .send()
            .await
            .expect("heartbeat request")
            .error_for_status()
            .expect("heartbeat status")
            .json::<HeartbeatResponse>()
            .await
            .expect("heartbeat body");
        assert!(heartbeat.known_session);

        let closed = client
            .delete(format!("{base_url}/v1/sessions/{}", opened.session_id))
            .send()
            .await
            .expect("close request")
            .error_for_status()
            .expect("close status")
            .json::<CloseSessionResponse>()
            .await
            .expect("close body");
        assert!(closed.project_removed);
        assert_eq!(closed.remaining_sessions, 0);

        let final_health = client
            .get(format!("{base_url}/health"))
            .send()
            .await
            .expect("final health request")
            .error_for_status()
            .expect("final health status")
            .json::<DaemonHealth>()
            .await
            .expect("final health body");
        assert_eq!(final_health.project_count, 0);
        assert_eq!(final_health.session_count, 0);
        assert_eq!(final_health.daemon_version, env!("CARGO_PKG_VERSION"));
        assert!(!final_health.executable_path.is_empty());

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PID_FILE,
        ))
        .await;
        assert!(
            !test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE).exists(),
            "daemon port file should be removed on shutdown"
        );
        assert!(
            !test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PID_FILE).exists(),
            "daemon pid file should be removed on shutdown"
        );
    }

    #[tokio::test]
    async fn test_daemon_auth_token_protects_session_tool_and_sidecar_routes() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let _bind_guard = EnvVarGuard::unset(DAEMON_BIND_ENV);
        let _allow_guard = EnvVarGuard::unset(DAEMON_ALLOW_NON_LOOPBACK_ENV);
        // Assembled at runtime: a credential-shaped source literal would trip
        // this repository's own detector (see
        // `repository_source_is_clean_under_its_own_detector`). Runtime bytes are
        // unchanged.
        let token = ["sfr03", "-test-", "to", "ken"].concat();
        let _auth_guard = EnvVarGuard::set_str(DAEMON_AUTH_TOKEN_ENV, &token);
        let project = project_dir("symforge-daemon-auth");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        // This test drives auth explicitly (missing / wrong / correct token), so
        // it uses a bare client and attaches `.bearer_auth` per request rather
        // than the always-authed `authed_client` helper.
        let client = reqwest::Client::new();
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let health_body = client
            .get(format!("{base_url}/health"))
            .send()
            .await
            .expect("health request")
            .error_for_status()
            .expect("health status")
            .text()
            .await
            .expect("health body");
        assert!(
            !health_body.contains(&token),
            "health body must not leak auth token"
        );
        let daemon_health: DaemonHealth = serde_json::from_str(&health_body).expect("health json");
        assert!(daemon_health.auth_required);

        let missing_projects = client
            .get(format!("{base_url}/v1/projects"))
            .send()
            .await
            .expect("projects request");
        assert_eq!(missing_projects.status(), StatusCode::UNAUTHORIZED);
        let missing_body = missing_projects.text().await.expect("missing auth body");
        assert!(
            !missing_body.contains(&token),
            "401 body must not leak auth token"
        );

        let wrong_open = client
            .post(format!("{base_url}/v1/sessions/open"))
            .bearer_auth("wrong-token")
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(5150),
            })
            .send()
            .await
            .expect("wrong auth open request");
        assert_eq!(wrong_open.status(), StatusCode::UNAUTHORIZED);
        let wrong_body = wrong_open.text().await.expect("wrong auth body");
        assert!(
            !wrong_body.contains(&token),
            "wrong-token body must not leak auth token"
        );

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .bearer_auth(&token)
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(5150),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        client
            .get(format!("{base_url}/v1/projects"))
            .bearer_auth(&token)
            .send()
            .await
            .expect("authorized projects request")
            .error_for_status()
            .expect("authorized projects status");

        let missing_tool = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/health",
                opened.session_id
            ))
            .json(&serde_json::json!({}))
            .send()
            .await
            .expect("missing tool auth request");
        assert_eq!(missing_tool.status(), StatusCode::UNAUTHORIZED);

        let tool_body = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/health",
                opened.session_id
            ))
            .bearer_auth(&token)
            .json(&serde_json::json!({}))
            .send()
            .await
            .expect("authorized tool request")
            .error_for_status()
            .expect("authorized tool status")
            .text()
            .await
            .expect("authorized tool body");
        assert!(
            tool_body.contains("Status:"),
            "health tool response should succeed: {tool_body}"
        );
        assert!(
            !tool_body.contains(&token),
            "tool response must not leak auth token"
        );

        let missing_sidecar = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/health",
                opened.session_id
            ))
            .send()
            .await
            .expect("missing sidecar auth request");
        assert_eq!(missing_sidecar.status(), StatusCode::UNAUTHORIZED);

        client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/health",
                opened.session_id
            ))
            .bearer_auth(&token)
            .send()
            .await
            .expect("authorized sidecar request")
            .error_for_status()
            .expect("authorized sidecar status");

        client
            .post(format!(
                "{base_url}/v1/sessions/{}/heartbeat",
                opened.session_id
            ))
            .bearer_auth(&token)
            .send()
            .await
            .expect("authorized heartbeat request")
            .error_for_status()
            .expect("authorized heartbeat status");

        client
            .delete(format!("{base_url}/v1/sessions/{}", opened.session_id))
            .bearer_auth(token)
            .send()
            .await
            .expect("authorized close request")
            .error_for_status()
            .expect("authorized close status");

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Feature 012 US1 — cross-project query, end-to-end on the DAEMON path.
    ///
    /// Drives the real production data path on loopback HTTP:
    ///   1. spawn a daemon, open a session bound to project A;
    ///   2. `index_folder(B, add:true)` -> B joins the session's working set
    ///      ADDITIVELY (A stays active);
    ///   3. a `search_symbols` with `projects:["*"]` returns ATTRIBUTED hits from
    ///      BOTH A and B (each project's distinctly-named symbol, under its own
    ///      `── project: <id> ──` header);
    ///   4. a `search_symbols` with NO project params returns ONLY the active
    ///      project A's symbol (the no-regression default target).
    ///
    /// This is the US1 acceptance gate at the daemon level. Honest coverage limit:
    /// it exercises the in-process front-end-absent daemon HTTP route directly
    /// (the production topology's data path); a full MCP-client dogfood against a
    /// built binary is a separate live-verify step.
    #[tokio::test]
    async fn test_cross_project_query_returns_attributed_hits_from_both_projects() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let project_a = project_dir("symforge-xproj-a");
        let project_b = project_dir("symforge-xproj-b");
        // Distinctly-named symbols so attribution is unambiguous. Both share the
        // substring "xproj_marker" so one query matches across both projects.
        std::fs::write(
            project_a.path().join("src").join("a.rs"),
            "pub fn xproj_marker_alpha() -> u32 { 1 }\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("b.rs"),
            "pub fn xproj_marker_beta() -> u32 { 2 }\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        // (1) Open a session bound to A.
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "xproj".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let project_a_id = opened.project_id.clone();
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        // Index A through the session so its index is warm (open does a load; a
        // reload via the active path guarantees the file is indexed).
        let index_a = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_a.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("index A request")
            .error_for_status()
            .expect("index A status")
            .text()
            .await
            .expect("index A body");
        assert!(index_a.contains("Indexed"), "index A: {index_a}");

        // (2) Additively open B.
        let index_b = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: Some(true),
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("index B request")
            .error_for_status()
            .expect("index B status")
            .text()
            .await
            .expect("index B body");
        assert!(
            index_b.contains("added to working set"),
            "additive index B: {index_b}"
        );

        // (3) Cross-project query with projects:["*"] -> hits from BOTH projects.
        let cross = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_symbols",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker",
                "projects": ["*"]
            }))
            .send()
            .await
            .expect("cross query request")
            .error_for_status()
            .expect("cross query status")
            .text()
            .await
            .expect("cross query body");
        assert!(
            cross.contains("xproj_marker_alpha"),
            "cross-project query must surface A's symbol: {cross}"
        );
        assert!(
            cross.contains("xproj_marker_beta"),
            "cross-project query must surface B's symbol: {cross}"
        );
        // Both projects attributed with their own section headers (ProjectHit ids).
        assert!(
            cross.contains(&format!("project: {project_a_id}")),
            "A must be attributed by project id: {cross}"
        );
        assert!(
            cross.contains(&format!("project: {project_b_id}")),
            "B must be attributed by project id: {cross}"
        );

        // (4) No-params query -> ONLY the active project A (no-regression default).
        let active_only = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_symbols",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker"
            }))
            .send()
            .await
            .expect("active query request")
            .error_for_status()
            .expect("active query status")
            .text()
            .await
            .expect("active query body");
        assert!(
            active_only.contains("xproj_marker_alpha"),
            "active-only query must surface A's symbol: {active_only}"
        );
        assert!(
            !active_only.contains("xproj_marker_beta"),
            "active-only query must NOT surface B's symbol (single active project): {active_only}"
        );
        // Single active project renders flat — no cross-project section header.
        assert!(
            !active_only.contains("project: "),
            "single-active query must render flat (no project header): {active_only}"
        );

        // (4b) Explicitly targeting the active project is still the same
        // single-project route. The daemon resolves the target before dispatch,
        // then strips the hint so the local worker does not refuse it as a
        // cross-project request without a daemon.
        let explicit_active = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_symbols",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker",
                "project": project_a_id
            }))
            .send()
            .await
            .expect("explicit active query request")
            .error_for_status()
            .expect("explicit active query status")
            .text()
            .await
            .expect("explicit active query body");
        assert!(
            explicit_active.contains("xproj_marker_alpha"),
            "explicit active project query must surface A's symbol: {explicit_active}"
        );
        assert!(
            !explicit_active.contains("xproj_marker_beta"),
            "explicit active project query must NOT surface B's symbol: {explicit_active}"
        );
        assert!(
            !explicit_active.contains("cross-project queries"),
            "explicit active project must not hit the local cross-project refusal: {explicit_active}"
        );
        assert!(
            !explicit_active.contains("project: "),
            "explicit active project must render as the flat single-project route: {explicit_active}"
        );

        // (5) B1 — cross-project scoping is now HONORED over the wire, not
        // refused (D11). These params previously returned a 400 "scoping is not
        // supported with cross-project targeting"; now they filter the results.
        //
        // 5a — a path_prefix matching NEITHER project's files scopes BOTH out
        //      (honored as a real filter, not silently ignored, not refused).
        let scoped_out = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_symbols",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker",
                "projects": ["*"],
                "path_prefix": "no_such_dir"
            }))
            .send()
            .await
            .expect("scoped query request")
            .error_for_status()
            .expect("B1: path_prefix must NOT be refused (HTTP 200, not 400)")
            .text()
            .await
            .expect("scoped query body");
        assert!(
            !scoped_out.contains("xproj_marker_alpha") && !scoped_out.contains("xproj_marker_beta"),
            "B1: a non-matching path_prefix must scope BOTH projects out \
             (honored, not ignored): {scoped_out}"
        );

        // 5b — language=Python excludes both Rust symbols (honored language filter).
        let lang_python = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_symbols",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker",
                "projects": ["*"],
                "language": "Python"
            }))
            .send()
            .await
            .expect("python query request")
            .error_for_status()
            .expect("B1: language must NOT be refused (HTTP 200, not 400)")
            .text()
            .await
            .expect("python query body");
        assert!(
            !lang_python.contains("xproj_marker_alpha")
                && !lang_python.contains("xproj_marker_beta"),
            "B1: language=Python must scope out the Rust symbols cross-project: {lang_python}"
        );

        // 5c — language=Rust keeps BOTH (the filter scopes; it does not break the
        // query) — proves the scope-outs above are real filtering, not breakage.
        let lang_rust = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_symbols",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker",
                "projects": ["*"],
                "language": "Rust"
            }))
            .send()
            .await
            .expect("rust query request")
            .error_for_status()
            .expect("rust query status")
            .text()
            .await
            .expect("rust query body");
        assert!(
            lang_rust.contains("xproj_marker_alpha") && lang_rust.contains("xproj_marker_beta"),
            "B1: language=Rust keeps both Rust symbols cross-project: {lang_rust}"
        );

        // (6) B1 — cross-project search_text scoping is ALSO honored over the wire
        // (closes the symbols-only coverage gap from the adversarial review). The
        // source text "xproj_marker_*" lives in both projects' .rs files.
        // 6-control: an unscoped cross-project text search finds BOTH.
        let text_all = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_text",
                opened.session_id
            ))
            .json(&serde_json::json!({ "query": "xproj_marker", "projects": ["*"] }))
            .send()
            .await
            .expect("text all request")
            .error_for_status()
            .expect("text all status")
            .text()
            .await
            .expect("text all body");
        assert!(
            text_all.contains("xproj_marker_alpha") && text_all.contains("xproj_marker_beta"),
            "B1 control: unscoped cross-project text search finds both projects: {text_all}"
        );
        // 6-scoped: a non-matching path_prefix scopes BOTH out — honored as a
        // filter (HTTP 200), not refused (this was HTTP 400 before B1).
        let text_scoped = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_text",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "xproj_marker",
                "projects": ["*"],
                "path_prefix": "no_such_dir"
            }))
            .send()
            .await
            .expect("text scoped request")
            .error_for_status()
            .expect("B1: search_text path_prefix must NOT be refused (200, not 400)")
            .text()
            .await
            .expect("text scoped body");
        assert!(
            !text_scoped.contains("xproj_marker_alpha")
                && !text_scoped.contains("xproj_marker_beta"),
            "B1: non-matching path_prefix must scope BOTH projects' text out (honored): {text_scoped}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_cross_project_knowledge_captures_selected_session_projects_only() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let project_a = project_dir("symforge-knowledge-a");
        let project_b = project_dir("symforge-knowledge-b");
        let project_c = project_dir("symforge-knowledge-c");
        for (project, source_name, source, document) in [
            (
                &project_a,
                "a.rs",
                "pub fn alpha_anchor() {}\n",
                "# Alpha knowledge\nQuartz boundary alpha. See [alpha](../src/a.rs).\n",
            ),
            (
                &project_b,
                "b.rs",
                "pub fn beta_anchor() {}\n",
                "# Beta knowledge\nQuartz boundary beta. See [beta](../src/b.rs).\n",
            ),
            (
                &project_c,
                "c.rs",
                "pub fn gamma_anchor() {}\n",
                "# Gamma knowledge\nQuartz boundary gamma. See [gamma](../src/c.rs).\n",
            ),
        ] {
            std::fs::create_dir_all(project.path().join("docs")).expect("docs dir");
            std::fs::write(project.path().join("src").join(source_name), source)
                .expect("source fixture");
            std::fs::write(project.path().join("docs").join("knowledge.md"), document)
                .expect("knowledge fixture");
        }

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "knowledge-xproj".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open A")
            .error_for_status()
            .expect("open A status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open A body");
        let project_a_id = opened.project_id.clone();
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical B"));
        let project_a_alias = project_a
            .path()
            .file_name()
            .and_then(|name| name.to_str())
            .expect("A project-name alias")
            .to_string();
        let project_b_alias = project_b
            .path()
            .file_name()
            .and_then(|name| name.to_str())
            .expect("B project-name alias")
            .to_string();

        for (path, add) in [(project_a.path(), None), (project_b.path(), Some(true))] {
            let response = http
                .post(format!(
                    "{base_url}/v1/sessions/{}/tools/index_folder",
                    opened.session_id
                ))
                .json(&IndexFolderInput {
                    path: path.display().to_string(),
                    idempotency_key: None,
                    add,
                    allow_protected_root: None,
                })
                .send()
                .await
                .expect("index request")
                .error_for_status()
                .expect("index status")
                .text()
                .await
                .expect("index body");
            assert!(
                response.contains("Indexed") || response.contains("added to working set"),
                "index response: {response}"
            );
        }

        // Open C globally, but in another session. The first session's wildcard
        // must remain scoped to its own A+B working set.
        let _other_session = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_c.path().display().to_string(),
                client_name: "knowledge-other-session".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open C")
            .error_for_status()
            .expect("open C status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open C body");

        let wildcard = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "quartz boundary",
                "projects": ["*"]
            }))
            .send()
            .await
            .expect("wildcard request")
            .error_for_status()
            .expect("wildcard status")
            .text()
            .await
            .expect("wildcard body");
        assert!(
            wildcard.contains("Quartz boundary alpha"),
            "A hit: {wildcard}"
        );
        assert!(
            wildcard.contains("Quartz boundary beta"),
            "B hit: {wildcard}"
        );
        assert!(
            !wildcard.contains("Quartz boundary gamma"),
            "session wildcard leaked C: {wildcard}"
        );

        let explicit_b = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "quartz boundary",
                "project": project_b_id
            }))
            .send()
            .await
            .expect("B request")
            .error_for_status()
            .expect("B status")
            .text()
            .await
            .expect("B body");
        assert!(
            explicit_b.contains("Quartz boundary beta"),
            "B hit: {explicit_b}"
        );
        assert!(
            !explicit_b.contains("Quartz boundary alpha") && !explicit_b.contains("src/a.rs"),
            "explicit B leaked A hit/bridge: {explicit_b}"
        );

        let alias_b = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "quartz boundary",
                "project": project_b_alias.clone()
            }))
            .send()
            .await
            .expect("B alias request")
            .error_for_status()
            .expect("B alias status")
            .text()
            .await
            .expect("B alias body");
        assert!(
            alias_b.contains("Quartz boundary beta"),
            "unique project-name aliases must resolve: {alias_b}"
        );
        assert!(
            !alias_b.contains("Quartz boundary alpha") && !alias_b.contains("src/a.rs"),
            "project-name alias leaked A hit/bridge: {alias_b}"
        );

        let reversed_subset = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "quartz boundary",
                "projects": [project_b_alias.clone(), project_a_alias.clone()]
            }))
            .send()
            .await
            .expect("subset request")
            .error_for_status()
            .expect("subset status")
            .text()
            .await
            .expect("subset body");
        let mut sorted_ids = [project_a_id.clone(), project_b_id.clone()];
        sorted_ids.sort();
        let first = reversed_subset
            .find(&format!("project: {}", sorted_ids[0]))
            .expect("first deterministic project header");
        let second = reversed_subset
            .find(&format!("project: {}", sorted_ids[1]))
            .expect("second deterministic project header");
        assert!(
            first < second,
            "project envelopes must be canonical: {reversed_subset}"
        );

        let review_subset = |selectors: Vec<String>| {
            let http = http.clone();
            let url = format!(
                "{base_url}/v1/sessions/{}/tools/review_knowledge",
                opened.session_id
            );
            async move {
                http.post(url)
                    .json(&serde_json::json!({
                        "mode": "remediation",
                        "projects": selectors,
                        "limit": 1
                    }))
                    .send()
                    .await
                    .expect("review subset request")
                    .error_for_status()
                    .expect("review subset status")
                    .text()
                    .await
                    .expect("review subset body")
            }
        };
        let reversed_review =
            review_subset(vec![project_b_alias.clone(), project_a_alias.clone()]).await;
        let forward_review =
            review_subset(vec![project_a_alias.clone(), project_b_alias.clone()]).await;
        assert_eq!(
            reversed_review, forward_review,
            "selector order must not affect the captured per-source plans or hashes"
        );
        assert_eq!(
            reversed_review.matches("top_result_hash=").count(),
            1,
            "one top-level result hash: {reversed_review}"
        );
        assert_eq!(
            reversed_review.matches("review_hash=").count(),
            2,
            "one isolated plan hash per selected source: {reversed_review}"
        );
        let review_first = reversed_review
            .find(&format!("project: {}", sorted_ids[0]))
            .expect("first review project header");
        let review_second = reversed_review
            .find(&format!("project: {}", sorted_ids[1]))
            .expect("second review project header");
        assert!(
            review_first < review_second,
            "review project envelopes must be canonical: {reversed_review}"
        );

        let conflict = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "quartz boundary",
                "project": project_a_id,
                "projects": ["*"]
            }))
            .send()
            .await
            .expect("conflict request")
            .error_for_status()
            .expect("conflict status")
            .text()
            .await
            .expect("conflict body");
        assert!(
            conflict.contains("mutually exclusive"),
            "selector conflict: {conflict}"
        );

        let unknown = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "quartz boundary",
                "project": "project-not-open"
            }))
            .send()
            .await
            .expect("unknown request")
            .error_for_status()
            .expect("unknown status")
            .text()
            .await
            .expect("unknown body");
        assert!(unknown.contains("not open"), "unknown selector: {unknown}");

        let review_conflict = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/review_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "mode": "summary",
                "project": project_a_id,
                "projects": ["*"]
            }))
            .send()
            .await
            .expect("review conflict request")
            .error_for_status()
            .expect("review conflict status")
            .text()
            .await
            .expect("review conflict body");
        assert!(
            review_conflict.contains("mutually exclusive"),
            "review selector conflict: {review_conflict}"
        );

        let review_unknown = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/review_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "mode": "summary",
                "project": "project-not-open"
            }))
            .send()
            .await
            .expect("review unknown request")
            .error_for_status()
            .expect("review unknown status")
            .text()
            .await
            .expect("review unknown body");
        assert!(
            review_unknown.contains("not open"),
            "unknown review selector: {review_unknown}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// B2/D12 regression: a cross-project read REFLECTS a project's watcher-
    /// observed change (no git commit). Two projects in one session; mutate a
    /// watched file in B (add a new symbol + delete an existing one); republish B
    /// deterministically (`SharedIndexHandle::reload`, the same swap_and_publish
    /// the watcher drives, with no debounce race); re-run the SAME cross-read.
    ///
    /// Asserts:
    ///   SC-1 (add)    — the NEW symbol `xproj_marker_gamma` now appears under B.
    ///   SC-2 (delete) — the deleted `xproj_marker_beta` is GONE (no stale ghost).
    ///   control       — B's interned base_generation ADVANCED across the refresh
    ///                   (proves the force-replace fired; the FROZEN base would
    ///                   still have surfaced beta and not gamma).
    ///   SC-002        — after the force-replace there is still exactly ONE
    ///                   `Arc<IndexBase>` per BaseKey: the session entry's base
    ///                   Arc IS the bases-table value for B's key (Arc::ptr_eq),
    ///                   and the bases-table key count is unchanged.
    #[tokio::test]
    async fn test_cross_project_read_is_fresh_after_watcher_reindex() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let project_a = project_dir("symforge-fresh-a");
        let project_b = project_dir("symforge-fresh-b");
        let b_source = project_b.path().join("src").join("b.rs");
        std::fs::write(
            project_a.path().join("src").join("a.rs"),
            "pub fn xproj_marker_alpha() -> u32 { 1 }\n",
        )
        .expect("write source a");
        std::fs::write(&b_source, "pub fn xproj_marker_beta() -> u32 { 2 }\n")
            .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        // Open A, index A, additively open B.
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "fresh".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let session_id = opened.session_id.clone();
        let canonical_b = canonical_project_root(project_b.path()).expect("canonical b");
        let project_b_id = project_key(&canonical_b);

        http.post(format!(
            "{base_url}/v1/sessions/{session_id}/tools/index_folder"
        ))
        .json(&IndexFolderInput {
            path: project_a.path().display().to_string(),
            idempotency_key: None,
            add: None,
            allow_protected_root: None,
        })
        .send()
        .await
        .expect("index A request")
        .error_for_status()
        .expect("index A status");

        http.post(format!(
            "{base_url}/v1/sessions/{session_id}/tools/index_folder"
        ))
        .json(&IndexFolderInput {
            path: project_b.path().display().to_string(),
            idempotency_key: None,
            add: Some(true),
            allow_protected_root: None,
        })
        .send()
        .await
        .expect("index B request")
        .error_for_status()
        .expect("index B status");

        // Baseline cross-read: B's ORIGINAL symbol present, the new one absent.
        let baseline = http
            .post(format!(
                "{base_url}/v1/sessions/{session_id}/tools/search_symbols"
            ))
            .json(&serde_json::json!({ "query": "xproj_marker", "projects": ["*"] }))
            .send()
            .await
            .expect("baseline request")
            .error_for_status()
            .expect("baseline status")
            .text()
            .await
            .expect("baseline body");
        assert!(
            baseline.contains("xproj_marker_beta"),
            "baseline cross-read must surface B's original symbol: {baseline}"
        );
        assert!(
            !baseline.contains("xproj_marker_gamma"),
            "baseline must NOT yet contain the not-written symbol: {baseline}"
        );

        // B's interned base_generation BEFORE the watcher change (control anchor).
        let b_key = BaseKey::new(canonical_b.clone(), CommitId::Dirtyless);
        let gen_before =
            state_base_generation(&handle.state, &b_key).expect("B base interned at open");
        let key_count_before = handle.state.bases.read().len();

        // A's interned base_generation BEFORE B's refresh — A is the UNTOUCHED
        // project; the mismatch-gate must NOT re-intern it. A is a non-git TempDir
        // like B, so its key is (canonical_root, Dirtyless) — same shape as B's.
        let canonical_a = canonical_project_root(project_a.path()).expect("canonical a");
        let a_key = BaseKey::new(canonical_a, CommitId::Dirtyless);
        let a_gen_before =
            state_base_generation(&handle.state, &a_key).expect("A base interned at open");

        // Mutate a WATCHED file in B: delete beta, add gamma. Then republish B
        // DETERMINISTICALLY via the project's SharedIndex reload (same publish the
        // watcher drives) so the test does not race the real watcher debounce.
        std::fs::write(&b_source, "pub fn xproj_marker_gamma() -> u32 { 3 }\n")
            .expect("rewrite source b");
        {
            let index = {
                let projects = handle.state.projects.read();
                let slot = projects
                    .get(&project_b_id)
                    .expect("project B loaded in daemon");
                slot.metadata.read().index.shared()
            };
            index
                .reload(&canonical_b)
                .expect("deterministic B reload (watcher-equivalent publish)");
        }

        // The SAME cross-read now reflects B's current state.
        let fresh = http
            .post(format!(
                "{base_url}/v1/sessions/{session_id}/tools/search_symbols"
            ))
            .json(&serde_json::json!({ "query": "xproj_marker", "projects": ["*"] }))
            .send()
            .await
            .expect("fresh request")
            .error_for_status()
            .expect("fresh status")
            .text()
            .await
            .expect("fresh body");
        // SC-1 (add): the new symbol appears.
        assert!(
            fresh.contains("xproj_marker_gamma"),
            "SC-1: cross-read after watcher reindex must surface B's NEW symbol: {fresh}"
        );
        // SC-2 (delete): the deleted symbol is gone (no stale ghost).
        assert!(
            !fresh.contains("xproj_marker_beta"),
            "SC-2: cross-read must NOT surface B's DELETED symbol (stale ghost): {fresh}"
        );
        // A is untouched and still present (the refresh did not drop other projects).
        assert!(
            fresh.contains("xproj_marker_alpha"),
            "A must remain present after B's refresh: {fresh}"
        );

        // Control: B's interned base_generation advanced (force-replace fired).
        let gen_after = state_base_generation(&handle.state, &b_key)
            .expect("B base still interned after refresh");
        assert!(
            gen_after > gen_before,
            "control: force-replace must advance B's base_generation \
             (before={gen_before}, after={gen_after}); a frozen base would not"
        );

        // Mismatch-gate control: A was UNTOUCHED, so its base must NOT have been
        // re-interned by the refresh (no spurious force-replace of fresh entries).
        let a_gen_after = state_base_generation(&handle.state, &a_key)
            .expect("A base still interned after refresh");
        assert_eq!(
            a_gen_after, a_gen_before,
            "mismatch-gate: untouched project A must NOT be re-interned \
             (before={a_gen_before}, after={a_gen_after})"
        );

        // SC-002: exactly ONE Arc<IndexBase> per BaseKey after the force-replace —
        // the session entry's base IS the bases-table value, and no key was added.
        {
            let bases = handle.state.bases.read();
            let table_base = bases.get(&b_key).expect("B base in table after refresh");
            let sessions = handle.state.sessions.read();
            let session = sessions.get(&session_id).expect("session present");
            let ws = session.working_set.read();
            let entry = ws.get(&project_b_id).expect("B entry in working set");
            assert!(
                Arc::ptr_eq(table_base, &entry.base),
                "SC-002: the working-set entry must share the SAME interned base Arc"
            );
            assert_eq!(
                bases.len(),
                key_count_before,
                "SC-002: force-replace must REPLACE the value, not add a duplicate key"
            );
        }

        // Lone NON-ACTIVE target (Targets::One(non_active)): the session is active
        // on A, so targeting ONLY B exercises the single-non-active cross-project
        // path the design promised to refresh (not just Targets::All). Mutate B
        // again, republish deterministically, then read with projects:[B] only.
        std::fs::write(&b_source, "pub fn xproj_marker_delta() -> u32 { 4 }\n")
            .expect("rewrite source b (delta)");
        {
            let index = {
                let projects = handle.state.projects.read();
                let slot = projects
                    .get(&project_b_id)
                    .expect("project B loaded in daemon");
                slot.metadata.read().index.shared()
            };
            index
                .reload(&canonical_b)
                .expect("deterministic B reload (delta)");
        }
        let lone_b = http
            .post(format!(
                "{base_url}/v1/sessions/{session_id}/tools/search_symbols"
            ))
            .json(&serde_json::json!({ "query": "xproj_marker", "projects": [project_b_id] }))
            .send()
            .await
            .expect("lone-B request")
            .error_for_status()
            .expect("lone-B status")
            .text()
            .await
            .expect("lone-B body");
        assert!(
            lone_b.contains("xproj_marker_delta"),
            "lone non-active target: refresh must fire for Targets::One(B) too: {lone_b}"
        );
        assert!(
            !lone_b.contains("xproj_marker_gamma"),
            "lone non-active target: B's superseded symbol must be gone: {lone_b}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Read the interned `base_generation` for `key`, if present. Test helper for
    /// the B2/D12 freshness control assertion.
    fn state_base_generation(state: &SharedDaemonState, key: &BaseKey) -> Option<u64> {
        state.bases.read().get(key).map(|b| b.base_generation)
    }

    // ── Feature 012 hardening — cross-project output is BOUNDED ──────────────────
    //
    // Without a cap the cross-project formatter would render every hit from every
    // targeted project (unbounded, unlike the single-project path). Prove the
    // total-hit cap truncates the rendered hits AND discloses the truncation.
    #[test]
    fn test_cross_project_symbols_output_is_capped_and_discloses_truncation() {
        use crate::live_index::search::SymbolMatchTier;
        use crate::live_index::view::{ProjectHit, ViewSymbolHit};

        // 5 synthetic hits across two projects.
        let hits: Vec<ProjectHit<ViewSymbolHit>> = (0..5)
            .map(|i| ProjectHit {
                project_id: if i < 3 { "proj-a" } else { "proj-b" }.to_string(),
                hit: ViewSymbolHit {
                    name: format!("sym_{i}"),
                    path: format!("src/f{i}.rs"),
                    kind: "fn".to_string(),
                    line: i + 1,
                    tier: SymbolMatchTier::Exact,
                },
            })
            .collect();

        // Cap below the hit count -> truncated + disclosed.
        let capped = format_cross_project_symbols(&hits, "sym", true, 2);
        assert!(
            capped.starts_with("2 of 5 matches across projects (truncated;"),
            "header must disclose shown-of-total truncation: {capped}"
        );
        assert!(
            capped.contains("query a single project for the full set"),
            "truncation must carry the corrective hint: {capped}"
        );
        // Exactly the first 2 hit lines are rendered (sym_0, sym_1); sym_2.. dropped.
        assert!(capped.contains("sym_0") && capped.contains("sym_1"));
        assert!(
            !capped.contains("sym_2") && !capped.contains("sym_4"),
            "hits beyond the cap must NOT be rendered: {capped}"
        );

        // Cap above the hit count -> no truncation language, all hits rendered.
        let full = format_cross_project_symbols(&hits, "sym", true, 100);
        assert!(
            full.starts_with("5 matches across projects\n"),
            "uncapped header must not claim truncation: {full}"
        );
        assert!(
            full.contains("sym_4"),
            "all hits rendered when under cap: {full}"
        );
        assert!(
            !full.contains("truncated"),
            "no truncation notice when under cap: {full}"
        );
    }

    #[test]
    fn cross_project_search_text_zero_hit_reports_exact_excluded_knowledge_count() {
        use crate::live_index::search::TextSearchResult;
        use crate::live_index::view::ProjectHit;

        fn zero_hit(excluded: usize) -> TextSearchResult {
            TextSearchResult {
                label: "'knowledge-needle-xyz'".to_string(),
                total_matches: 0,
                files: vec![],
                suppressed_by_noise: 0,
                overflow_count: 0,
                excluded_knowledge_files: excluded,
                withheld_policy_files: 0,
                withheld_size_files: 0,
            }
        }

        // Two targeted projects, each already path-scoped: 1 + 2 = 3. A
        // formatter that prints only the first project's count cannot match 3.
        let results = vec![
            ProjectHit {
                project_id: "alpha".to_string(),
                hit: zero_hit(1),
            },
            ProjectHit {
                project_id: "beta".to_string(),
                hit: zero_hit(2),
            },
        ];
        let rendered = format_cross_project_text(&results, true, 50);
        assert!(
            rendered.starts_with("No text matches in the targeted project(s)."),
            "zero-hit header must stay; got: {rendered}"
        );
        assert!(
            rendered.contains("3 in-scope knowledge-only files"),
            "must sum in-scope excluded knowledge across projects; got: {rendered}"
        );
        assert!(
            rendered.contains("search_knowledge"),
            "zero-hit must point at search_knowledge; got: {rendered}"
        );
        assert!(
            !rendered.contains("1 in-scope knowledge-only file\n")
                && !rendered.contains("2 in-scope knowledge-only files"),
            "must not print a per-project count instead of the sum; got: {rendered}"
        );
    }

    // The cross-project total-hit cap derived from the caller's `limit`:
    // None -> default cap; a value clamps into [1, MAX]; zero/absurd cannot
    // disable the bound.
    #[test]
    fn test_cross_project_result_cap_clamps_limit() {
        assert_eq!(
            cross_project_result_cap(None),
            CROSS_PROJECT_DEFAULT_RESULT_CAP,
            "no limit -> default cap"
        );
        assert_eq!(
            cross_project_result_cap(Some(10)),
            10,
            "small limit honored"
        );
        assert_eq!(
            cross_project_result_cap(Some(0)),
            1,
            "zero clamps up to 1 (cap never disabled)"
        );
        assert_eq!(
            cross_project_result_cap(Some(u32::MAX)),
            CROSS_PROJECT_MAX_RESULT_CAP,
            "absurd limit clamps to the hard ceiling"
        );
    }

    // The `max_tokens` budget truncates an assembled body at a line boundary and
    // discloses the cut.
    #[test]
    fn test_cross_project_token_budget_truncates_and_discloses() {
        let body = (0..50)
            .map(|i| format!("line {i} with some content\n"))
            .collect::<String>();
        // ~26 bytes/line * 50 = ~1300 bytes; max_tokens=10 -> 40-byte budget.
        let out = apply_cross_project_token_budget(body.clone(), Some(10));
        assert!(out.len() < body.len(), "budget must shrink the body");
        assert!(
            out.contains("truncated to fit max_tokens=10"),
            "truncation must be disclosed: {out}"
        );
        assert!(
            out.ends_with('\n'),
            "truncated body ends on a line boundary"
        );

        // No budget / zero budget -> identity.
        assert_eq!(apply_cross_project_token_budget(body.clone(), None), body);
        assert_eq!(
            apply_cross_project_token_budget(body.clone(), Some(0)),
            body
        );
    }

    // ── B1 — cross-project HONORS path_prefix/language, still REFUSES the params
    // with no cross-project path ─────────────────────────────────────────────
    //
    // `path_prefix`/`language`/noise/`limit` are now threaded through the
    // engine's option-honoring search (D11 + D14), so they are NO LONGER refused.
    // `structural` (search_text) and `path`/`symbol_kind`/`direction`
    // (find_references) have no cross-project entry point and are still refused
    // (honest, not silently dropped).
    #[test]
    fn test_reject_unsupported_cross_project_scoping_per_tool() {
        use serde_json::json;

        // search_symbols: path_prefix + language are now HONORED (not refused);
        // kind always allowed.
        assert!(
            reject_unsupported_cross_project_scoping(
                "search_symbols",
                &json!({ "query": "x", "path_prefix": "src/" }),
            )
            .is_ok(),
            "path_prefix is now honored cross-project and must NOT be refused"
        );
        assert!(
            reject_unsupported_cross_project_scoping(
                "search_symbols",
                &json!({ "query": "x", "language": "Rust" }),
            )
            .is_ok(),
            "language is now honored cross-project and must NOT be refused"
        );
        assert!(
            reject_unsupported_cross_project_scoping(
                "search_symbols",
                &json!({ "query": "x", "kind": "fn" }),
            )
            .is_ok(),
            "kind IS honored cross-project and must NOT be refused"
        );

        // search_text: path_prefix/language honored; structural still refused.
        assert!(
            reject_unsupported_cross_project_scoping(
                "search_text",
                &json!({ "query": "x", "path_prefix": "src/", "language": "Rust" }),
            )
            .is_ok(),
            "search_text path_prefix/language are now honored cross-project"
        );
        let structural_err = reject_unsupported_cross_project_scoping(
            "search_text",
            &json!({ "query": "x", "structural": true }),
        )
        .expect_err("structural must be refused");
        assert!(
            structural_err
                .to_string()
                .contains("structural scoping is not supported")
                && structural_err
                    .to_string()
                    .contains("query a single project for scoped results"),
            "structural refusal must name the param + corrective hint: {structural_err}"
        );

        // find_references: path / symbol_kind / direction still refused (no
        // cross-project meaning).
        for (field, value) in [
            ("path", json!("src/db.rs")),
            ("symbol_kind", json!("fn")),
            ("direction", json!("trait")),
        ] {
            let err = reject_unsupported_cross_project_scoping(
                "find_references",
                &json!({ "name": "x", field: value }),
            )
            .unwrap_err()
            .to_string();
            assert!(
                err.contains(&format!("{field} scoping is not supported")),
                "{field} must be refused on find_references: {err}"
            );
        }

        // A blank still-refused value is treated as not-set (no false refusal).
        assert!(
            reject_unsupported_cross_project_scoping(
                "find_references",
                &json!({ "name": "x", "path": "  " }),
            )
            .is_ok(),
            "blank path value must not trip the refusal"
        );
    }

    // End-to-end: the scoping refusal fires from `execute_cross_project_read`
    // BEFORE any query runs (the working set need not even contain the target —
    // but here it does, so we prove the refusal precedes a would-be-successful
    // query). A synthetic single-entry working set over an empty base.
    #[test]
    fn test_execute_cross_project_read_rejects_scoping_before_query() {
        use crate::live_index::store::LiveIndex;
        use crate::live_index::view::{BaseKey, CommitId, IndexBase, WorkingSet};
        use serde_json::json;

        let base = Arc::new(IndexBase::new(
            BaseKey::new("/synthetic/root", CommitId::Dirtyless),
            Arc::new(LiveIndex::empty_live_index()),
            1,
        ));
        let mut ws = WorkingSet::new();
        ws.add("proj-x", base);

        // A still-unsupported param (find_references `direction`) is refused up
        // front, before any query runs. (`path_prefix`/`language` are now honored,
        // so they no longer exercise this guard — `direction` still has no
        // cross-project path.)
        let err = execute_cross_project_read(
            "find_references",
            json!({ "name": "anything", "direction": "trait" }),
            Targets::Subset(vec!["proj-x".to_string()]),
            &ws,
        )
        .expect_err("scoping param must be refused");
        assert!(
            err.to_string()
                .contains("direction scoping is not supported with cross-project targeting"),
            "cross-project read must refuse the unsupported scoping param: {err}"
        );
    }

    #[tokio::test]
    async fn test_daemon_is_fail_closed_without_env_token() {
        // Item-2 acceptance: with NO env pin, the daemon must STILL establish a
        // token, persist it to the token file, reject unauthenticated requests,
        // and accept requests bearing the file-resolved token.
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let _bind_guard = EnvVarGuard::unset(DAEMON_BIND_ENV);
        let _allow_guard = EnvVarGuard::unset(DAEMON_ALLOW_NON_LOOPBACK_ENV);
        // Critical: no env token. Previously this meant "auth disabled".
        let _auth_guard = EnvVarGuard::unset(DAEMON_AUTH_TOKEN_ENV);
        let project = project_dir("symforge-daemon-failclosed");
        let control_state_dir = test_control_state(daemon_home.path());

        let handle = spawn_daemon_at("127.0.0.1", &control_state_dir)
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        // 1. A token file is always present after start.
        let token_path = test_daemon_path(daemon_home.path(), daemon_token_file_name());
        assert!(
            token_path.exists(),
            "daemon must persist an auth token file even without an env pin"
        );
        let file_token = std::fs::read_to_string(&token_path)
            .expect("read token file")
            .trim()
            .to_string();
        assert!(!file_token.is_empty(), "persisted token must be non-empty");
        assert_eq!(
            file_token, handle.state.auth_token,
            "the persisted token must match the token the daemon enforces"
        );

        // The token must not leak via the unauthenticated health endpoint.
        let bare = reqwest::Client::new();
        let health_body = bare
            .get(format!("{base_url}/health"))
            .send()
            .await
            .expect("health request")
            .error_for_status()
            .expect("health status")
            .text()
            .await
            .expect("health body");
        assert!(
            !health_body.contains(&file_token),
            "health body must not leak the auth token"
        );
        let health: DaemonHealth = serde_json::from_str(&health_body).expect("health json");
        assert!(health.auth_required, "auth must always be required");

        // 2. An unauthenticated session-open is rejected.
        let unauth = bare
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(7000),
            })
            .send()
            .await
            .expect("unauth open request");
        assert_eq!(
            unauth.status(),
            StatusCode::UNAUTHORIZED,
            "a request without the token must be rejected"
        );

        // 3. The file-resolved token authenticates successfully.
        let opened = bare
            .post(format!("{base_url}/v1/sessions/open"))
            .bearer_auth(&file_token)
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(7000),
            })
            .send()
            .await
            .expect("authed open request")
            .error_for_status()
            .expect("authed open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("authed open body");
        assert!(!opened.session_id.is_empty());

        // 4. `resolve_daemon_auth_token` (the client/hook resolution path) reads
        //    the same token from the file when no env pin is set.
        assert_eq!(
            resolve_daemon_auth_token_at(&control_state_dir).as_deref(),
            Some(file_token.as_str()),
            "client token resolution must read the persisted token file"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_daemon_executes_session_scoped_tool_calls() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-tool");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(9001),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let response = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/get_repo_map",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "detail": "full"
            }))
            .send()
            .await
            .expect("tool request");

        assert!(
            response.status().is_success(),
            "tool endpoint should succeed, got {}",
            response.status()
        );

        let body = response.text().await.expect("tool body");
        assert!(
            body.contains("main.rs"),
            "repo outline should include the indexed file, got: {body}"
        );

        let search_files = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_files",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "main.rs",
                "limit": 5
            }))
            .send()
            .await
            .expect("search_files request");

        assert!(
            search_files.status().is_success(),
            "search_files endpoint should succeed, got {}",
            search_files.status()
        );

        let search_files_body = search_files.text().await.expect("search_files body");
        assert!(
            search_files_body.contains("src/main.rs"),
            "search_files should return the indexed file, got: {search_files_body}"
        );

        let resolved_path = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_files",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "main.rs",
                "resolve": true
            }))
            .send()
            .await
            .expect("search_files resolve request");

        assert!(
            resolved_path.status().is_success(),
            "search_files resolve mode should succeed, got {}",
            resolved_path.status()
        );

        let resolved_path_body = resolved_path
            .text()
            .await
            .expect("search_files resolve body");
        assert!(
            resolved_path_body.contains("src/main.rs"),
            "search_files resolve mode should return the indexed file, got: {resolved_path_body}"
        );

        let curation_preview = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/curate_knowledge",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "project": opened.project_id.clone(),
                "actions": [{
                    "action_id": "action-daemon-route-oracle",
                    "mutation": {
                        "operation": "upsert",
                        "entry": {
                            "entry_id": "entry-daemon-route-oracle",
                            "target": {
                                "path": "src/main.rs",
                                "content_hash": "0".repeat(64)
                            },
                            "lifecycle": "unknown",
                            "evidence": [],
                            "justification_code": "daemon-route-oracle"
                        }
                    }
                }],
                "if_source_review_hash": "0".repeat(64),
                "if_manifest_digest": "0".repeat(64),
                "if_policy_digest": "0".repeat(64)
            }))
            .send()
            .await
            .expect("curate_knowledge preview request")
            .error_for_status()
            .expect("curate_knowledge preview status")
            .text()
            .await
            .expect("curate_knowledge preview body");
        assert!(
            curation_preview.contains("stale_review_hash"),
            "daemon must dispatch curate_knowledge to the project runtime: {curation_preview}"
        );

        let reused = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex-reused".to_string(),
                pid: Some(9002),
            })
            .send()
            .await
            .expect("reused open request")
            .error_for_status()
            .expect("reused open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("reused open body");
        assert_eq!(reused.project_id, opened.project_id);
        assert_ne!(reused.session_id, opened.session_id);

        let health = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/health_compact",
                reused.session_id
            ))
            .json(&serde_json::json!({}))
            .send()
            .await
            .expect("health request")
            .error_for_status()
            .expect("health status")
            .text()
            .await
            .expect("health body");
        assert!(
            health.contains("Runtime: mode=daemon_reused_session"),
            "daemon health should distinguish reused daemon sessions, got: {health}"
        );
        assert!(
            health.contains(&format!("project_root={}", reused.canonical_root)),
            "daemon health should surface canonical project root, got: {health}"
        );
        assert!(
            health.contains(&format!("project_id={}", reused.project_id)),
            "daemon health should surface daemon project id, got: {health}"
        );
        assert!(
            health.contains(&format!("session_id={}", reused.session_id)),
            "daemon health should surface daemon session id, got: {health}"
        );
        assert!(
            health.contains("index_id=index-"),
            "daemon health should surface index identity, got: {health}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// SF-007 regression: `checkpoint_now` must forward to the daemon in
    /// daemon-proxy mode and checkpoint the daemon's authoritative live index,
    /// instead of hard-failing with "unavailable in daemon-proxy mode" (the old
    /// proxy-side guard) or "unknown tool" (the missing daemon dispatch arm).
    #[tokio::test]
    async fn test_daemon_executes_checkpoint_now_tool_call() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-checkpoint");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(9101),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let response = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/checkpoint_now",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "verify_after_write": true
            }))
            .send()
            .await
            .expect("checkpoint_now request");

        assert!(
            response.status().is_success(),
            "checkpoint_now endpoint should succeed, got {}",
            response.status()
        );

        let body = response.text().await.expect("checkpoint_now body");
        assert!(
            body.contains("Checkpoint complete"),
            "checkpoint_now should report completion, got: {body}"
        );
        assert!(
            !body.contains("unavailable in daemon-proxy mode"),
            "checkpoint_now must not hard-fail in daemon-proxy mode, got: {body}"
        );
        assert!(
            !body.contains("unknown tool"),
            "daemon must dispatch checkpoint_now, got: {body}"
        );

        // The snapshot was written to the daemon's authoritative project root
        // (the canonical root the session is bound to) and must deserialize.
        let canonical_root = PathBuf::from(&opened.canonical_root);
        let RootResolution::Bound(binding) = crate::discovery::resolve_root_candidate(
            &canonical_root,
            RootCandidateSource::LaunchCwd,
            RootRequestMode::Automatic,
        ) else {
            panic!("opened daemon root must remain bound");
        };
        let state_placement = crate::discovery::resolve_state_placement(&binding);
        assert!(
            crate::live_index::persist::load_snapshot(&canonical_root, &state_placement).is_some(),
            "checkpoint should write a loadable snapshot under {}/.symforge/index.bin",
            canonical_root.display()
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_daemon_port_if_compatible_accepts_matching_identity() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let health = DaemonState::new().health();
        let (port, shutdown_tx) = spawn_fake_health_server(health).await;
        std::fs::write(
            test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE),
            port.to_string(),
        )
        .expect("write daemon port");

        let identity = current_daemon_identity();
        let selected =
            daemon_port_if_compatible_at(&test_control_state(daemon_home.path()), &identity)
                .await
                .expect("compatible health lookup");

        assert_eq!(selected, Some(port));

        let _ = shutdown_tx.send(());
    }

    #[tokio::test]
    async fn test_daemon_port_if_compatible_rejects_version_mismatch() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let health = DaemonHealth {
            project_count: 0,
            session_count: 0,
            stale_sessions: 0,
            daemon_version: "0.0.0".to_string(),
            executable_path: current_daemon_identity().executable_path,
            auth_required: false,
            pid: None,
            started_at_unix_secs: None,
        };
        let (port, shutdown_tx) = spawn_fake_health_server(health).await;
        std::fs::write(
            test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE),
            port.to_string(),
        )
        .expect("write daemon port");

        let identity = current_daemon_identity();
        let selected =
            daemon_port_if_compatible_at(&test_control_state(daemon_home.path()), &identity)
                .await
                .expect("mismatch health lookup");

        assert_eq!(selected, None);

        let _ = shutdown_tx.send(());
    }

    #[test]
    fn test_daemon_health_matches_recorded_pid_requires_exact_pid() {
        let mut health = DaemonHealth {
            project_count: 0,
            session_count: 0,
            stale_sessions: 0,
            daemon_version: current_daemon_identity().version,
            executable_path: current_daemon_identity().executable_path,
            auth_required: false,
            pid: Some(42),
            started_at_unix_secs: None,
        };

        assert!(daemon_health_matches_recorded_pid(&health, 42));
        assert!(!daemon_health_matches_recorded_pid(&health, 43));

        health.pid = None;
        assert!(!daemon_health_matches_recorded_pid(&health, 42));
    }

    #[tokio::test]
    async fn test_stop_incompatible_recorded_daemon_does_not_kill_unrelated_pid() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        #[cfg(windows)]
        let mut child = crate::process_util::hidden_command("powershell")
            .args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn long-running child");

        #[cfg(not(windows))]
        let mut child = crate::process_util::hidden_command("sleep")
            .arg("30")
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn long-running child");

        let child_pid = child.id();
        let health = DaemonHealth {
            project_count: 0,
            session_count: 0,
            stale_sessions: 0,
            daemon_version: current_daemon_identity().version,
            executable_path: "C:/unrelated/not-symforge-daemon.exe".to_string(),
            auth_required: false,
            pid: Some(child_pid),
            started_at_unix_secs: None,
        };
        let (port, shutdown_tx) = spawn_fake_health_server(health).await;
        std::fs::write(
            test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE),
            port.to_string(),
        )
        .expect("write daemon port");
        std::fs::write(
            test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PID_FILE),
            child_pid.to_string(),
        )
        .expect("write daemon pid");

        stop_incompatible_recorded_daemon_at(
            &test_control_state(daemon_home.path()),
            &current_daemon_identity(),
        )
        .await
        .expect("stop incompatible daemon");

        assert!(
            child.try_wait().expect("poll child").is_none(),
            "daemon pid safety checks must not terminate unrelated processes"
        );

        let _ = child.kill();
        let _ = child.wait();
        let _ = shutdown_tx.send(());
    }

    #[tokio::test]
    async fn test_stop_incompatible_recorded_daemon_cleans_port_file_without_pid() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let health = DaemonHealth {
            project_count: 0,
            session_count: 0,
            stale_sessions: 0,
            daemon_version: "0.0.0".to_string(),
            executable_path: current_daemon_identity().executable_path,
            auth_required: false,
            pid: None,
            started_at_unix_secs: None,
        };
        let (port, shutdown_tx) = spawn_fake_health_server(health).await;
        std::fs::write(
            test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE),
            port.to_string(),
        )
        .expect("write daemon port");

        stop_incompatible_recorded_daemon_at(
            &test_control_state(daemon_home.path()),
            &current_daemon_identity(),
        )
        .await
        .expect("stop incompatible daemon");

        assert!(
            !test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE).exists(),
            "incompatible daemon port file should be cleared"
        );

        let _ = shutdown_tx.send(());
    }

    #[tokio::test]
    async fn test_daemon_serves_session_scoped_repo_map_hook_endpoint() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-hook");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(77),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let response = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/repo-map",
                opened.session_id
            ))
            .send()
            .await
            .expect("hook request");

        assert!(
            response.status().is_success(),
            "repo-map hook endpoint should succeed, got {}",
            response.status()
        );

        let body = response.text().await.expect("hook body");
        assert!(
            body.contains("Index: 1 files, 1 symbols"),
            "repo-map hook output should come from daemon project instance, got: {body}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// caller-root guard parity (worktree-routing incident): daemon-proxied
    /// sidecar routes must enforce the SAME caller_root check the local
    /// sidecar router installs. A session whose ACTIVE project moved must 409
    /// a caller rooted at the old project instead of serving the wrong one.
    #[tokio::test]
    async fn test_daemon_sidecar_enforces_caller_root_guard() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-guard-home-a");
        let project_b = project_dir("symforge-guard-open-b");
        std::fs::write(project_a.path().join("src").join("a.rs"), "fn a() {}\n")
            .expect("write source a");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "guard".to_string(),
                pid: Some(88),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        // Default-open B: the session's ACTIVE project moves to B (locked
        // contract). A caller rooted at A must now be refused, not served B.
        client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("open B request")
            .error_for_status()
            .expect("open B status");

        let url = |extra: &str| {
            format!(
                "{base_url}/v1/sessions/{}/sidecar/repo-map{extra}",
                opened.session_id
            )
        };

        let mismatched = client
            .get(url(&format!("?caller_root={}", project_a.path().display())))
            .send()
            .await
            .expect("mismatched request");
        assert_eq!(
            mismatched.status(),
            StatusCode::CONFLICT,
            "caller_root=A must 409 once B is active"
        );

        // B was made ACTIVE moments ago. `require_queryable_sidecar_index`
        // answers 503 until B's publication catches up with its project
        // generation, and on a loaded runner the assertion below can land
        // inside that window -- which is what reddened Release 32660381244 and
        // 32665940448 with no regression behind it, and PR 715's rust job after
        // the 10s readiness retry alone ran out. Wait on that exact condition
        // in B's index first, with a wider bound; a timeout names both
        // generations, so a stuck publication reads differently from a slow one.
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));
        let publication_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
        loop {
            let generations = handle.state.projects.read().get(&project_b_id).map(|slot| {
                let project = slot.metadata.read();
                let data_plane = project.index.data_plane();
                (
                    data_plane.published_generation().project_generation,
                    data_plane.current_project_generation(),
                )
            });
            if matches!(generations, Some((published, current)) if published == current) {
                break;
            }
            assert!(
                std::time::Instant::now() < publication_deadline,
                "B's publication never caught up with its project generation within 30s; \
                 (published, current) = {generations:?}"
            );
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }

        //
        // Retry ONLY the readiness condition. Any other status is decided
        // immediately, so a real 409 still fails fast with its evidence rather
        // than being polled into a timeout.
        let readiness_deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        let matched = loop {
            let response = client
                .get(url(&format!("?caller_root={}", project_b.path().display())))
                .send()
                .await
                .expect("matched request");
            if response.status() != StatusCode::SERVICE_UNAVAILABLE
                || std::time::Instant::now() >= readiness_deadline
            {
                break response;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        };
        // The status and body are read BEFORE asserting. A bare `assert!` on
        // `is_success()` reports only its own message, so a failure here could
        // not be told apart from a 409 the guard raised, a 5xx the sidecar
        // returned, or anything else non-2xx -- which is exactly what left
        // Release 32660381244 undiagnosable. Reading the body consumes the
        // response, which is safe: nothing uses `matched` after this.
        let matched_status = matched.status();
        let matched_body = matched
            .text()
            .await
            .unwrap_or_else(|error| format!("<body unreadable: {error}>"));
        assert!(
            matched_status.is_success(),
            "caller_root=B (the active project) must be served, got {matched_status}: \
             {matched_body}"
        );

        let unpinned = client.get(url("")).send().await.expect("unpinned request");
        assert!(
            unpinned.status().is_success(),
            "a request without caller_root stays unguarded"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_daemon_workflow_repo_start_endpoint_matches_repo_map_route() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-workflow-repo-start");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(78),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let canonical = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/repo-map",
                opened.session_id
            ))
            .send()
            .await
            .expect("canonical request")
            .error_for_status()
            .expect("canonical status")
            .text()
            .await
            .expect("canonical body");

        let workflow = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/workflows/repo-start",
                opened.session_id
            ))
            .send()
            .await
            .expect("workflow request")
            .error_for_status()
            .expect("workflow status")
            .text()
            .await
            .expect("workflow body");

        assert_eq!(
            workflow, canonical,
            "workflow repo-start route should stay identical to the canonical repo-map route"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_daemon_serves_session_scoped_prompt_context_hook_endpoint() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-prompt-hook");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(88),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let response = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/prompt-context",
                opened.session_id
            ))
            .query(&[("text", "please inspect src/main.rs")])
            .send()
            .await
            .expect("hook request");

        assert!(
            response.status().is_success(),
            "prompt-context hook endpoint should succeed, got {}",
            response.status()
        );

        let body = response.text().await.expect("hook body");
        assert!(
            body.contains("src/main.rs") && body.contains("main"),
            "prompt-context hook output should come from daemon project instance, got: {body}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_daemon_workflow_prompt_context_endpoint_matches_canonical_route() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-workflow-prompt-context");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(89),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let canonical = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/prompt-context",
                opened.session_id
            ))
            .query(&[("text", "please inspect src/main.rs")])
            .send()
            .await
            .expect("canonical request")
            .error_for_status()
            .expect("canonical status")
            .text()
            .await
            .expect("canonical body");

        let workflow = client
            .get(format!(
                "{base_url}/v1/sessions/{}/sidecar/workflows/prompt-context",
                opened.session_id
            ))
            .query(&[("text", "please inspect src/main.rs")])
            .send()
            .await
            .expect("workflow request")
            .error_for_status()
            .expect("workflow status")
            .text()
            .await
            .expect("workflow body");

        assert_eq!(
            workflow, canonical,
            "workflow prompt-context route should stay identical to the canonical prompt-context route"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_index_folder_default_open_activates_target() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-daemon-a");
        let project_b = project_dir("symforge-daemon-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(55),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let reload = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("index request")
            .error_for_status()
            .expect("index status")
            .text()
            .await
            .expect("index body");
        assert!(
            reload.contains("Indexed"),
            "index_folder should report success, got: {reload}"
        );
        assert!(
            reload.contains("active_project="),
            "default open must report activation, got: {reload}"
        );

        let target_sessions = client
            .get(format!(
                "{base_url}/v1/projects/{}/sessions",
                project_key(&canonical_project_root(project_b.path()).expect("canonical root"))
            ))
            .send()
            .await
            .expect("session list request")
            .error_for_status()
            .expect("session list status")
            .json::<Vec<SessionSummary>>()
            .await
            .expect("session list body");
        assert_eq!(target_sessions.len(), 1);
        assert_eq!(target_sessions[0].session_id, opened.session_id);
        assert_eq!(
            target_sessions[0].project_id,
            project_key(&canonical_project_root(project_b.path()).expect("canonical root")),
            "session summary must report B as the ACTIVE project"
        );

        let home_sessions = client
            .get(format!(
                "{base_url}/v1/projects/{}/sessions",
                opened.project_id
            ))
            .send()
            .await
            .expect("home session list request")
            .error_for_status()
            .expect("home session list status")
            .json::<Vec<SessionSummary>>()
            .await
            .expect("home session list body");
        assert_eq!(
            home_sessions.len(),
            1,
            "opening B must not evict home A from the working set"
        );
        assert_eq!(home_sessions[0].session_id, opened.session_id);

        let outline = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/get_repo_map",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "detail": "full"
            }))
            .send()
            .await
            .expect("outline request")
            .error_for_status()
            .expect("outline status")
            .text()
            .await
            .expect("outline body");
        assert!(
            outline.contains("new.rs"),
            "unqualified reads must follow the ACTIVATED project B: {outline}"
        );
        assert!(
            !outline.contains("old.rs"),
            "default open of B must switch unqualified reads off home A: {outline}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Task 4 parity table (daemon route): explicit `project` selects the open
    /// project B, omission stays bound to the ACTIVE project (home A — B was
    /// opened additively, which never activates), and an unknown selector
    /// returns deterministic candidates without touching any index.
    #[tokio::test]
    async fn test_project_routing_parity_table() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-route-home-a");
        let project_b = project_dir("symforge-route-open-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "route-parity".to_string(),
                pid: Some(77),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        let opened_b = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: Some(true),
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("open B request")
            .error_for_status()
            .expect("open B status")
            .text()
            .await
            .expect("open B body");
        assert!(opened_b.contains("Indexed"), "open B: {opened_b}");

        let call = |tool: &str, body: serde_json::Value| {
            let client = client.clone();
            let url = format!("{base_url}/v1/sessions/{}/tools/{tool}", opened.session_id);
            async move {
                client
                    .post(url)
                    .json(&body)
                    .send()
                    .await
                    .expect("tool request")
                    .error_for_status()
                    .expect("tool status")
                    .text()
                    .await
                    .expect("tool body")
            }
        };

        // get_repo_map: explicit B vs omitted home A.
        let map_b = call(
            "get_repo_map",
            serde_json::json!({"detail": "full", "project": project_b_id}),
        )
        .await;
        assert!(
            map_b.contains("new.rs") && !map_b.contains("old.rs"),
            "explicit project must serve B: {map_b}"
        );
        let map_home = call("get_repo_map", serde_json::json!({"detail": "full"})).await;
        assert!(
            map_home.contains("old.rs") && !map_home.contains("new.rs"),
            "omission must serve immutable home A: {map_home}"
        );

        // get_file_content: exact read routed to B; home cannot see B's file.
        let content_b = call(
            "get_file_content",
            serde_json::json!({"path": "src/new.rs", "project": project_b_id}),
        )
        .await;
        assert!(
            content_b.contains("fn new_fn"),
            "explicit project read must return B's bytes: {content_b}"
        );
        let content_home = call(
            "get_file_content",
            serde_json::json!({"path": "src/new.rs"}),
        )
        .await;
        assert!(
            !content_home.contains("fn new_fn"),
            "home read must not leak B's bytes: {content_home}"
        );

        // search_files: discovery routed by explicit project.
        let files_b = call(
            "search_files",
            serde_json::json!({"query": "new.rs", "project": project_b_id}),
        )
        .await;
        assert!(
            files_b.contains("new.rs"),
            "explicit project search_files must serve B: {files_b}"
        );

        // Unknown selector: deterministic candidates, no index mutation.
        let unknown = call(
            "get_repo_map",
            serde_json::json!({"detail": "full", "project": "no-such-project"}),
        )
        .await;
        assert!(
            unknown.contains("not open") && unknown.contains(&project_b_id),
            "unknown selector must return candidates: {unknown}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Task 4 leftover: set-valued `search_files` fans out across targeted
    /// projects with attributed hits, one deterministic global cap, and honest
    /// refusals for the modes that stay single-project (resolve/coupling) and
    /// for a `project`+`projects` mutual-exclusion violation. A lone `project`
    /// selector keeps the FULL single-project handler (envelope, modes).
    #[tokio::test]
    async fn test_search_files_projects_fan_out() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-files-home-a");
        let project_b = project_dir("symforge-files-open-b");
        std::fs::write(
            project_a.path().join("src").join("widget_old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("widget_new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "files-fan-out".to_string(),
                pid: Some(78),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        let opened_b = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("open B request")
            .error_for_status()
            .expect("open B status")
            .text()
            .await
            .expect("open B body");
        assert!(opened_b.contains("Indexed"), "open B: {opened_b}");

        let call = |body: serde_json::Value| {
            let client = client.clone();
            let url = format!(
                "{base_url}/v1/sessions/{}/tools/search_files",
                opened.session_id
            );
            async move {
                client
                    .post(url)
                    .json(&body)
                    .send()
                    .await
                    .expect("tool request")
                    .error_for_status()
                    .expect("tool status")
                    .text()
                    .await
                    .expect("tool body")
            }
        };

        // All projects: attributed hits from BOTH, with project headers.
        let all = call(serde_json::json!({"query": "widget", "projects": ["*"]})).await;
        assert!(
            all.contains("widget_old.rs") && all.contains("widget_new.rs"),
            "wildcard fan-out must surface both projects' files: {all}"
        );
        assert!(
            all.contains(&format!("project: {}", opened.project_id))
                && all.contains(&format!("project: {project_b_id}")),
            "multi-target output must attribute hits by project: {all}"
        );

        // Explicit subset of one: only B's hits, flat (no headers).
        let only_b = call(serde_json::json!({"query": "widget", "projects": [project_b_id]})).await;
        assert!(
            only_b.contains("widget_new.rs") && !only_b.contains("widget_old.rs"),
            "single-target fan-out must serve only B: {only_b}"
        );
        assert!(
            !only_b.contains("── project:"),
            "single-target output renders flat: {only_b}"
        );

        // resolve mode stays single-project: honest refusal, no silent drop.
        let refused =
            call(serde_json::json!({"query": "widget", "resolve": true, "projects": ["*"]})).await;
        assert!(
            refused.contains("not supported with cross-project targeting"),
            "resolve mode must refuse cross-project targeting: {refused}"
        );

        // project + projects together: deterministic mutual-exclusion error.
        let conflict = call(serde_json::json!({
            "query": "widget",
            "project": opened.project_id,
            "projects": [project_b_id],
        }))
        .await;
        assert!(
            conflict.contains("mutually exclusive"),
            "project+projects must be rejected: {conflict}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// INCIDENT GUARD (2026-07-11): a test build must NEVER auto-spawn a
    /// daemon process — under `cargo test` the spawned `current_exe()` is the
    /// libtest binary and the `daemon` argument is a test FILTER, so spawning
    /// recursively re-runs the suite (exponential fork bomb, console-window
    /// flood). This pins the refusal at both seams.
    #[tokio::test]
    async fn test_test_builds_never_auto_spawn_daemon_processes() {
        let error = spawn_daemon_process(None).expect_err("test build must refuse to spawn");
        assert!(
            error.to_string().contains("test build"),
            "refusal must name the test-build guard: {error}"
        );

        // ensure_daemon_running with no daemon reachable must fail fast with
        // the same refusal instead of spawning or waiting on the start lock.
        let _env_lock = env_lock().await;
        let empty_home = TempDir::new().expect("empty home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", empty_home.path());
        let error = ensure_daemon_running_at(&test_control_state(empty_home.path()))
            .await
            .expect_err("no daemon + no spawn must error");
        assert!(
            error.to_string().contains("auto-spawn is disabled"),
            "ensure_daemon_running must fail fast without spawning: {error}"
        );
    }

    /// `symforge update` leaves sessions of the previous release running; one
    /// that loses its daemon connection must not replace the newer daemon.
    #[tokio::test]
    async fn an_older_session_never_replaces_a_newer_daemon() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let older = DaemonIdentity {
            version: "0.0.1".to_string(),
            executable_path: current_daemon_identity().executable_path,
        };

        let error = ensure_daemon_running_as(&test_control_state(daemon_home.path()), &older, None)
            .await
            .expect_err("an older identity must not take over");

        assert!(
            error.to_string().contains("newer symforge daemon"),
            "{error}"
        );
        assert!(
            error
                .to_string()
                .contains("end the newer daemon's process first"),
            "the refusal must say how to downgrade on purpose: {error}"
        );
        assert!(
            daemon_health_ok(handle.port).await,
            "the newer daemon must still be serving"
        );
        let _ = handle.shutdown_tx.send(());
    }

    /// nvm-windows makes `C:\Program Files\nodejs` a directory link to the
    /// active version dir, so `symforge update` can name the running daemon's
    /// binary through a different path. That is the same binary: the update
    /// must keep the daemon and say it did not start one.
    #[tokio::test]
    async fn the_update_keeps_a_same_version_daemon_named_through_a_linked_directory() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let exe = std::env::current_exe().expect("test binary path");
        let links = TempDir::new().expect("link dir");
        let linked_dir = links.path().join("linked");
        link_dir(exe.parent().expect("test binary dir"), &linked_dir);
        let linked_exe = linked_dir.join(exe.file_name().expect("test binary name"));

        let kept = ensure_installed_daemon_running_at(
            &test_control_state(daemon_home.path()),
            &linked_exe,
            env!("CARGO_PKG_VERSION"),
        )
        .await;
        unlink_dir(&linked_dir);

        assert_eq!(
            kept.expect("the running daemon is the same binary"),
            InstalledDaemon::Running {
                port: handle.port,
                started: false
            }
        );
        assert!(daemon_health_ok(handle.port).await);
        let _ = handle.shutdown_tx.send(());
    }

    /// Autospawn switched off, or a newer daemon owning the home, is policy:
    /// the update must report the restart as skipped, not fail (a failure
    /// rolls the new binary back).
    #[tokio::test]
    async fn the_update_reports_a_policy_refusal_as_a_skipped_restart() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let control_state_dir = test_control_state(daemon_home.path());
        let exe = std::env::current_exe().expect("test binary path");

        let off = {
            let _autospawn = EnvVarGuard::set(DAEMON_AUTOSPAWN_ENV, Path::new("off"));
            ensure_installed_daemon_running_at(&control_state_dir, &exe, "99.0.0").await
        };
        assert!(
            matches!(&off, Ok(InstalledDaemon::Skipped(why)) if why.contains(DAEMON_AUTOSPAWN_ENV)),
            "{off:?}"
        );

        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let older = ensure_installed_daemon_running_at(&control_state_dir, &exe, "0.0.1").await;
        assert!(
            matches!(&older, Ok(InstalledDaemon::Skipped(why)) if why.contains("newer daemon")),
            "{older:?}"
        );
        assert!(daemon_health_ok(handle.port).await);
        let _ = handle.shutdown_tx.send(());
    }

    /// A directory symlink, or on Windows without the symlink privilege a
    /// junction (same resolution through `canonicalize`).
    fn link_dir(target: &Path, link: &Path) {
        #[cfg(unix)]
        std::os::unix::fs::symlink(target, link).expect("symlink");
        #[cfg(windows)]
        if std::os::windows::fs::symlink_dir(target, link).is_err() {
            let status = crate::process_util::hidden_command("cmd")
                .args(["/C", "mklink", "/J"])
                .arg(link)
                .arg(target)
                .stdout(std::process::Stdio::null())
                .status()
                .expect("run mklink");
            assert!(status.success(), "mklink /J failed");
        }
    }

    /// Remove the link itself, never what it points at.
    fn unlink_dir(link: &Path) {
        #[cfg(unix)]
        std::fs::remove_file(link).expect("remove symlink");
        #[cfg(windows)]
        std::fs::remove_dir(link).expect("remove junction");
    }

    /// Task 8: after the daemon dies and a replacement comes up, the proxy
    /// reconnect must restore the WHOLE working set — home A stays home (same
    /// deterministic id) and additively-opened B is reopened and explicitly
    /// routable with the same id — before any read is served.
    #[tokio::test]
    async fn test_reconnect_reopens_home_and_working_set() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-reconnect-home-a");
        let project_b = project_dir("symforge-reconnect-open-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let first = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn first daemon");
        let base_url = format!("http://127.0.0.1:{}", first.port);
        let http = authed_client(&first);
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "reconnect".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project_a.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        // Open B additively through the proxy so the sibling root is recorded
        // WITHOUT changing the active project (home A stays active).
        let opened_b = server
            .index_folder(Parameters(IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: Some(true),
                allow_protected_root: None,
            }))
            .await;
        assert!(opened_b.starts_with("Indexed "), "open B: {opened_b}");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        // Kill the first daemon and bring up a replacement on the SAME home.
        // Wait on the OS-TAGGED port file — the one daemons actually write —
        // so daemon 1's shutdown cleanup provably finished before daemon 2
        // writes its own files (the untagged legacy name never exists, so
        // waiting on it is a no-op that races the cleanup).
        let _ = first.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            daemon_port_file_name(),
        ))
        .await;
        let second = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn second daemon");

        let stale_client = server
            .daemon_client
            .as_ref()
            .expect("daemon proxy client")
            .read()
            .await
            .clone();
        let stale_activation_lane = stale_client.activation_lane();
        crate::protocol::result_status::with_project_evidence_scope(None, async {
            let reconnected = stale_client
                .reconnect()
                .await
                .expect("direct reconnect probe");
            assert!(
                std::sync::Arc::ptr_eq(&stale_activation_lane, &reconnected.activation_lane()),
                "a reconnect replacement must retain the connection's activation lane"
            );
            assert!(
                crate::protocol::result_status::current_project_evidence().is_none(),
                "reconnect housekeeping receipts must not escape into the next user call"
            );
        })
        .await;

        // A routed read through the stale proxy: the first attempt fails, the
        // reconnect discovers the replacement, reopens home + B, verifies ids,
        // and the retry serves B.
        let map_b_input = serde_json::from_value(serde_json::json!({
            "detail": "full",
            "project": project_b_id,
        }))
        .expect("map input");
        let map_b = server.get_repo_map(Parameters(map_b_input)).await;
        assert!(
            map_b.contains("new.rs") && !map_b.contains("old.rs"),
            "explicit B must remain routable after reconnect: {map_b}"
        );

        // Unqualified reads still serve the ACTIVE project (home A — B was
        // opened additively, which never activates).
        let map_home_input =
            serde_json::from_value(serde_json::json!({"detail": "full"})).expect("home input");
        let map_home = server.get_repo_map(Parameters(map_home_input)).await;
        assert!(
            map_home.contains("old.rs") && !map_home.contains("new.rs"),
            "home must survive reconnect unchanged: {map_home}"
        );

        let _ = second.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Locked-contract regression (worktree-routing incident): a DEFAULT
    /// `index_folder` activates the opened project, and a reconnect across a
    /// daemon endpoint replacement must RESTORE that activation — otherwise
    /// unqualified reads silently fall back to the launch-CWD home, the exact
    /// wrong-repo failure from the field.
    #[tokio::test]
    async fn test_reconnect_restores_activated_project() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-reconnect-active-home-a");
        let project_b = project_dir("symforge-reconnect-active-open-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let first = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn first daemon");
        let base_url = format!("http://127.0.0.1:{}", first.port);
        let http = authed_client(&first);
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "reconnect-active".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project_a.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        // DEFAULT open of B: activates B for unqualified reads.
        let opened_b = server
            .index_folder(Parameters(IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(opened_b.starts_with("Indexed "), "open B: {opened_b}");
        assert!(
            opened_b.contains("active_project="),
            "default open must report activation: {opened_b}"
        );

        // Kill the daemon and bring up a replacement on the same home.
        let _ = first.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            daemon_port_file_name(),
        ))
        .await;
        let second = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn second daemon");

        // Unqualified read through the stale proxy: first attempt fails, the
        // reconnect discovers the replacement, restores the working set AND
        // re-activates B, and the retry must serve B — not home A.
        let map_input =
            serde_json::from_value(serde_json::json!({"detail": "full"})).expect("map input");
        let map = server.get_repo_map(Parameters(map_input)).await;
        assert!(
            map.contains("new.rs") && !map.contains("old.rs"),
            "activated project B must survive reconnect (unqualified read): {map}"
        );

        let _ = second.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Carried Slice 3 residual (T037 / 020:T072, frozen 028 edge case): a
    /// caller that cancels a non-abortable `index_folder` after the daemon
    /// began activation leaves the distributed outcome unknown — the daemon
    /// session's ACTIVE moved while the adapter mirror kept the last OBSERVED
    /// activation. The required resolution: an authoritative ACTIVE re-sync,
    /// never a half-published root. Concretely: (1) the unobserved activation
    /// never governs the adapter's unqualified reads — every read stays
    /// pinned to the last observed project, body and receipt agreeing on it —
    /// and (2) the caller's OBSERVED retry of the cancelled call is the
    /// authoritative re-sync after which both sides agree on the new ACTIVE.
    #[tokio::test]
    async fn a_cancelled_activation_never_governs_until_an_observed_resync() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-cancelled-activation-home-a");
        let project_b = project_dir("symforge-cancelled-activation-open-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "cancelled-activation".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project_a.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        // The cancellation: the daemon runs its non-abortable DEFAULT
        // activation of B to completion, but the ADAPTER never observes the
        // response. The raw HTTP hop below stands in for the caller-cancelled
        // adapter future — the daemon-side outcome is identical: the
        // session's ACTIVE moved to B and nobody on the adapter side knows.
        let activated_b = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("activate B request")
            .error_for_status()
            .expect("activate B status")
            .text()
            .await
            .expect("activate B body");
        assert!(
            activated_b.starts_with("Indexed "),
            "daemon-side activation must complete: {activated_b}"
        );

        // Control proving the divergence is real: the DAEMON's own unqualified
        // view now serves B. Without the adapter's pin, the fence below would
        // have nothing to defend against.
        let daemon_view = http
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/get_repo_map",
                opened.session_id
            ))
            .json(&serde_json::json!({ "detail": "full" }))
            .send()
            .await
            .expect("daemon view request")
            .error_for_status()
            .expect("daemon view status")
            .text()
            .await
            .expect("daemon view body");
        assert!(
            daemon_view.contains("new.rs"),
            "control: the daemon session ACTIVE must have moved to B: {daemon_view}"
        );

        // THE FENCE, half 1 — the unobserved activation must not govern: an
        // unqualified read through the adapter serves the last OBSERVED
        // project (home A), body and receipt agreeing on A. Serving B here
        // would report an activation nobody observed; pairing A's body with
        // B's receipt (or vice versa) would be the half-published root.
        let (map_home, home_receipt) =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let input = serde_json::from_value(serde_json::json!({"detail": "full"}))
                    .expect("map input");
                let map = server.get_repo_map(Parameters(input)).await;
                let receipt = crate::protocol::result_status::current_project_evidence();
                (map, receipt)
            })
            .await;
        assert!(
            map_home.contains("old.rs") && !map_home.contains("new.rs"),
            "an unqualified read must stay on the last OBSERVED activation: {map_home}"
        );
        let home_receipt = home_receipt.expect("a proxied read must carry a daemon receipt");
        assert_eq!(
            home_receipt.project_id, opened.project_id,
            "the receipt must name the same project that served the body"
        );

        // THE FENCE, half 2 — the authoritative re-sync: the caller's natural
        // retry of the cancelled call, OBSERVED through the adapter this
        // time, resolves the unknown outcome. Both sides converge on B.
        let retried = server
            .index_folder(Parameters(IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            retried.starts_with("Indexed "),
            "the observed retry must complete: {retried}"
        );
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));
        let (map_b, receipt_b) =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let input = serde_json::from_value(serde_json::json!({"detail": "full"}))
                    .expect("map input");
                let map = server.get_repo_map(Parameters(input)).await;
                let receipt = crate::protocol::result_status::current_project_evidence();
                (map, receipt)
            })
            .await;
        assert!(
            map_b.contains("new.rs") && !map_b.contains("old.rs"),
            "after the observed re-sync the activation governs unqualified reads: {map_b}"
        );
        let receipt_b = receipt_b.expect("the re-synced read must carry a daemon receipt");
        assert_eq!(
            receipt_b.project_id, project_b_id,
            "body and receipt must agree on the re-synced ACTIVE"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            daemon_port_file_name(),
        ))
        .await;
    }

    #[tokio::test]
    async fn test_tool_receipt_carries_project_evidence() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-receipt-home-a");
        let project_b = project_dir("symforge-receipt-open-é");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "receipt".to_string(),
                pid: Some(80),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        let opened_b = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                // Additive: keep home A active so the omitted-project
                // attestation below asserts the home evidence.
                add: Some(true),
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("open B request")
            .error_for_status()
            .expect("open B status")
            .text()
            .await
            .expect("open B body");
        assert!(opened_b.contains("Indexed"), "open B: {opened_b}");

        let evidence_for = |body: serde_json::Value| {
            let client = client.clone();
            let url = format!(
                "{base_url}/v1/sessions/{}/tools/get_repo_map",
                opened.session_id
            );
            async move {
                let response = client
                    .post(url)
                    .json(&body)
                    .send()
                    .await
                    .expect("tool request")
                    .error_for_status()
                    .expect("tool status");
                let header = response
                    .headers()
                    .get(crate::protocol::result_status::PROJECT_EVIDENCE_HEADER)
                    .expect("evidence header must be present");
                serde_json::from_slice::<crate::protocol::result_status::ProjectEvidence>(
                    header.as_bytes(),
                )
                .expect("evidence header must parse as typed evidence")
            }
        };

        let home_evidence = evidence_for(serde_json::json!({"detail": "compact"})).await;
        assert_eq!(
            home_evidence.project_id, opened.project_id,
            "omitted project must be served (and attested) by home"
        );
        assert!(
            home_evidence.canonical_root.is_some() && !home_evidence.index_state.is_empty(),
            "evidence carries root and index state: {home_evidence:?}"
        );

        let routed_evidence =
            evidence_for(serde_json::json!({"detail": "compact", "project": project_b_id})).await;
        assert_eq!(
            routed_evidence.project_id, project_b_id,
            "explicit project must be attested by the routed sibling"
        );

        let response = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/search_text",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "query": "new_fn",
                "project": project_b_id,
            }))
            .send()
            .await
            .expect("cross-project search request")
            .error_for_status()
            .expect("cross-project search status");
        let header = response
            .headers()
            .get(crate::protocol::result_status::PROJECT_EVIDENCE_HEADER)
            .expect("cross-project search evidence header");
        let search_evidence = serde_json::from_slice::<
            crate::protocol::result_status::ProjectEvidence,
        >(header.as_bytes())
        .expect("cross-project search evidence parses");
        let body = response.text().await.expect("cross-project search body");
        assert!(
            body.contains("new_fn") && !body.contains("old_fn"),
            "scalar search body must come from project B: {body}"
        );
        assert_eq!(
            search_evidence.project_id, project_b_id,
            "scalar cross-project body and receipt must identify the same project"
        );

        // Exercise the actual adapter parser, not only raw reqwest header
        // access. The unicode project root is valid UTF-8 JSON but is not a
        // `HeaderValue::to_str()` ASCII value.
        let proxy = DaemonSessionClient::new_for_test_at(
            base_url,
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        );
        let (proxied_body, proxied_evidence) =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let body = proxy
                    .call_tool_value(
                        "search_text",
                        serde_json::json!({
                            "query": "new_fn",
                            "project": project_b_id,
                        }),
                    )
                    .await
                    .expect("proxied unicode-project search");
                let evidence = crate::protocol::result_status::current_project_evidence();
                (body, evidence)
            })
            .await;
        assert!(
            proxied_body.contains("new_fn"),
            "proxied body: {proxied_body}"
        );
        let proxied_evidence =
            proxied_evidence.expect("unicode project receipt must survive adapter parsing");
        assert_eq!(proxied_evidence.project_id, project_b_id);
        assert!(
            proxied_evidence
                .canonical_root
                .as_deref()
                .is_some_and(|root| root.contains('é')),
            "unicode canonical root must remain byte-exact: {proxied_evidence:?}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Task 9: the reaper re-checks the SAME last-seen observation under the
    /// sessions write lock before claiming — a heartbeat that advances the
    /// timestamp between candidate collection and the claim WINS and preserves
    /// the session; an actually-expired session closes through the normal
    /// close path, removing orphan project membership exactly once.
    #[test]
    fn test_reaper_rechecks_heartbeat_before_close() {
        let project = project_dir("symforge-reaper");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "reaper".to_string(),
                pid: None,
            })
            .expect("open session");

        // Simulate a real sweep: an ANCIENT observation and a cutoff in the
        // recent past (now - ttl), exactly the shape reap_expired_sessions
        // produces. A heartbeat between observation and claim advances
        // last_seen past the cutoff, so the claim must lose.
        let ancient: u64 = 1_000;
        let store_last_seen = |value: u64| {
            let sessions = state.sessions.read();
            sessions
                .get(&opened.session_id)
                .expect("session")
                .last_seen_at
                .store(value, Ordering::Relaxed);
        };
        store_last_seen(ancient);
        let cutoff = now_epoch_millis().saturating_sub(60_000);
        assert!(
            ancient < cutoff,
            "test premise: ancient observation expired"
        );

        state.heartbeat(&opened.session_id); // advances last_seen to now > cutoff
        assert!(
            !state.close_session_if_expired(&opened.session_id, ancient, cutoff),
            "a heartbeat between observation and claim must preserve the session"
        );
        assert!(
            state.sessions.read().contains_key(&opened.session_id),
            "session survives the losing claim"
        );

        // Genuinely expired: same ancient observation, no heartbeat since.
        // Claim wins, the session closes through the normal path, and the
        // project whose only member it was is torn down exactly once.
        store_last_seen(ancient);
        assert!(
            state.close_session_if_expired(&opened.session_id, ancient, cutoff),
            "an expired unchanged observation must be claimed"
        );
        assert!(
            !state.sessions.read().contains_key(&opened.session_id),
            "claimed session is removed"
        );
        assert!(
            !state.projects.read().contains_key(&opened.project_id),
            "orphan project membership is removed once"
        );
        // A late heartbeat cannot resurrect the claimed session.
        assert!(
            !state.heartbeat(&opened.session_id).known_session,
            "heartbeat after the claim must fail, not resurrect"
        );

        // Sweep entry point: an expired session found by reap_expired_sessions
        // is closed with the same guarantees.
        let reopened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "reaper-sweep".to_string(),
                pid: None,
            })
            .expect("reopen session");
        {
            let sessions = state.sessions.read();
            sessions
                .get(&reopened.session_id)
                .expect("session")
                .last_seen_at
                .store(1, Ordering::Relaxed); // ancient heartbeat
        }
        let reaped = state.reap_expired_sessions(std::time::Duration::from_secs(60));
        assert_eq!(reaped, 1, "sweep must reap exactly the expired session");
        assert!(!state.sessions.read().contains_key(&reopened.session_id));
    }

    /// A long-lived child the test owns, so the "live pid" case is a real process.
    fn spawn_sleeper() -> std::process::Child {
        #[cfg(windows)]
        let mut command = crate::process_util::hidden_command("powershell");
        #[cfg(windows)]
        command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 60"]);
        #[cfg(not(windows))]
        let mut command = crate::process_util::hidden_command("sleep");
        #[cfg(not(windows))]
        command.arg("60");
        command
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn long-running child")
    }

    /// A process that has definitely exited. Keep the `Child` in scope for the
    /// whole test: on Windows its open handle pins the pid, so the OS cannot
    /// hand it to an unrelated process before the probe runs.
    fn dead_child() -> std::process::Child {
        let mut child = spawn_sleeper();
        child.kill().expect("kill child");
        child.wait().expect("reap child");
        child
    }

    fn open_session_with_pid(
        state: &DaemonState,
        project: &TempDir,
        pid: u32,
    ) -> OpenProjectResponse {
        state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "mcp-stdio".to_string(),
                pid: Some(pid),
            })
            .expect("open session")
    }

    fn set_last_seen(state: &DaemonState, session_id: &str, millis: u64) {
        state
            .sessions
            .read()
            .get(session_id)
            .expect("session")
            .last_seen_at
            .store(millis, Ordering::Relaxed);
    }

    /// The pid rule needs BOTH halves: a stale heartbeat and a dead process.
    /// A dead pid with a fresh heartbeat may be a beat in flight, and a live
    /// pid with a stale heartbeat is a busy or suspended adapter; neither is
    /// reaped. The sweep is the daemon's own tick body.
    #[test]
    fn test_reaper_closes_only_stale_sessions_whose_pid_is_dead() {
        let project = project_dir("symforge-pid-reaper");
        let state = DaemonState::new();
        let mut live_child = spawn_sleeper();
        let stale = now_epoch_millis() - 10 * 60_000;

        let (dead_a, dead_b, dead_c) = (dead_child(), dead_child(), dead_child());
        let dead_stale = open_session_with_pid(&state, &project, dead_a.id());
        let dead_fresh = open_session_with_pid(&state, &project, dead_b.id());
        // The only member of its project: reaping it must retire the slot.
        let lonely_project = project_dir("symforge-pid-reaper-lonely");
        let lonely = open_session_with_pid(&state, &lonely_project, dead_c.id());
        set_last_seen(&state, &lonely.session_id, stale);
        let live_stale = open_session_with_pid(&state, &project, live_child.id());
        let no_pid_stale = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "http".to_string(),
                pid: None,
            })
            .expect("open pid-less session");
        set_last_seen(&state, &dead_stale.session_id, stale);
        set_last_seen(&state, &live_stale.session_id, stale);
        set_last_seen(&state, &no_pid_stale.session_id, stale);

        let reaped = state.reap_dead_pid_sessions(STALE_SESSION_HEARTBEAT);
        let open = |id: &str| state.sessions.read().contains_key(id);
        let survived = (
            open(&dead_stale.session_id),
            open(&dead_fresh.session_id),
            open(&live_stale.session_id),
            open(&no_pid_stale.session_id),
        );
        let _ = live_child.kill();
        let _ = live_child.wait();

        assert_eq!(
            reaped, 2,
            "only the stale sessions with a dead pid are reaped"
        );
        assert!(
            !state.projects.read().contains_key(&lonely.project_id),
            "a reaped session that was its project's last member retires the project slot"
        );
        assert_eq!(
            survived,
            (false, true, true, true),
            "dead+stale gone; dead+fresh, live+stale and pid-less+stale kept"
        );
        assert!(
            state.projects.read().contains_key(&dead_fresh.project_id),
            "the project stays open for its surviving sessions"
        );
    }

    /// Health separates live from stale by heartbeat age at query time, and
    /// the per-project session list carries the same verdict.
    #[test]
    fn test_health_and_session_list_report_live_versus_stale() {
        let project = project_dir("symforge-stale-health");
        let state = DaemonState::new();
        let live = open_session_with_pid(&state, &project, std::process::id());
        let stale_a = open_session_with_pid(&state, &project, std::process::id());
        let stale_b = open_session_with_pid(&state, &project, std::process::id());
        let old = now_epoch_millis() - 10 * 60_000;
        set_last_seen(&state, &stale_a.session_id, old);
        set_last_seen(&state, &stale_b.session_id, old);

        let health = state.health();
        assert_eq!((health.session_count, health.stale_sessions), (3, 2));
        let rows = state.list_sessions(&live.project_id).expect("sessions");
        let stale_by_id: Vec<(&str, bool)> = rows
            .iter()
            .map(|row| (row.session_id.as_str(), row.stale))
            .collect();
        assert!(stale_by_id.contains(&(live.session_id.as_str(), false)));
        assert!(stale_by_id.contains(&(stale_a.session_id.as_str(), true)));
        assert!(stale_by_id.contains(&(stale_b.session_id.as_str(), true)));
        let inventory = state
            .render_session_project_inventory(&live.session_id)
            .expect("inventory");
        assert!(
            inventory.contains("daemon sessions: 1 heartbeating, 2 stale (heartbeat > 120 s)"),
            "{inventory}"
        );

        state.heartbeat(&stale_a.session_id);
        assert_eq!(state.health().stale_sessions, 1, "a heartbeat revives one");
    }

    /// The adapter's exit path: however the served body ends, the session it
    /// opened is closed on the daemon instead of leaking until the reaper.
    #[tokio::test]
    async fn test_run_then_close_session_closes_when_the_body_errs_early() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-close-on-err");
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        // ponytail: match instead of expect — DaemonSessionClient has no Debug impl.
        let session = match connect_or_spawn_session_at(
            project.path(),
            "close-on-err",
            Some(std::process::id()),
            &test_control_state(daemon_home.path()),
        )
        .await
        {
            Ok(session) => session,
            Err(error) => panic!("open session: {error:#}"),
        };
        assert_eq!(handle.state.health().session_count, 1);

        let result: anyhow::Result<()> =
            run_then_close_session(session, async |_slot| Err(anyhow::anyhow!("early return")))
                .await;

        assert_eq!(
            result
                .expect_err("the body's error is preserved")
                .to_string(),
            "early return"
        );
        assert_eq!(
            handle.state.health().session_count,
            0,
            "the session must be closed on the daemon"
        );
        let _ = handle.shutdown_tx.send(());
    }

    /// A reconnect holds the slot's write lock for as long as the daemon open
    /// takes. An adapter exiting meanwhile must give up within its bound
    /// instead of queueing behind that lock.
    #[tokio::test]
    async fn test_exit_close_gives_up_while_a_reconnect_holds_the_slot() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-close-bound");
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        // ponytail: match instead of expect — DaemonSessionClient has no Debug impl.
        let session = match connect_or_spawn_session_at(
            project.path(),
            "close-bound",
            Some(std::process::id()),
            &test_control_state(daemon_home.path()),
        )
        .await
        {
            Ok(session) => session,
            Err(error) => panic!("open session: {error:#}"),
        };
        let slot: SessionSlot = Arc::new(tokio::sync::RwLock::new(session.clone()));
        let (held_tx, held_rx) = tokio::sync::oneshot::channel();
        let holder_slot = Arc::clone(&slot);
        let holder = tokio::spawn(async move {
            let _write = holder_slot.write().await;
            let _ = held_tx.send(());
            tokio::time::sleep(std::time::Duration::from_secs(60)).await;
        });
        held_rx.await.expect("write lock held");

        let started = std::time::Instant::now();
        tokio::time::timeout(
            std::time::Duration::from_secs(5),
            close_current_session(session, Some(slot), std::time::Duration::from_millis(200)),
        )
        .await
        .expect("the exit close must return within its bound, not wait for the reconnect");
        assert!(started.elapsed() < std::time::Duration::from_secs(3));
        assert_eq!(
            handle.state.health().session_count,
            1,
            "it gave up, so the reaper still owns the session"
        );
        holder.abort();
        let _ = handle.shutdown_tx.send(());
    }

    /// The sweep the reaper tick runs applies the pid rule even when the TTL
    /// rule has nothing to do (default TTL, heartbeat only ten minutes old).
    #[tokio::test]
    async fn test_reaper_sweep_applies_the_pid_rule_off_the_async_worker() {
        let project = project_dir("symforge-sweep-wiring");
        let state = Arc::new(DaemonState::new());
        let mut dead = dead_child();
        let opened = open_session_with_pid(&state, &project, dead.id());
        set_last_seen(&state, &opened.session_id, now_epoch_millis() - 10 * 60_000);

        let counts = sweep_sessions_off_thread(Arc::clone(&state), session_ttl_from_env()).await;

        assert_eq!(
            counts,
            (0, 1),
            "TTL rule idle, pid rule reaps the dead session"
        );
        assert!(!state.sessions.read().contains_key(&opened.session_id));
        dead.wait().expect("child stays reaped");
    }

    /// After a reconnect the server's slot holds a DIFFERENT client than the
    /// one the adapter started with; the exit close must end that one.
    #[tokio::test]
    async fn test_exit_close_ends_the_session_a_reconnect_left_in_the_slot() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-close-slot");
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let control = test_control_state(daemon_home.path());
        // ponytail: match instead of expect — DaemonSessionClient has no Debug impl.
        let open = async || match connect_or_spawn_session_at(
            project.path(),
            "close-slot",
            Some(std::process::id()),
            &control,
        )
        .await
        {
            Ok(session) => session,
            Err(error) => panic!("open session: {error:#}"),
        };
        let original = open().await;
        let replacement = open().await;
        let replacement_id = replacement.session_id().to_string();
        assert_eq!(handle.state.health().session_count, 2);

        let result: anyhow::Result<()> = run_then_close_session(original, async |slot| {
            *slot = Some(Arc::new(tokio::sync::RwLock::new(replacement)));
            Ok(())
        })
        .await;

        result.expect("body result is preserved");
        let remaining: Vec<String> = handle.state.sessions.read().keys().cloned().collect();
        assert_eq!(remaining.len(), 1, "exactly one session is closed");
        assert_ne!(
            remaining[0], replacement_id,
            "the session in the slot is the one that closes"
        );
        let _ = handle.shutdown_tx.send(());
    }

    /// Task 7: `status(detail="projects")` renders the session's open-project
    /// inventory (ids, home marker, counts, snapshot evidence), and full-surface
    /// `health` gains the same inventory once more than one project is open.
    #[tokio::test]
    async fn test_status_projects_detail_lists_session_inventory() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-inventory-home-a");
        let project_b = project_dir("symforge-inventory-open-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "inventory".to_string(),
                pid: Some(79),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        // health BEFORE the second open: no inventory section (compatibility).
        let health_single = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/health_compact",
                opened.session_id
            ))
            .json(&serde_json::json!({}))
            .send()
            .await
            .expect("health request")
            .error_for_status()
            .expect("health status")
            .text()
            .await
            .expect("health body");
        assert!(
            !health_single.contains("── projects ──"),
            "single-project health must stay byte-compatible: {health_single}"
        );

        let opened_b = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("open B request")
            .error_for_status()
            .expect("open B status")
            .text()
            .await
            .expect("open B body");
        assert!(opened_b.contains("Indexed"), "open B: {opened_b}");

        let inventory = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/status",
                opened.session_id
            ))
            .json(&serde_json::json!({"detail": "projects"}))
            .send()
            .await
            .expect("status request")
            .error_for_status()
            .expect("status status")
            .text()
            .await
            .expect("status body");
        assert!(
            inventory.contains(&opened.project_id) && inventory.contains(&project_b_id),
            "inventory must list both open projects: {inventory}"
        );
        assert!(
            inventory.contains(&format!("{} home=yes", opened.project_id)),
            "home project must carry the home marker: {inventory}"
        );
        assert!(
            inventory.contains(&format!("{project_b_id} active=yes")),
            "the default-opened project must carry the active marker: {inventory}"
        );
        assert!(
            inventory.contains("snapshot=present") || inventory.contains("snapshot=absent"),
            "inventory rows must carry snapshot evidence: {inventory}"
        );
        assert!(
            inventory.contains("last_seen=") && inventory.contains("ttl_secs="),
            "inventory must expose session last-seen and reaper TTL evidence: {inventory}"
        );

        let health_multi = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/health_compact",
                opened.session_id
            ))
            .json(&serde_json::json!({}))
            .send()
            .await
            .expect("health multi request")
            .error_for_status()
            .expect("health multi status")
            .text()
            .await
            .expect("health multi body");
        assert!(
            health_multi.contains("── projects ──") && health_multi.contains(&project_b_id),
            "multi-project health must expose the inventory: {health_multi}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Task 5: structural edits route by explicit project. An explicit B edit
    /// mutates ONLY B, an omitted edit mutates the ACTIVE project (home A — B
    /// is opened ADDITIVELY here, which never activates), and an
    /// unknown/ambiguous target writes NOTHING anywhere. Worktree routing and
    /// `working_directory` validation run against the SELECTED project's
    /// repository (the existing per-project edit safety, now bound by the
    /// resolver).
    #[tokio::test]
    async fn test_explicit_project_edit_routes_and_preserves_worktree() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-edit-route-a");
        let project_b = project_dir("symforge-edit-route-b");
        let file_a = project_a.path().join("src").join("lib.rs");
        let file_b = project_b.path().join("src").join("lib.rs");
        std::fs::write(&file_a, "pub fn shared_name() -> u32 { 1 }\n").expect("write source a");
        std::fs::write(&file_b, "pub fn shared_name() -> u32 { 1 }\n").expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "edit-route".to_string(),
                pid: Some(78),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));

        let opened_b = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: Some(true),
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("open B request")
            .error_for_status()
            .expect("open B status")
            .text()
            .await
            .expect("open B body");
        assert!(opened_b.contains("Indexed"), "open B: {opened_b}");

        let edit = |body: serde_json::Value| {
            let client = client.clone();
            let url = format!(
                "{base_url}/v1/sessions/{}/tools/replace_symbol_body",
                opened.session_id
            );
            async move {
                client
                    .post(url)
                    .json(&body)
                    .send()
                    .await
                    .expect("edit request")
                    .error_for_status()
                    .expect("edit status")
                    .text()
                    .await
                    .expect("edit body")
            }
        };

        // Explicit B edit mutates ONLY B.
        let result_b = edit(serde_json::json!({
            "path": "src/lib.rs",
            "name": "shared_name",
            "new_body": "pub fn shared_name() -> u32 { 2 }",
            "project": project_b_id,
        }))
        .await;
        let on_disk_b = std::fs::read_to_string(&file_b).expect("read B");
        let on_disk_a = std::fs::read_to_string(&file_a).expect("read A");
        assert!(
            on_disk_b.contains("{ 2 }"),
            "explicit B edit must mutate B: {result_b}\n{on_disk_b}"
        );
        assert!(
            on_disk_a.contains("{ 1 }"),
            "explicit B edit must not touch home A: {on_disk_a}"
        );

        // Omitted edit mutates the ACTIVE project (home A — B was opened additively).
        let result_a = edit(serde_json::json!({
            "path": "src/lib.rs",
            "name": "shared_name",
            "new_body": "pub fn shared_name() -> u32 { 3 }",
        }))
        .await;
        let on_disk_a = std::fs::read_to_string(&file_a).expect("read A after");
        let on_disk_b = std::fs::read_to_string(&file_b).expect("read B after");
        assert!(
            on_disk_a.contains("{ 3 }"),
            "omitted edit must mutate home A: {result_a}\n{on_disk_a}"
        );
        assert!(
            on_disk_b.contains("{ 2 }"),
            "omitted edit must not touch B: {on_disk_b}"
        );

        // Unknown target writes NOTHING.
        let refused = edit(serde_json::json!({
            "path": "src/lib.rs",
            "name": "shared_name",
            "new_body": "pub fn shared_name() -> u32 { 4 }",
            "project": "no-such-project",
        }))
        .await;
        assert!(
            refused.contains("not open"),
            "unknown edit target must refuse with candidates: {refused}"
        );
        assert!(
            !std::fs::read_to_string(&file_a)
                .expect("read A final")
                .contains("{ 4 }")
                && !std::fs::read_to_string(&file_b)
                    .expect("read B final")
                    .contains("{ 4 }"),
            "unknown edit target must write nothing"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// T016 / TR-01 / FR-006 / FR-007 (SC-002): in the default daemon-proxy
    /// topology the front-end `status` readout MUST reflect the DAEMON's
    /// populated index (the one that actually serves queries) — never the empty
    /// front-end `self.index`.
    ///
    /// This drives the REAL proxy path end-to-end:
    ///   1. spawn a daemon, open a session, build a `new_daemon_proxy`
    ///      front-end server (the exact shape `run_remote_mcp_server_async`
    ///      constructs for an MCP client);
    ///   2. index the project through the proxy so the DAEMON's index is warm;
    ///   3. run a real query (`search_symbols`) through the proxy and confirm it
    ///      serves the indexed symbol from the daemon;
    ///   4. call `status` through the front-end and assert the readout reports
    ///      `index_ready: true` with a non-zero `index_files` count.
    ///
    /// The test also asserts the front-end's OWN `self.index` stays EMPTY,
    /// proving `status` did not read it. This is the air-tight form of the bug:
    /// pre-fix, step 4 failed two ways — the daemon had no `status` dispatch arm
    /// (`unknown tool 'status'`) and the front-end read its empty index
    /// (`index_ready: false`, `index_files: 0`). Post-fix it reports the served
    /// index.
    ///
    /// Coverage limits (honest): this exercises the in-process front-end →
    /// daemon HTTP proxy on loopback, which is the production topology's data
    /// path. It does NOT exercise the OS desktop launcher / CWD discovery
    /// (TR-03, a separate phase) nor a cross-binary version skew; those remain
    /// for live-verify against a built 8.0.0 binary.
    #[tokio::test]
    async fn test_status_index_matches_daemon_proxy_after_symforge_serve() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        // `status_stel_tool`'s front-end entry gate requires the compact surface.
        let _surface_guard = EnvVarGuard::set_str("SYMFORGE_SURFACE", "compact");

        // A project with one real Rust symbol so the daemon index is non-empty
        // and a query can demonstrably serve from it.
        let project = project_dir("symforge-status-proxy");
        std::fs::write(
            project.path().join("src").join("lib.rs"),
            "pub fn served_symbol() -> u32 { 42 }\n",
        )
        .expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "status-proxy".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        // The exact front-end an MCP client gets: empty self.index, proxying to
        // the warm daemon.
        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        // Index the project through the proxy → populates the DAEMON's index.
        let indexed = server
            .index_folder(Parameters(IndexFolderInput {
                path: project.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            indexed.starts_with("Indexed "),
            "daemon proxy index_folder must succeed, got: {indexed}"
        );

        // Run a real query through the proxy: it must serve the indexed symbol
        // from the warm daemon index (so a successful query is established).
        // Build the input from JSON so this stays robust to optional-field
        // additions on `SearchSymbolsInput`.
        let search_input = serde_json::from_value(serde_json::json!({
            "query": "served_symbol"
        }))
        .expect("search_symbols input");
        let query = server.search_symbols(Parameters(search_input)).await;
        assert!(
            query.contains("served_symbol"),
            "proxied query must serve the indexed symbol from the warm daemon, got: {query}"
        );

        // Now read `status` through the front-end. With the TR-01 fix it proxies
        // to the daemon and reports the SERVED index.
        let status_result = server
            .status_stel_tool(Parameters(crate::stel::StelStatusRequest::default()))
            .await
            .expect("status dispatch");
        let serialized = serde_json::to_value(&status_result).expect("serialize status result");
        let status_body = serialized["content"][0]["text"]
            .as_str()
            .expect("status result text")
            .to_string();

        assert!(
            status_body.contains("index_ready: true"),
            "status must report the served daemon index as ready (FR-006), got:\n{status_body}"
        );
        // A successful query implies non-zero counts — the index_files line must
        // not be zero (SC-002).
        assert!(
            !status_body.contains("index_files: 0"),
            "status must report non-zero index_files for the served index (SC-002), got:\n{status_body}"
        );
        assert!(
            status_body.contains("index_files: 1\n"),
            "status must report exactly the single indexed file from the daemon, got:\n{status_body}"
        );

        // Air-tight: the front-end's OWN index stayed empty; `status` reported
        // the daemon's index, not this one. This is what was broken pre-fix.
        assert_eq!(
            server.index().data_plane().published_state().file_count,
            0,
            "front-end self.index must remain empty — status must source from the daemon"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_symforge_edit_apply_commits_through_daemon_proxy() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let _surface_guard = EnvVarGuard::set_str("SYMFORGE_SURFACE", "compact");

        let project = project_dir("symforge-edit-proxy");
        let file_path = project.path().join("src").join("lib.rs");
        std::fs::write(&file_path, "pub fn proxy_edit() -> u32 { 1 }\n").expect("write source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "edit-proxy".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        let indexed = server
            .index_folder(Parameters(IndexFolderInput {
                path: project.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            indexed.starts_with("Indexed "),
            "daemon proxy index_folder must succeed, got: {indexed}"
        );
        assert_eq!(
            server.index().data_plane().published_state().file_count,
            0,
            "front-end proxy index is intentionally empty"
        );

        let result = server
            .symforge_edit_facade_tool(Parameters(crate::stel::StelEditRequest {
                path: "src/lib.rs".to_string(),
                symbol: Some("proxy_edit".to_string()),
                body: Some("pub fn proxy_edit() -> u32 { 2 }".to_string()),
                apply: Some(true),
                ..Default::default()
            }))
            .await
            .expect("symforge_edit dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize symforge_edit result");
        let body = serialized["content"][0]["text"]
            .as_str()
            .expect("symforge_edit result text");
        assert!(
            !body.starts_with("Index not loaded."),
            "daemon-proxy apply must not inspect the empty front-end index:\n{body}"
        );

        let on_disk = std::fs::read_to_string(&file_path).expect("read edited file");
        assert!(
            on_disk.contains("{ 2 }"),
            "symforge_edit apply must commit through the daemon proxy, got:\n{on_disk}\n\nbody:\n{body}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// F6 regression: a `symforge_edit` apply carrying `working_directory`
    /// must route the write into the sibling git worktree through the DAEMON
    /// dispatch path (front-end proxy → daemon `execute_tool_call` →
    /// `edit_within_symbol`), NOT into the daemon's indexed root; and a
    /// `working_directory` that is not a recognized worktree must error loudly
    /// instead of silently writing to the indexed root.
    ///
    /// This is the path the field bug lived on: the in-process direct-dispatch
    /// tests (`tests/worktree_awareness.rs`) never exercised the daemon's own
    /// `execute_tool_call` server, so a daemon that resolved edits through the
    /// no-op `DefaultEditHook` (worktree routing not effective) passed every
    /// existing test while writing to the wrong tree in production.
    #[tokio::test]
    async fn test_symforge_edit_apply_routes_into_worktree_through_daemon_proxy() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        // A real git repo (main checkout) with one committed symbol.
        let project = project_dir("symforge-wt-route-main");
        let main_root = project.path().to_path_buf();
        let main_file = main_root.join("src").join("lib.rs");
        std::fs::write(&main_file, "pub fn wt_edit() -> u32 { 1 }\n").expect("write source");
        let git = |args: &[&str]| {
            let out = crate::process_util::hidden_command("git")
                .current_dir(&main_root)
                .args(args)
                .output()
                .unwrap_or_else(|e| panic!("git {args:?} spawn: {e}"));
            assert!(
                out.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&out.stderr)
            );
        };
        git(&["init", "-b", "main"]);
        git(&["config", "user.email", "t@t.test"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["add", "-A"]);
        git(&["commit", "-q", "-m", "init"]);

        // A sibling worktree (outside the main checkout) on a new branch.
        let wt_parent = TempDir::new().expect("worktree parent");
        let worktree_root = wt_parent.path().join("wt_one");
        git(&[
            "worktree",
            "add",
            worktree_root.to_str().expect("utf-8 worktree path"),
            "-b",
            "feature",
        ]);
        let worktree_file = worktree_root.join("src").join("lib.rs");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: main_root.display().to_string(),
                client_name: "wt-route".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(main_root.clone());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        let indexed = server
            .index_folder(Parameters(IndexFolderInput {
                path: main_root.display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            indexed.starts_with("Indexed "),
            "daemon proxy index_folder must succeed, got: {indexed}"
        );
        // Prove the DAEMON holds the index and the edit below runs on the daemon
        // dispatch path, not a front-end local fallback (which would also route
        // because THIS process registered the hook via `new_daemon_proxy`). An
        // empty front-end index means the daemon executed the edit.
        assert_eq!(
            server.index().data_plane().published_state().file_count,
            0,
            "front-end proxy index must be empty — the daemon must serve the edit"
        );

        // (1) Routed apply: working_directory = the real worktree. The write
        // must land in the WORKTREE copy and leave the indexed root untouched.
        let routed = server
            .symforge_edit_facade_tool(Parameters(crate::stel::StelEditRequest {
                path: "src/lib.rs".to_string(),
                symbol: Some("wt_edit".to_string()),
                body: Some("pub fn wt_edit() -> u32 { 2 }".to_string()),
                apply: Some(true),
                working_directory: Some(worktree_root.display().to_string()),
                ..Default::default()
            }))
            .await
            .expect("symforge_edit dispatch");
        let routed_body =
            serde_json::to_value(&routed).expect("serialize routed result")["content"][0]["text"]
                .as_str()
                .expect("routed result text")
                .to_string();

        assert!(
            routed_body.contains("rerouted: true"),
            "worktree apply must report rerouted: true through the daemon path, got:\n{routed_body}"
        );
        let worktree_after = std::fs::read_to_string(&worktree_file).expect("read worktree file");
        assert!(
            worktree_after.contains("{ 2 }"),
            "worktree copy must receive the routed edit, got:\n{worktree_after}\n\nbody:\n{routed_body}"
        );
        let main_after = std::fs::read_to_string(&main_file).expect("read main file");
        assert!(
            main_after.contains("{ 1 }") && !main_after.contains("{ 2 }"),
            "indexed root must NOT be contaminated by a routed worktree edit, got:\n{main_after}\n\nbody:\n{routed_body}"
        );

        // (2) A working_directory that is not a recognized worktree must error
        // loudly (not silently write to the indexed root).
        let stray = TempDir::new().expect("stray dir");
        let stray_result = server
            .symforge_edit_facade_tool(Parameters(crate::stel::StelEditRequest {
                path: "src/lib.rs".to_string(),
                symbol: Some("wt_edit".to_string()),
                body: Some("pub fn wt_edit() -> u32 { 9 }".to_string()),
                apply: Some(true),
                working_directory: Some(stray.path().display().to_string()),
                ..Default::default()
            }))
            .await
            .expect("symforge_edit dispatch");
        let stray_body = serde_json::to_value(&stray_result).expect("serialize stray result")
            ["content"][0]["text"]
            .as_str()
            .expect("stray result text")
            .to_string();
        assert!(
            stray_body.contains("WorkingDirectoryNotARecognizedWorktree"),
            "a non-worktree working_directory must error loudly, got:\n{stray_body}"
        );
        let main_after_stray = std::fs::read_to_string(&main_file).expect("read main after stray");
        assert!(
            main_after_stray.contains("{ 1 }") && !main_after_stray.contains("{ 9 }"),
            "a rejected non-worktree edit must not write to the indexed root, got:\n{main_after_stray}\n\nbody:\n{stray_body}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// F6 root-cause guard: drive `edit_within_symbol` DIRECTLY against the
    /// daemon's HTTP tool endpoint (the exact route the front-end proxy POSTs
    /// to) with NO front-end `SymForgeServer` constructed in this test. That
    /// isolation matters because the edit-hook registry is PROCESS-GLOBAL and
    /// order-sensitive: the daemon registers BOTH `WorktreeAwareEditHook`
    /// (via `SymForgeServer::new`) and the observer-only `FrecencyBumpHook`
    /// (via `LiveIndex::load`), and the field bug was `edit_hooks::resolve`
    /// picking only the LAST-registered hook — so when frecency registered
    /// after the worktree hook, its default (no-op) `resolve_target_path`
    /// shadowed worktree routing and every `working_directory` edit
    /// contaminated the indexed root. This test indexes through the daemon
    /// (registering frecency) so the resolve order matches production, then
    /// asserts routing still holds.
    #[tokio::test]
    async fn test_daemon_http_edit_within_routes_into_worktree_without_frontend_server() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _home_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let project = project_dir("symforge-wt-http-main");
        let main_root = project.path().to_path_buf();
        let main_file = main_root.join("src").join("lib.rs");
        std::fs::write(&main_file, "pub fn wt_edit() -> u32 { 1 }\n").expect("write source");
        let git = |args: &[&str]| {
            let out = crate::process_util::hidden_command("git")
                .current_dir(&main_root)
                .args(args)
                .output()
                .unwrap_or_else(|e| panic!("git {args:?} spawn: {e}"));
            assert!(
                out.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&out.stderr)
            );
        };
        git(&["init", "-b", "main"]);
        git(&["config", "user.email", "t@t.test"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["add", "-A"]);
        git(&["commit", "-q", "-m", "init"]);

        let wt_parent = TempDir::new().expect("worktree parent");
        let worktree_root = wt_parent.path().join("wt_one");
        git(&[
            "worktree",
            "add",
            worktree_root.to_str().expect("utf-8 worktree path"),
            "-b",
            "feature",
        ]);
        let worktree_file = worktree_root.join("src").join("lib.rs");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: main_root.display().to_string(),
                client_name: "wt-http".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");
        let session_id = opened.session_id;

        // Raw HTTP tool call to the daemon — the same route `call_tool_value`
        // uses. No `SymForgeServer` exists in this test process.
        let call_tool = |tool: &str, params: serde_json::Value| {
            let url = format!("{base_url}/v1/sessions/{session_id}/tools/{tool}");
            let http = http.clone();
            async move {
                http.post(url)
                    .json(&params)
                    .send()
                    .await
                    .expect("tool request")
                    .error_for_status()
                    .expect("tool status")
                    .text()
                    .await
                    .expect("tool body")
            }
        };

        let indexed = call_tool(
            "index_folder",
            serde_json::json!({ "path": main_root.display().to_string() }),
        )
        .await;
        assert!(
            indexed.starts_with("Indexed "),
            "daemon index_folder must succeed, got: {indexed}"
        );

        // (1) Routed edit through the daemon HTTP endpoint.
        let routed = call_tool(
            "edit_within_symbol",
            serde_json::json!({
                "path": "src/lib.rs",
                "name": "wt_edit",
                "old_text": "{ 1 }",
                "new_text": "{ 2 }",
                "working_directory": worktree_root.display().to_string(),
            }),
        )
        .await;
        assert!(
            routed.contains("rerouted: true"),
            "daemon must route the worktree edit (rerouted: true), got:\n{routed}"
        );
        let worktree_after = std::fs::read_to_string(&worktree_file).expect("read worktree file");
        assert!(
            worktree_after.contains("{ 2 }"),
            "worktree copy must receive the routed edit, got:\n{worktree_after}\n\nresp:\n{routed}"
        );
        let main_after = std::fs::read_to_string(&main_file).expect("read main file");
        assert!(
            main_after.contains("{ 1 }") && !main_after.contains("{ 2 }"),
            "indexed root must NOT be contaminated by a routed worktree edit, got:\n{main_after}\n\nresp:\n{routed}"
        );

        // (2) Non-worktree working_directory must error loudly, not write to root.
        let stray = TempDir::new().expect("stray dir");
        let stray_resp = call_tool(
            "edit_within_symbol",
            serde_json::json!({
                "path": "src/lib.rs",
                "name": "wt_edit",
                "old_text": "{ 1 }",
                "new_text": "{ 9 }",
                "working_directory": stray.path().display().to_string(),
            }),
        )
        .await;
        assert!(
            stray_resp.contains("WorkingDirectoryNotARecognizedWorktree"),
            "a non-worktree working_directory must error loudly, got:\n{stray_resp}"
        );
        let main_after_stray = std::fs::read_to_string(&main_file).expect("read main after stray");
        assert!(
            main_after_stray.contains("{ 1 }") && !main_after_stray.contains("{ 9 }"),
            "a rejected non-worktree edit must not write to the indexed root, got:\n{main_after_stray}\n\nresp:\n{stray_resp}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    /// Regression: a daemon-proxy `index_folder` switch must invalidate any
    /// stale in-process index that a prior local fallback populated for the OLD
    /// project. Without the fix, the server keeps serving the old project from
    /// every tool that falls back to local execution (search_symbols,
    /// search_text, get_file_context, conventions, explore), silently mixing
    /// two projects in one session while health/get_repo_map/index_folder
    /// follow the switch.
    #[tokio::test]
    async fn test_index_folder_proxy_open_preserves_local_home_fallback() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-proxy-stale-a");
        let project_b = project_dir("symforge-proxy-stale-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        // Open a daemon session bound to project A.
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "regression".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        // Build a daemon-proxy SymForgeServer for that session — the exact shape
        // `run_remote_mcp_server_async` constructs for a real MCP client.
        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project_a.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        // Simulate a prior local-fallback load: the in-process index already
        // holds OLD-project (project A) state.
        server.index.data_plane().add_file(
            "src/old.rs".to_string(),
            crate::live_index::store::IndexedFile {
                relative_path: "src/old.rs".to_string(),
                language: crate::domain::index::LanguageId::Rust,
                classification: crate::domain::FileClassification::for_code_path("src/old.rs"),
                content: b"fn old_fn() {}".to_vec(),
                symbols: vec![],
                parse_status: crate::live_index::store::ParseStatus::Parsed,
                parse_diagnostic: None,
                byte_len: 14,
                content_hash: "old-hash".to_string(),
                references: vec![],
                alias_map: std::collections::HashMap::new(),
                mtime_secs: 0,
            },
        );
        assert_eq!(
            server.index.data_plane().published_state().file_count,
            1,
            "precondition: stale local index holds the OLD project"
        );

        // Open project B via the proxy path. This must not change the immutable
        // home binding or invalidate its local fallback state.
        let result = server
            .index_folder(Parameters(IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            result.starts_with("Indexed "),
            "daemon proxy index_folder should report success, got: {result}"
        );

        // The immutable-home contract keeps the existing local fallback for A.
        assert_eq!(
            server.index.data_plane().published_state().file_count,
            1,
            "opening B must not reset the local home-A fallback, got: {result}"
        );
        assert!(
            server
                .index
                .data_plane()
                .read()
                .get_file("src/old.rs")
                .is_some(),
            "home-A fallback must remain reachable after opening B"
        );

        let home_root = server.capture_repo_root().expect("home root after open");
        assert_eq!(
            home_root,
            project_a.path().to_path_buf(),
            "repo_root must remain bound to immutable home A"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_index_folder_proxy_failure_refuses_destructive_local_fallback() {
        let project_a = project_dir("symforge-proxy-refusal-a");
        let project_b = project_dir("symforge-proxy-refusal-b");
        std::fs::write(
            project_a.path().join("src").join("home.rs"),
            "fn home() {}\n",
        )
        .expect("write home source");
        std::fs::write(
            project_b.path().join("src").join("other.rs"),
            "fn other() {}\n",
        )
        .expect("write other source");

        let home_root = canonical_project_root(project_a.path()).expect("canonical home A");
        // Hermetic unreachable endpoint: bind an ephemeral port, then release it.
        // Nothing is listening there afterwards, so the proxy call fails fast and
        // deterministically — no assumption that a fixed port (e.g. 1) is free.
        let dead_port = {
            let listener =
                std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral probe port");
            listener.local_addr().expect("probe port local addr").port()
        };
        let daemon_home = TempDir::new().expect("isolated daemon control state");
        let client = DaemonSessionClient::new_for_test_at(
            format!("http://127.0.0.1:{dead_port}"),
            project_key(&home_root),
            "unreachable-session".to_string(),
            "home-a".to_string(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(home_root.clone());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);
        // Mark the daemon connection as already degraded so `proxy_tool_call`
        // fails over immediately instead of entering the reconnect path, which
        // would try to discover or SPAWN a real daemon — the opposite of a
        // hermetic unit test.
        {
            let mut state = server.daemon_degraded.lock();
            state.degraded = true;
            state.last_reconnect_attempt = Some(std::time::Instant::now());
        }
        server
            .index
            .data_plane()
            .reload(&home_root)
            .expect("seed local home fallback");

        let output = server
            .index_folder(Parameters(IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            output.contains("daemon") && output.contains("refus"),
            "daemon-proxy failure must refuse destructive local index_folder: {output}"
        );
        assert_eq!(
            server.capture_repo_root().as_deref(),
            Some(home_root.as_path()),
            "failed proxy open must keep home root"
        );
        let guard = server.index.data_plane().read();
        assert!(guard.get_file("src/home.rs").is_some());
        assert!(
            guard.get_file("src/other.rs").is_none(),
            "failed proxy open must not replace home index with B"
        );
    }

    /// Opening another project must not move connection-scoped surfaces away
    /// from the immutable home project.
    #[tokio::test]
    async fn test_index_folder_activation_keeps_status_home_but_routes_facade_to_active_project() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        // The facade surfaces require the compact profile.
        let _surface_guard = EnvVarGuard::set_str("SYMFORGE_SURFACE", "compact");

        let project_a = project_dir("symforge-retarget-root-a");
        let project_b = project_dir("symforge-retarget-root-b");
        std::fs::write(
            project_a.path().join("src").join("lib.rs"),
            "pub fn alpha_symbol() -> u32 { 1 }\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("lib.rs"),
            "pub fn beta_symbol() -> u32 { 2 }\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let http = authed_client(&handle);

        // Open a daemon session bound to project A.
        let opened = http
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "retarget-root".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let client = DaemonSessionClient::new_for_test_at(
            base_url.clone(),
            opened.project_id.clone(),
            opened.session_id.clone(),
            opened.project_name.clone(),
            test_control_state(daemon_home.path()),
        )
        .with_project_root(project_a.path().to_path_buf());
        let server = crate::protocol::SymForgeServer::new_daemon_proxy(client);

        // Sanity: before retarget the bound root is project A and the local
        // status render surfaces it.
        let root_a_norm = project_a.path().display().to_string().replace('\\', "/");
        let status_before =
            server.render_stel_status_body(&crate::stel::StelStatusRequest::default());
        assert!(
            status_before.contains(&format!("project_root: {root_a_norm}")),
            "pre-retarget status must surface project A root, got:\n{status_before}"
        );

        // Open project B via the explicit `index_folder` verb.
        let indexed = server
            .index_folder(Parameters(IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(
            indexed.starts_with("Indexed "),
            "daemon proxy open must succeed, got: {indexed}"
        );

        // (a) The bound root remains the connection's home A.
        let bound = server.capture_repo_root().expect("repo root after open");
        assert_eq!(
            bound,
            project_a.path().to_path_buf(),
            "repo_root must remain at immutable home A after opening B"
        );

        // (b) `status` (local render path) still reflects home A.
        let root_b_norm = project_b.path().display().to_string().replace('\\', "/");
        let root_b_canonical = project_b
            .path()
            .canonicalize()
            .expect("canonical project B root");
        let root_b_receipt = dunce::simplified(&root_b_canonical)
            .display()
            .to_string()
            .replace('\\', "/");
        let status_after =
            server.render_stel_status_body(&crate::stel::StelStatusRequest::default());
        assert!(
            status_after.contains(&format!("project_root: {root_a_norm}")),
            "post-open status must preserve home A root, got:\n{status_after}"
        );
        assert!(
            !status_after.contains(&format!("project_root: {root_b_norm}")),
            "opened B must not replace home A in status, got:\n{status_after}"
        );

        // The adapter-private route pin is what lets selector-less tools keep
        // the ACTIVE snapshot they captured before dispatch. Prove the daemon
        // consumes it as a real target selector by routing `conventions` back
        // to home A while session ACTIVE remains B.
        let direct_client = server
            .daemon_client_slot()
            .expect("daemon client slot")
            .read()
            .await
            .clone();
        let mut private_home_args = serde_json::json!({});
        private_home_args
            .as_object_mut()
            .expect("private route args")
            .insert(
                PRIVATE_PROJECT_ROUTE_PIN.to_string(),
                serde_json::Value::String(opened.project_id.clone()),
            );
        let private_home_evidence =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let body = direct_client
                    .call_tool_value("conventions", private_home_args)
                    .await
                    .expect("private-pinned conventions response");
                assert!(body.contains("Project Conventions"), "{body}");
                crate::protocol::result_status::current_project_evidence()
            })
            .await
            .expect("private-pinned call must carry project evidence");
        assert_eq!(private_home_evidence.project_id, opened.project_id);
        let root_a_canonical = project_a
            .path()
            .canonicalize()
            .expect("canonical project A root");
        let root_a_receipt = dunce::simplified(&root_a_canonical)
            .display()
            .to_string()
            .replace('\\', "/");
        assert_eq!(
            private_home_evidence.canonical_root.as_deref(),
            Some(root_a_receipt.as_str()),
            "the private route pin must override mutable daemon ACTIVE"
        );

        // (c) unqualified facade calls follow the daemon session's ACTIVE
        // project. Adapter-local status remains home-scoped, but the served
        // body, facade root line, and typed receipt must all describe B.
        // `SymforgeCallInput` flattens the `StelRequest`, so `query` is top-level.
        let symforge_input = serde_json::from_value(serde_json::json!({
            "query": "find beta_symbol"
        }))
        .expect("symforge facade input");
        let symforge_result =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let mut result = server
                    .symforge_facade_tool(Parameters(symforge_input))
                    .await?;
                crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
                Ok::<_, rmcp::ErrorData>(result)
            })
            .await
            .expect("symforge facade dispatch");
        let serialized = serde_json::to_value(&symforge_result).expect("serialize symforge result");
        let symforge_body = serialized["content"][0]["text"]
            .as_str()
            .expect("symforge result text")
            .to_string();
        assert!(
            symforge_body.contains("beta_symbol"),
            "unqualified facade body must be served from active project B, got:\n{symforge_body}"
        );
        assert!(
            !symforge_body.contains("alpha_symbol"),
            "unqualified facade body must not mix home project A, got:\n{symforge_body}"
        );
        assert!(
            symforge_body.contains(&format!("project_root: {root_b_receipt}")),
            "unqualified facade root line must name active project B, got:\n{symforge_body}"
        );
        assert!(
            !symforge_body.contains(&format!("project_root: {root_a_norm}")),
            "unqualified facade root line must not name home project A, got:\n{symforge_body}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"]["canonical_root"], root_b_receipt,
            "typed facade evidence must name the active daemon project: {serialized}"
        );

        // Pin an explicit B selector and choose a path that would resolve inside
        // HOME A but outside selected B. This makes the adapter preflight
        // mutation-sensitive: validating against A, skipping the guard, or
        // relying only on the downstream primitive cannot produce the required
        // selected-B-root refusal text.
        let project_a_name = project_a
            .path()
            .file_name()
            .and_then(|name| name.to_str())
            .expect("project A basename");
        let a_inside_b_escape = format!("../{project_a_name}/src/lib.rs");
        let escaped_input = crate::stel::SymforgeCallInput {
            request: crate::stel::StelRequest {
                query: "read the selected file".to_string(),
                intent: Some(crate::stel::IntentBucket::Read),
                path: Some(a_inside_b_escape),
                project: Some(project_key(&root_b_canonical)),
                ..Default::default()
            },
            ..Default::default()
        };
        let escaped_result =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let mut result = server
                    .symforge_facade_tool(Parameters(escaped_input))
                    .await?;
                crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
                Ok::<_, rmcp::ErrorData>(result)
            })
            .await
            .expect("active-project path containment result");
        let escaped = serde_json::to_value(&escaped_result).expect("serialize path refusal");
        let escaped_body = escaped["content"][0]["text"]
            .as_str()
            .expect("path refusal text");
        assert_eq!(
            escaped["_meta"]["symforge/result_status"]["outcome_class"], "invalid_request",
            "the selected primitive must type the containment refusal: {escaped}"
        );
        assert!(
            escaped_body.contains("Path is outside the repository root")
                && escaped_body.contains(&format!("The selected project root is {root_b_receipt}")),
            "the active daemon project must reject a path escape: {escaped_body}"
        );
        assert!(
            !escaped_body.contains(&root_a_norm)
                && !escaped_body.contains("alpha_symbol")
                && !escaped_body.contains("beta_symbol"),
            "a rejected path must not serve source from either project: {escaped_body}"
        );

        // Real daemon routing refusals must retain a shared error prefix so a
        // direct public wrapper cannot classify a headerless refusal as Found.
        let unknown_input: GetFileContentInput = serde_json::from_value(serde_json::json!({
            "path": "src/lib.rs",
            "project": "not-an-open-project",
        }))
        .expect("unknown-project file input");
        let unknown_result = server
            .get_file_content_tool(Parameters(unknown_input))
            .await
            .expect("unknown-project file result");
        let unknown = serde_json::to_value(unknown_result).expect("serialize routing refusal");
        assert_eq!(
            unknown["_meta"]["symforge/result_status"]["outcome_class"], "invalid_request",
            "a daemon routing refusal must never look Found: {unknown}"
        );
        assert!(
            unknown["content"][0]["text"]
                .as_str()
                .is_some_and(|text| text.starts_with("Error: project_routing:")),
            "daemon routing refusal must use the shared error prefix: {unknown}"
        );

        // The daemon HTTP route is independently callable. A structural edit
        // must not drop a malformed/set-valued selector and mutate ACTIVE B.
        let edit_url = format!(
            "{base_url}/v1/sessions/{}/tools/edit_within_symbol",
            opened.session_id
        );
        for projects in [
            serde_json::json!([project_key(&root_b_canonical)]),
            serde_json::json!([project_key(&root_b_canonical), 7]),
        ] {
            let refused = http
                .post(&edit_url)
                .json(&serde_json::json!({
                    "path": "src/lib.rs",
                    "name": "beta_symbol",
                    "old_text": "{ 2 }",
                    "new_text": "{ 9 }",
                    "projects": projects,
                }))
                .send()
                .await
                .expect("malformed edit selector request")
                .error_for_status()
                .expect("malformed edit selector status")
                .text()
                .await
                .expect("malformed edit selector body");
            assert!(
                refused.starts_with("Error: project_routing:"),
                "unsupported/malformed edit selectors must refuse before dispatch: {refused}"
            );
        }
        assert_eq!(
            std::fs::read_to_string(project_b.path().join("src").join("lib.rs"))
                .expect("read B after refused edits"),
            "pub fn beta_symbol() -> u32 { 2 }\n",
            "a rejected set-valued edit must leave ACTIVE B byte-identical"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn test_index_folder_idempotency_replays_same_key_same_request_in_daemon_route() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-daemon-idempotency-a");
        let project_b = project_dir("symforge-daemon-idempotency-b");
        std::fs::write(
            project_a.path().join("src").join("old.rs"),
            "fn old_fn() {}\n",
        )
        .expect("write source a");
        std::fs::write(
            project_b.path().join("src").join("new.rs"),
            "fn new_fn() {}\n",
        )
        .expect("write source b");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(56),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let tool_url = format!(
            "{base_url}/v1/sessions/{}/tools/index_folder",
            opened.session_id
        );
        let first = client
            .post(&tool_url)
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: Some("daemon-replay-key".to_string()),
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("first index request")
            .error_for_status()
            .expect("first index status")
            .text()
            .await
            .expect("first index body");
        assert!(
            first.starts_with("Indexed 1 files"),
            "first daemon idempotent index_folder should index once, got: {first}"
        );

        std::fs::write(
            project_b.path().join("src").join("second.rs"),
            "fn second_fn() {}\n",
        )
        .expect("write second source b");

        let replay = client
            .post(&tool_url)
            .json(&IndexFolderInput {
                path: project_b.path().display().to_string(),
                idempotency_key: Some("daemon-replay-key".to_string()),
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("replay index request")
            .error_for_status()
            .expect("replay index status")
            .text()
            .await
            .expect("replay index body");
        assert_eq!(
            replay, first,
            "daemon special route must replay stored output for same key and canonical request"
        );

        let conflict = client
            .post(&tool_url)
            .json(&IndexFolderInput {
                path: project_a.path().display().to_string(),
                idempotency_key: Some("daemon-replay-key".to_string()),
                add: None,
                allow_protected_root: None,
            })
            .send()
            .await
            .expect("conflict index request")
            .error_for_status()
            .expect("conflict index status")
            .text()
            .await
            .expect("conflict index body");
        assert!(
            conflict.contains("Idempotency conflict"),
            "daemon special route must reject same key with different request, got: {conflict}"
        );
        assert!(
            !conflict.starts_with("Indexed "),
            "daemon conflict must not report synthetic indexing success: {conflict}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[test]
    fn test_index_folder_additive_replays_and_conflicts() {
        let control_state_home = TempDir::new().expect("isolated idempotency control state");
        let project_a = project_dir("symforge-idempotency-home-a");
        let project_b = project_dir("symforge-idempotency-open-b");
        let project_c = project_dir("symforge-idempotency-conflict-c");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");
        std::fs::write(project_c.path().join("src").join("c.rs"), "fn c() {}\n")
            .expect("write source c");
        let state = test_daemon_state(control_state_home.path());
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "idempotency".to_string(),
                pid: None,
            })
            .expect("open home A");

        let first = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: Some("shared-open-key".to_string()),
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("default open B");
        assert!(first.contains("project_id="), "identity receipt: {first}");
        assert!(
            first.contains("checkpoint=written"),
            "checkpoint receipt: {first}"
        );

        std::fs::write(
            project_b.path().join("src").join("second.rs"),
            "fn second() {}\n",
        )
        .expect("write second source b");
        let replay = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: Some("shared-open-key".to_string()),
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("identical default replay B");
        assert_eq!(
            replay, first,
            "same key + same request (including the activation spelling) must replay"
        );

        // The `add` spelling changes observable side effects (activation), so
        // it MUST distinguish the canonical request: same key + different
        // spelling conflicts deterministically rather than silently skipping
        // activation.
        let spelling_conflict = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: Some("shared-open-key".to_string()),
                    add: Some(true),
                    allow_protected_root: None,
                },
            )
            .expect("add=true against a default-open record");
        assert!(
            spelling_conflict.contains("Idempotency conflict"),
            "same key with a different activation spelling must conflict: {spelling_conflict}"
        );

        let conflict = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_c.path().display().to_string(),
                    idempotency_key: Some("shared-open-key".to_string()),
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("conflicting open C");
        assert!(
            conflict.contains("Idempotency conflict"),
            "same key with another target must fail deterministically: {conflict}"
        );
        assert!(
            !state.projects.read().contains_key(&project_key(
                &canonical_project_root(project_c.path()).expect("canonical C")
            )),
            "conflict must be rejected before project C is loaded"
        );
    }

    #[test]
    fn test_index_folder_open_persists_snapshot_for_restore() {
        let project_a = project_dir("symforge-snapshot-home-a");
        let project_b = project_dir("symforge-snapshot-open-b");
        std::fs::write(
            project_b.path().join("src").join("restored.rs"),
            "fn restored() {}\n",
        )
        .expect("write source b");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "snapshot".to_string(),
                pid: None,
            })
            .expect("open home A");

        let receipt = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("open B");
        assert!(
            receipt.contains("checkpoint=written"),
            "successful open must expose durable checkpoint outcome: {receipt}"
        );
        assert!(
            project_b
                .path()
                .join(".symforge")
                .join("index.bin")
                .is_file(),
            "successful daemon reload must atomically persist B"
        );

        drop(state);
        let canonical_b = canonical_project_root(project_b.path()).expect("canonical B");
        let RootResolution::Bound(binding_b) = crate::discovery::resolve_root_candidate(
            &canonical_b,
            RootCandidateSource::LaunchCwd,
            RootRequestMode::Automatic,
        ) else {
            panic!("B must remain a valid automatic project root");
        };
        let placement_b = crate::discovery::resolve_state_placement(&binding_b);
        let restored = bootstrap_project_index(&canonical_b, &placement_b, &Arc::default())
            .expect("restore B from snapshot");
        {
            let guard = restored.read();
            assert_eq!(
                guard.load_source(),
                crate::live_index::store::IndexLoadSource::SnapshotRestore
            );
            assert_eq!(guard.file_count(), 1);
        }
        let snapshot =
            live_index::persist::load_snapshot(&canonical_b, &placement_b).expect("snapshot");
        let snapshot_mtimes = snapshot
            .files
            .iter()
            .map(|(path, file)| (path.clone(), file.mtime_secs))
            .collect();
        live_index::persist::block_on_background_verify_for_test(
            restored.clone(),
            &canonical_b,
            snapshot_mtimes,
        );
        let guard = restored.read();
        assert!(guard.get_file("src/restored.rs").is_some());
    }

    /// An unavailable project-local state directory must move the whole project
    /// instance to user-local state instead of retrying writes under the source.
    #[tokio::test]
    async fn test_index_folder_open_falls_back_to_user_local_when_project_state_unavailable() {
        let _env_lock = env_lock().await;
        let state_home = TempDir::new().expect("private user-local state base");
        let _home = EnvVarGuard::set("SYMFORGE_HOME", state_home.path());
        let project_a = project_dir("symforge-degraded-home-a");
        let project_b = project_dir("symforge-degraded-open-b");
        std::fs::write(project_b.path().join("src").join("b.rs"), "fn b() {}\n")
            .expect("write source b");
        // Block snapshot persistence: a FILE at `.symforge` makes the snapshot
        // directory creation fail while indexing itself is unaffected.
        std::fs::write(project_b.path().join(".symforge"), "not a directory")
            .expect("write .symforge blocker");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "state-fallback".to_string(),
                pid: None,
            })
            .expect("open home A");

        let receipt = state
            .index_folder_for_session(
                &opened.session_id,
                IndexFolderInput {
                    path: project_b.path().display().to_string(),
                    idempotency_key: None,
                    add: None,
                    allow_protected_root: None,
                },
            )
            .expect("open B must succeed through user-local fallback");
        assert!(
            receipt.starts_with("Indexed "),
            "open itself must succeed: {receipt}"
        );
        assert!(
            receipt.contains("state=user-local"),
            "project-local failure must select user-local state: {receipt}"
        );
        assert!(
            receipt.contains("checkpoint=written"),
            "user-local placement must checkpoint through its resolved state directory: {receipt}"
        );

        // The in-memory open stayed published: B is attached to the working
        // set, and the default spelling ACTIVATED B (locked contract) while
        // home A stays in the working set.
        let project_b_id =
            project_key(&canonical_project_root(project_b.path()).expect("canonical b"));
        let sessions = state.sessions.read();
        let session = sessions.get(&opened.session_id).expect("session");
        assert_eq!(
            session.active_project_id, project_b_id,
            "default open must activate B"
        );
        assert!(
            session.working_set.read().get(&opened.project_id).is_some(),
            "home A must stay in the working set"
        );
        assert!(
            session.working_set.read().get(&project_b_id).is_some(),
            "B must be attached despite project-local state being unavailable"
        );
        assert!(
            state_home
                .path()
                .join("projects")
                .join(&project_b_id)
                .is_dir(),
            "fallback state must be prepared under the private user-local project directory"
        );
        assert!(
            state_home
                .path()
                .join("projects")
                .join(&project_b_id)
                .join("index.bin")
                .is_file(),
            "user-local checkpoint must be written under the resolved project state directory"
        );
        // The source blocker remains untouched: fallback never tries to repair
        // or replace source-root state behind the user's back.
        assert!(
            project_b.path().join(".symforge").is_file(),
            "the blocking file must remain in place (no destructive recovery)"
        );
    }

    #[tokio::test]
    async fn test_analyze_file_impact_uses_session_project_root_not_process_cwd() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project = project_dir("symforge-daemon-impact-root");
        let outside = TempDir::new().expect("outside cwd");
        let source_path = project.path().join("src").join("lib.rs");
        std::fs::write(&source_path, "pub fn old_name() {}\n").expect("write initial source");

        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);

        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "codex".to_string(),
                pid: Some(4242),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let before_response = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/health",
                opened.session_id
            ))
            .json(&serde_json::json!({}))
            .send()
            .await
            .expect("pre-impact health request")
            .error_for_status()
            .expect("pre-impact health status");
        let before_evidence: crate::protocol::result_status::ProjectEvidence =
            serde_json::from_slice(
                before_response
                    .headers()
                    .get(crate::protocol::result_status::PROJECT_EVIDENCE_HEADER)
                    .expect("pre-impact evidence header")
                    .as_bytes(),
            )
            .expect("decode pre-impact evidence");
        let _ = before_response
            .text()
            .await
            .expect("pre-impact health body");

        std::fs::write(&source_path, "pub fn new_name() {}\n").expect("write updated source");

        let _cwd_guard = CwdGuard::set(outside.path());

        let impact_response = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/analyze_file_impact",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "path": "src/lib.rs"
            }))
            .send()
            .await
            .expect("impact request")
            .error_for_status()
            .expect("impact status");
        let impact_evidence: crate::protocol::result_status::ProjectEvidence =
            serde_json::from_slice(
                impact_response
                    .headers()
                    .get(crate::protocol::result_status::PROJECT_EVIDENCE_HEADER)
                    .expect("impact evidence header")
                    .as_bytes(),
            )
            .expect("decode impact evidence");
        let impact = impact_response.text().await.expect("impact body");

        assert!(
            impact.contains("new_name"),
            "impact analysis should read from the session project root, got: {impact}"
        );
        assert!(
            impact_evidence.generation > before_evidence.generation,
            "the daemon receipt must come from the publication rendered by impact: before={before_evidence:?}, impact={impact_evidence:?}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    #[tokio::test]
    async fn direct_daemon_rejects_unsupported_selectors_before_project_mutation() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());
        let project_a = project_dir("symforge-daemon-selector-a");
        let project_b = project_dir("symforge-daemon-selector-b");
        let handle = spawn_test_daemon("127.0.0.1", daemon_home.path())
            .await
            .expect("spawn daemon");
        let client = authed_client(&handle);
        let base_url = format!("http://127.0.0.1:{}", handle.port);
        let opened = client
            .post(format!("{base_url}/v1/sessions/open"))
            .json(&OpenProjectRequest {
                project_root: project_a.path().display().to_string(),
                client_name: "selector-guard".to_string(),
                pid: Some(std::process::id()),
            })
            .send()
            .await
            .expect("open request")
            .error_for_status()
            .expect("open status")
            .json::<OpenProjectResponse>()
            .await
            .expect("open body");

        let illegal_open = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/index_folder",
                opened.session_id
            ))
            .json(&serde_json::json!({
                "path": project_b.path().display().to_string(),
                "project": opened.project_id.clone(),
            }))
            .send()
            .await
            .expect("selector-bearing index request")
            .error_for_status()
            .expect("selector-bearing index status")
            .text()
            .await
            .expect("selector-bearing index body");
        assert!(
            illegal_open.starts_with("Error: project_routing:"),
            "index_folder must reject selectors before opening or activating: {illegal_open}"
        );

        let inventory = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/status",
                opened.session_id
            ))
            .json(&serde_json::json!({"detail": "projects"}))
            .send()
            .await
            .expect("project inventory request")
            .error_for_status()
            .expect("project inventory status")
            .text()
            .await
            .expect("project inventory body");
        let project_b_id = project_key(
            &project_b
                .path()
                .canonicalize()
                .expect("canonical project B root"),
        );
        assert!(
            !inventory.contains(&project_b_id),
            "rejected index_folder must leave project B unopened: {inventory}"
        );

        let illegal_checkpoint = client
            .post(format!(
                "{base_url}/v1/sessions/{}/tools/checkpoint_now",
                opened.session_id
            ))
            .json(&serde_json::json!({"project": project_b_id}))
            .send()
            .await
            .expect("selector-bearing checkpoint request")
            .error_for_status()
            .expect("selector-bearing checkpoint status")
            .text()
            .await
            .expect("selector-bearing checkpoint body");
        assert!(
            illegal_checkpoint.starts_with("Error: project_routing:"),
            "checkpoint_now must refuse an unsupported scalar selector: {illegal_checkpoint}"
        );

        let _ = handle.shutdown_tx.send(());
        wait_for_path_absent(&test_daemon_path(
            daemon_home.path(),
            LEGACY_DAEMON_PORT_FILE,
        ))
        .await;
    }

    // -----------------------------------------------------------------
    // C6: concurrent open_project_session tests
    // -----------------------------------------------------------------

    #[test]
    fn test_concurrent_open_same_project_no_panic() {
        use std::sync::{Arc, Barrier};

        let project = project_dir("symforge-conc-same");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");
        let project_root = project.path().display().to_string();

        let state = Arc::new(DaemonState::new());
        let barrier = Arc::new(Barrier::new(2));

        let handles: Vec<_> = (0..2)
            .map(|i| {
                let state = Arc::clone(&state);
                let barrier = Arc::clone(&barrier);
                let root = project_root.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    state.open_project_session(OpenProjectRequest {
                        project_root: root,
                        client_name: format!("client-{i}"),
                        pid: None,
                    })
                })
            })
            .collect();

        for handle in handles {
            handle
                .join()
                .expect("thread panicked")
                .expect("open_project_session failed");
        }

        let projects = state.list_projects();
        assert_eq!(projects.len(), 1, "exactly 1 project instance expected");
        assert_eq!(
            state.health().session_count,
            2,
            "exactly 2 sessions expected"
        );

        let project_id = &projects[0].project_id;
        let projects_lock = state.projects.read();
        let slot = projects_lock.get(project_id).expect("project must exist");
        let instance = slot.metadata.read();
        assert_eq!(
            instance.activation_state,
            ActivationState::Active,
            "project must be Active after concurrent opens"
        );
    }

    #[test]
    fn test_concurrent_open_different_projects() {
        use std::sync::{Arc, Barrier};

        let project_a = project_dir("symforge-conc-diff-a");
        std::fs::write(
            project_a.path().join("src").join("main.rs"),
            "fn main() {}\n",
        )
        .expect("write source a");
        let project_b = project_dir("symforge-conc-diff-b");
        std::fs::write(
            project_b.path().join("src").join("main.rs"),
            "fn main() {}\n",
        )
        .expect("write source b");

        let root_a = project_a.path().display().to_string();
        let root_b = project_b.path().display().to_string();

        let state = Arc::new(DaemonState::new());
        let barrier = Arc::new(Barrier::new(2));

        let roots = [root_a, root_b];
        let handles: Vec<_> = roots
            .iter()
            .enumerate()
            .map(|(i, root)| {
                let state = Arc::clone(&state);
                let barrier = Arc::clone(&barrier);
                let root = root.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    state.open_project_session(OpenProjectRequest {
                        project_root: root,
                        client_name: format!("client-{i}"),
                        pid: None,
                    })
                })
            })
            .collect();

        let responses: Vec<_> = handles
            .into_iter()
            .map(|h| h.join().expect("thread panicked").expect("open failed"))
            .collect();

        assert_ne!(
            responses[0].project_id, responses[1].project_id,
            "two distinct projects expected"
        );
        assert_eq!(
            state.list_projects().len(),
            2,
            "exactly 2 project instances expected"
        );
    }

    #[test]
    fn test_open_close_race_no_panic() {
        use std::sync::{Arc, Barrier};

        let project = project_dir("symforge-conc-race");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");
        let project_root = project.path().display().to_string();

        let state = Arc::new(DaemonState::new());

        // Open a first session before the race.
        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project_root.clone(),
                client_name: "racer-first".to_string(),
                pid: None,
            })
            .expect("first session");
        let first_session_id = first.session_id.clone();

        let barrier = Arc::new(Barrier::new(2));

        // Thread A: opens another session concurrently.
        let state_a = Arc::clone(&state);
        let barrier_a = Arc::clone(&barrier);
        let root_a = project_root.clone();
        let open_handle = std::thread::spawn(move || {
            barrier_a.wait();
            state_a.open_project_session(OpenProjectRequest {
                project_root: root_a,
                client_name: "racer-open".to_string(),
                pid: None,
            })
        });

        // Thread B: closes the first session concurrently.
        let state_b = Arc::clone(&state);
        let barrier_b = Arc::clone(&barrier);
        let close_handle = std::thread::spawn(move || {
            barrier_b.wait();
            state_b.close_session(&first_session_id)
        });

        // Both must return Ok / Some — not panic.
        open_handle
            .join()
            .expect("open thread panicked")
            .expect("open failed");
        close_handle.join().expect("close thread panicked");
        // (close_session returns Option — None is acceptable if session was already gone)
    }

    #[test]
    fn test_discarded_instance_no_leaked_tasks() {
        use std::sync::{Arc, Barrier};

        let project = project_dir("symforge-conc-3way");
        std::fs::write(project.path().join("src").join("main.rs"), "fn main() {}\n")
            .expect("write source");
        let project_root = project.path().display().to_string();

        let state = Arc::new(DaemonState::new());
        let barrier = Arc::new(Barrier::new(3));

        let handles: Vec<_> = (0..3)
            .map(|i| {
                let state = Arc::clone(&state);
                let barrier = Arc::clone(&barrier);
                let root = project_root.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    state.open_project_session(OpenProjectRequest {
                        project_root: root,
                        client_name: format!("racer-{i}"),
                        pid: None,
                    })
                })
            })
            .collect();

        for handle in handles {
            handle
                .join()
                .expect("thread panicked")
                .expect("open_project_session failed");
        }

        let projects = state.list_projects();
        assert_eq!(projects.len(), 1, "exactly 1 project instance expected");
        assert_eq!(
            state.health().session_count,
            3,
            "exactly 3 sessions expected"
        );

        let project_id = &projects[0].project_id;
        let projects_lock = state.projects.read();
        let slot = projects_lock.get(project_id).expect("project must exist");
        let instance = slot.metadata.read();

        assert_eq!(
            instance.activation_state,
            ActivationState::Active,
            "project must be Active"
        );
        // watcher_task is None in sync tests (no Tokio runtime for try_current()),
        // but activation_state == Active proves activate() ran exactly once and
        // no extra ProjectInstance was left alive from discarded racers.
        // The session_count == 3 proves all 3 callers got a valid session back.
    }

    #[tokio::test]
    async fn test_stale_start_lock_is_removed() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let lock_path = test_daemon_path(daemon_home.path(), daemon_start_lock_file_name());

        // Create a lock file and backdate it to 60 seconds ago.
        let file = std::fs::File::create(&lock_path).expect("create lock");
        let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
        let times = std::fs::FileTimes::new().set_modified(old_time);
        file.set_times(times).expect("set file times");
        drop(file);

        // try_acquire_start_lock should detect the stale lock and succeed.
        let result = try_acquire_start_lock_at(&test_control_state(daemon_home.path()))
            .expect("should not error");
        assert!(
            result.is_some(),
            "stale lock (>30s old) should be removed and lock acquired"
        );

        // Clean up — the DaemonStartLock Drop impl removes the file.
        drop(result);
    }

    #[tokio::test]
    async fn test_fresh_start_lock_blocks_acquisition() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let lock_path = test_daemon_path(daemon_home.path(), daemon_start_lock_file_name());

        // Create a fresh lock file (just now — well within 30s threshold).
        std::fs::write(&lock_path, "").expect("create lock");

        // try_acquire_start_lock should see the fresh lock and return None.
        let result = try_acquire_start_lock_at(&test_control_state(daemon_home.path()))
            .expect("should not error");
        assert!(
            result.is_none(),
            "fresh lock (<30s old) should block acquisition"
        );

        // Clean up.
        let _ = std::fs::remove_file(&lock_path);
    }

    #[tokio::test]
    async fn test_cleanup_daemon_files_removes_start_lock() {
        let _env_lock = env_lock().await;
        // Verify that cleanup_daemon_files removes the start lock file
        // alongside port and pid files. We test the function signature
        // and that it doesn't panic — actual file removal is best-effort.
        let dir = TempDir::new().expect("temp dir");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", dir.path());
        let port_file = test_daemon_path(dir.path(), LEGACY_DAEMON_PORT_FILE);
        let pid_file = test_daemon_path(dir.path(), LEGACY_DAEMON_PID_FILE);
        let lock_file = test_daemon_path(dir.path(), LEGACY_DAEMON_START_LOCK_FILE);

        std::fs::write(&port_file, "12345").expect("write port");
        std::fs::write(&pid_file, "99999").expect("write pid");
        std::fs::write(&lock_file, "").expect("write lock");

        cleanup_daemon_files_at(&test_control_state(dir.path()));

        assert!(!port_file.exists(), "cleanup removes port file");
        assert!(!pid_file.exists(), "cleanup removes pid file");
        assert!(!lock_file.exists(), "cleanup removes start lock file");
    }

    #[tokio::test]
    async fn test_runtime_cleanup_preserves_start_lock() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        let port_file = test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE);
        let pid_file = test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PID_FILE);
        let lock_file = test_daemon_path(daemon_home.path(), LEGACY_DAEMON_START_LOCK_FILE);

        std::fs::write(&port_file, "12345").expect("write port");
        std::fs::write(&pid_file, "99999").expect("write pid");
        std::fs::write(&lock_file, "").expect("write lock");

        cleanup_daemon_runtime_files_at(&test_control_state(daemon_home.path()));

        assert!(!port_file.exists(), "runtime cleanup removes port file");
        assert!(!pid_file.exists(), "runtime cleanup removes pid file");
        assert!(
            lock_file.exists(),
            "runtime cleanup must not release another process' start lock"
        );
    }

    #[tokio::test]
    async fn test_corrupt_port_file_does_not_block_daemon_selection() {
        let _env_lock = env_lock().await;
        let daemon_home = TempDir::new().expect("daemon home");
        let _env_guard = EnvVarGuard::set("SYMFORGE_HOME", daemon_home.path());

        std::fs::write(
            test_daemon_path(daemon_home.path(), LEGACY_DAEMON_PORT_FILE),
            "not-a-port",
        )
        .expect("write corrupt port");

        let identity = current_daemon_identity();
        let selected =
            daemon_port_if_compatible_at(&test_control_state(daemon_home.path()), &identity)
                .await
                .expect("corrupt port should be ignored, not fatal");

        assert_eq!(selected, None);
    }

    fn session_open_placement(root: &Path) -> StatePlacement {
        crate::discovery::resolve_state_placement(&RootBinding {
            source: RootCandidateSource::InitCwd,
            canonical_root: root.to_path_buf(),
            root_id: crate::discovery::project_id_for_canonical_root(root),
            access_mode: SourceAccessMode::NormalProject,
        })
    }

    async fn wait_until_published(
        index: &SharedIndex,
        done: impl Fn(&crate::live_index::PublishedIndexState) -> bool,
    ) -> Arc<crate::live_index::PublishedIndexState> {
        let deadline = std::time::Instant::now() + Duration::from_secs(60);
        loop {
            let published = index.published_state();
            if done(&published) {
                return published;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "background cold load never settled: status {:?}",
                published.status
            );
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    }

    fn source_tree(files: usize) -> (TempDir, PathBuf) {
        let tmp = TempDir::new().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonical root");
        std::fs::create_dir_all(root.join("src")).expect("src dir");
        for file in 0..files {
            std::fs::write(
                root.join("src").join(format!("f{file}.rs")),
                format!("pub fn f{file}() -> u32 {{ {file} }}\n"),
            )
            .expect("write source");
        }
        (tmp, root)
    }

    fn cold_load_job(root: &Path) -> ColdLoadJob {
        ColdLoadJob {
            index: LiveIndex::empty(),
            root: root.to_path_buf(),
            placement: session_open_placement(root),
            curation_coordinator: Arc::default(),
            persistence_status: CapabilityStatus::Available,
            background: Arc::default(),
        }
    }

    /// `load`, held until the test opens the gate. Opened only after the
    /// opener stopped waiting, it can never land inside the budget and turn
    /// the case under test into the other one.
    fn gated<L>(
        load: L,
    ) -> (
        std::sync::mpsc::Sender<()>,
        impl FnOnce(&SharedIndex, &AtomicBool) -> anyhow::Result<()> + Send + 'static,
    )
    where
        L: FnOnce(&SharedIndex, &AtomicBool) -> anyhow::Result<()> + Send + 'static,
    {
        let (release, gate) = std::sync::mpsc::channel::<()>();
        let held = move |index: &SharedIndex, cancel: &AtomicBool| {
            let _ = gate.recv();
            load(index, cancel)
        };
        (release, held)
    }

    /// The session-open cold load is bounded: past its budget the open gets a
    /// `Loading` placeholder back at once and the load lands in the background,
    /// instead of the whole parse running inside `/v1/sessions/open` (which a
    /// large repository turned into a client timeout).
    #[tokio::test(flavor = "multi_thread")]
    async fn session_open_cold_load_past_its_budget_finishes_in_the_background() {
        let (_tmp, root) = source_tree(200);
        let job = cold_load_job(&root);
        let (release, load) = gated(job.reload());

        let (index, cold) = job
            .open_within(&tokio::runtime::Handle::current(), Duration::ZERO, load)
            .expect("an open past its budget still succeeds");

        assert_eq!(cold, ColdIndex::LoadingInBackground);
        assert_eq!(
            index.published_state().status,
            crate::live_index::PublishedIndexStatus::Loading,
            "the placeholder must report Loading, never an empty Ready index"
        );
        release.send(()).expect("the load is waiting at its gate");
        let published = wait_until_published(&index, |published| {
            published.status == crate::live_index::PublishedIndexStatus::Ready
        })
        .await;
        assert_eq!(published.file_count, 200);
    }

    /// A load that finishes inside the budget opens exactly as the inline path
    /// did: Ready, with curation recovery left to the opener.
    #[tokio::test(flavor = "multi_thread")]
    async fn session_open_cold_load_within_its_budget_opens_ready() {
        let tmp = TempDir::new().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonical root");
        std::fs::write(root.join("lib.rs"), "pub fn f() {}\n").expect("write source");
        let placement = session_open_placement(&root);
        let coordinator =
            Arc::new(crate::protocol::knowledge_curation::KnowledgeCurationCoordinator::default());

        let (index, cold) = bootstrap_project_index_within(
            &root,
            &placement,
            Duration::from_secs(60),
            &coordinator,
            CapabilityStatus::Available,
            &Arc::default(),
        )
        .expect("open");

        assert_eq!(cold, ColdIndex::Loaded);
        let published = index.published_state();
        assert_eq!(
            published.status,
            crate::live_index::PublishedIndexStatus::Ready
        );
        assert_eq!(published.file_count, 1);
    }

    /// A load that fails after the opener stopped waiting must not leave the
    /// project reporting `Loading` for a load that is no longer running, and
    /// is flagged for the next open to retry.
    #[tokio::test(flavor = "multi_thread")]
    async fn background_cold_load_failure_is_never_reported_as_loading() {
        let (_tmp, root) = source_tree(1);
        let job = cold_load_job(&root);
        let background = Arc::clone(&job.background);
        let (release, load) =
            gated(|_: &SharedIndex, _: &AtomicBool| Err(anyhow::anyhow!("source tree unreadable")));

        let (index, cold) = job
            .open_within(&tokio::runtime::Handle::current(), Duration::ZERO, load)
            .expect("open");
        assert_eq!(cold, ColdIndex::LoadingInBackground);
        release.send(()).expect("the load is waiting at its gate");

        let published = wait_until_published(&index, |published| {
            published.status != crate::live_index::PublishedIndexStatus::Loading
                && background.failed.load(Ordering::Acquire)
        })
        .await;
        assert_eq!(
            published.status,
            crate::live_index::PublishedIndexStatus::Empty
        );
        assert!(
            published
                .local_empty_reason
                .as_deref()
                .is_some_and(|reason| reason.contains("source tree unreadable")),
            "the failure is named: {:?}",
            published.local_empty_reason
        );
    }

    /// A load that panics is settled like one that failed. Before, the
    /// placeholder reported `Loading` for the rest of the daemon's life.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_panicking_background_load_is_settled_instead_of_left_loading() {
        let (_tmp, root) = source_tree(1);
        let job = cold_load_job(&root);
        let (release, load) = gated(|_: &SharedIndex, _: &AtomicBool| -> anyhow::Result<()> {
            panic!("parser exploded")
        });

        let (index, _) = job
            .open_within(&tokio::runtime::Handle::current(), Duration::ZERO, load)
            .expect("open");
        release.send(()).expect("the load is waiting at its gate");

        let published = wait_until_published(&index, |published| {
            published.status != crate::live_index::PublishedIndexStatus::Loading
        })
        .await;
        assert_eq!(
            published.status,
            crate::live_index::PublishedIndexStatus::Empty
        );
        let reason = published.local_empty_reason.clone().unwrap_or_default();
        assert!(
            reason.contains("panicked") && reason.contains("parser exploded"),
            "{reason}"
        );
    }

    /// Stopping the slot abandons its background load: the reload stops at
    /// its next cancellation check and nothing is settled or recovered into a
    /// project that no longer exists.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_background_load_whose_project_closed_is_abandoned() {
        let (_tmp, root) = source_tree(50);
        let job = cold_load_job(&root);
        let background = Arc::clone(&job.background);
        let reload = job.reload();
        let (landed, outcome) = std::sync::mpsc::channel::<bool>();
        let (release, load) = gated(move |index: &SharedIndex, cancel: &AtomicBool| {
            let result = reload(index, cancel);
            let _ = landed.send(result.is_ok());
            result
        });

        let (index, _) = job
            .open_within(&tokio::runtime::Handle::current(), Duration::ZERO, load)
            .expect("open");
        // What `ProjectSlot::stop` does.
        background.cancel.store(true, Ordering::Release);
        release.send(()).expect("the load is waiting at its gate");

        let loaded = tokio::task::spawn_blocking(move || outcome.recv().expect("the load ran"))
            .await
            .expect("join");
        assert!(!loaded, "a stopped slot's reload abandons its candidate");
        tokio::time::sleep(Duration::from_millis(300)).await;
        let published = index.published_state();
        assert_eq!(published.file_count, 0, "nothing was published");
        assert_eq!(published.local_empty_reason, None, "nothing was settled");
        assert!(
            !background.failed.load(Ordering::Acquire),
            "nothing to retry"
        );
    }

    #[test]
    fn closing_the_last_session_cancels_the_project_background_load() {
        let project = project_dir("symforge-daemon-cancel");
        let state = DaemonState::new();
        let opened = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(100),
            })
            .expect("open");
        let background = Arc::clone(
            &state
                .projects
                .read()
                .get(&opened.project_id)
                .expect("slot")
                .metadata
                .read()
                .background_load,
        );
        assert!(!background.cancel.load(Ordering::Acquire));

        state.close_session(&opened.session_id).expect("closed");

        assert!(
            background.cancel.load(Ordering::Acquire),
            "a reaped slot must stop its background load"
        );
    }

    /// A background load that failed is retried by the next session open.
    /// Before, later opens joined the failed slot and it stayed `Empty` until
    /// the daemon restarted.
    #[test]
    fn a_failed_background_load_is_retried_by_the_next_open() {
        let project = project_dir("symforge-daemon-retry");
        std::fs::write(project.path().join("src").join("a.rs"), "pub fn a() {}\n")
            .expect("write source");
        let state = Arc::new(DaemonState::new());
        let first = state
            .open_project_session(OpenProjectRequest {
                project_root: project.path().display().to_string(),
                client_name: "claude".to_string(),
                pid: Some(100),
            })
            .expect("first open");
        let (index, background) = {
            let projects = state.projects.read();
            let project = projects
                .get(&first.project_id)
                .expect("slot")
                .metadata
                .read();
            (project.index.shared(), Arc::clone(&project.background_load))
        };
        // What a background load that failed after its opener stopped waiting
        // leaves behind.
        index.set_local_empty_reason(Some(
            "the background index load failed: simulated".to_string(),
        ));
        background.failed.store(true, Ordering::Release);
        std::fs::write(project.path().join("src").join("b.rs"), "pub fn b() {}\n")
            .expect("write source");

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .expect("runtime");
        runtime.block_on(async {
            let opener = Arc::clone(&state);
            let root = project.path().display().to_string();
            tokio::task::spawn_blocking(move || {
                opener.open_project_session(OpenProjectRequest {
                    project_root: root,
                    client_name: "codex".to_string(),
                    pid: Some(200),
                })
            })
            .await
            .expect("join")
            .expect("second open");
            let published = wait_until_published(&index, |published| {
                published.file_count == 2 && published.local_empty_reason.is_none()
            })
            .await;
            assert_eq!(
                published.status,
                crate::live_index::PublishedIndexStatus::Ready
            );
        });
        assert!(!background.failed.load(Ordering::Acquire));
    }

    /// A background load that fails after another reload already published,
    /// `index_folder` for one, must not write its failure onto that Ready
    /// index or schedule a full reload for every later open.
    #[test]
    fn a_background_load_failing_after_another_load_published_leaves_it_alone() {
        let (_tmp, root) = source_tree(3);
        let job = cold_load_job(&root);
        job.index
            .reload_for_state_placement(&root, &job.placement)
            .expect("another reload published");

        job.finish(Err(anyhow::anyhow!(
            "reload refused: live mutation conflicts with the disk-built candidate"
        )));

        let published = job.index.published_state();
        assert_eq!(
            published.status,
            crate::live_index::PublishedIndexStatus::Ready
        );
        assert_eq!(published.local_empty_reason, None);
        assert!(!job.background.failed.load(Ordering::Acquire));
    }
}