symforge 11.20.0

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
pub mod ccr;
pub mod conventions;
pub(crate) mod deferred_stdio;
pub(crate) mod edit;
pub(crate) mod edit_format;
pub mod edit_hooks;
pub mod edit_plan;
pub(crate) mod edit_tools;
pub mod explore;
pub mod format;
pub mod investigation;
pub(crate) mod knowledge_curation;
pub(crate) mod knowledge_model;
pub(crate) mod knowledge_review;
pub(crate) mod knowledge_search;
pub mod prompts;
// Public within the crate tree for the C5 seam anchor `ReadGate` (reachable
// externally only through the repo-internal test door).
pub mod read_gate;
pub(crate) mod read_tools;
pub(crate) mod repeat;
pub mod resources;
pub mod result_status;
pub(crate) mod search_format;
pub(crate) mod search_tools;
pub use crate::knowledge::secret_dismissals;
pub(crate) mod secret_remediate;
pub(crate) mod serve_projects;
pub mod session;
pub mod smart_query;
pub mod surface_probe;
pub(crate) mod tool_contract;
pub mod tools;
pub mod withheld;

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use parking_lot::{Mutex, RwLock};

use rmcp::RoleServer;
use rmcp::handler::server::router::prompt::PromptRouter;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::model::{
    ListResourceTemplatesResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams,
    ReadResourceRequestParams, ServerCapabilities, ServerConfig, Tool,
};
use rmcp::service::RequestContext;
use rmcp::{ServerHandler, tool_handler};

use crate::domain::{
    CapabilityStatus, CapabilityUnavailableReason, ControlStateDir, ProjectStateDir, StatePlacement,
};
use crate::live_index::SharedIndex;
use crate::protocol::result_status::OutcomeClass;
use crate::sidecar::TokenStats;
use crate::watcher::WatcherInfo;

/// Tracks in-flight durable-ledger `spawn_blocking` writes so [`crate::server::serve::run`]
/// can drain them on shutdown instead of dropping economics events scheduled
/// just before SIGINT/SIGTERM (review finding P2-3).
///
/// Dependency-free: an atomic in-flight counter polled by [`Self::drain`]. Each
/// scheduled write holds a [`LedgerWriteGuard`] whose `Drop` decrements the
/// counter when the blocking write returns.
#[cfg(feature = "server")]
#[derive(Debug, Default)]
pub struct LedgerWriteTracker {
    in_flight: std::sync::atomic::AtomicUsize,
}

#[cfg(feature = "server")]
impl LedgerWriteTracker {
    /// Register a write about to be scheduled; the returned guard decrements the
    /// in-flight count on drop (i.e. when the blocking write completes).
    fn begin(self: &std::sync::Arc<Self>) -> LedgerWriteGuard {
        self.in_flight
            .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
        LedgerWriteGuard(std::sync::Arc::clone(self))
    }

    /// Number of durable writes still in flight.
    fn pending(&self) -> usize {
        self.in_flight.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Wait until every scheduled durable write completes, or `timeout` elapses
    /// (whichever comes first). Polls the in-flight counter; on timeout it logs
    /// the residual count rather than blocking shutdown indefinitely.
    pub async fn drain(&self, timeout: std::time::Duration) {
        let deadline = std::time::Instant::now() + timeout;
        while self.pending() != 0 {
            if std::time::Instant::now() >= deadline {
                tracing::warn!(
                    pending = self.pending(),
                    "durable ledger drain timed out; some economics events may be unwritten"
                );
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    }
}

/// Guard returned by [`LedgerWriteTracker::begin`]; decrements the in-flight
/// count when the blocking durable write completes (on drop).
#[cfg(feature = "server")]
struct LedgerWriteGuard(std::sync::Arc<LedgerWriteTracker>);

#[cfg(feature = "server")]
impl Drop for LedgerWriteGuard {
    fn drop(&mut self) {
        self.0
            .in_flight
            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
    }
}

#[cfg(all(test, feature = "server"))]
mod ledger_write_tracker_tests {
    use super::LedgerWriteTracker;
    use std::sync::Arc;
    use std::time::Duration;

    #[tokio::test]
    async fn drain_returns_after_pending_write_completes() {
        let tracker = Arc::new(LedgerWriteTracker::default());
        let guard = tracker.begin();
        assert_eq!(tracker.pending(), 1);
        // Release the guard shortly; drain must wait for it, then return.
        let t2 = Arc::clone(&tracker);
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            drop(guard);
            let _ = &t2;
        });
        tracker.drain(Duration::from_secs(2)).await;
        assert_eq!(
            tracker.pending(),
            0,
            "drain returned with a write still pending"
        );
    }

    #[tokio::test]
    async fn drain_times_out_without_hanging_on_a_stuck_write() {
        let tracker = Arc::new(LedgerWriteTracker::default());
        let _held = tracker.begin(); // never released => simulates a stuck write
        let start = std::time::Instant::now();
        tracker.drain(Duration::from_millis(50)).await;
        assert!(
            start.elapsed() >= Duration::from_millis(50),
            "drain returned before the timeout elapsed"
        );
        assert_eq!(tracker.pending(), 1, "stuck write must still be counted");
    }
}
/// Reconnect rediscovery cadence for a degraded daemon proxy: at most one
/// reconnect attempt per cooldown, so a dead endpoint neither pins the client
/// forever nor storms the daemon spawn path.
pub(crate) const DAEMON_RECONNECT_COOLDOWN: std::time::Duration =
    std::time::Duration::from_secs(30);

/// Degradation state for the daemon proxy. A degraded client must recover
/// across daemon ENDPOINT replacement (bounded rediscovery), not just when
/// the same endpoint heals — the sticky-degraded incident class.
#[derive(Default, Debug)]
pub(crate) struct DaemonDegradation {
    pub degraded: bool,
    /// Failure class of the last proxy failure (error text; never secrets).
    pub last_failure: Option<String>,
    pub last_failure_at: Option<std::time::Instant>,
    /// Base URL (no auth material) of the endpoint that last failed.
    pub last_endpoint: Option<String>,
    /// Last reconnect ATTEMPT — bounds rediscovery to one per cooldown.
    pub last_reconnect_attempt: Option<std::time::Instant>,
}

/// Health-renderable snapshot of the degradation state.
#[derive(Debug, Clone)]
pub struct DaemonDegradationSnapshot {
    pub endpoint: String,
    pub last_failure: String,
    pub retry_after_secs: u64,
}

/// The MCP server struct.
///
/// Holds a `SharedIndex` and a `ToolRouter` generated by the `#[tool_router]` macro.
/// Holds a `PromptRouter` generated by the `#[prompt_router]` macro.
/// The `project_name` field is passed through to `format::repo_outline`.
/// The `watcher_info` field is read by the health tool to report live watcher state.
/// The `repo_root` field is used by `index_folder` to restart the watcher at a new root.
/// The `token_stats` field provides live hook token savings to the health tool (AD-4 simpler path).
#[derive(Clone)]
pub struct SymForgeServer {
    // C4 (Feature 020 Slice 4, D1): held through the typed handle — the frozen
    // publication_roots census retires bare `SharedIndex` state fields.
    pub(crate) index: crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle,
    pub(crate) tool_router: ToolRouter<Self>,
    pub(crate) prompt_router: PromptRouter<Self>,
    pub(crate) project_name: String,
    pub(crate) watcher_info: Arc<Mutex<WatcherInfo>>,
    /// MUST NOT be held across `.await`. Use `.lock().take()` and
    /// `.lock().replace(...)` around async work; `parking_lot::Mutex` is
    /// non-async and held-across-await would deadlock the runtime.
    /// Some only in local-stdio mode where this server owns its watcher.
    /// None in daemon-proxy mode and daemon-degraded mode.
    pub(crate) watcher_handle: Arc<Mutex<Option<crate::watcher::WatcherTaskHandle>>>,
    /// Root directory the watcher is currently watching. Stored in shared mutable
    /// state so local stdio tools can keep using the latest project root after
    /// `index_folder` rebinds the server to a new workspace.
    pub(crate) repo_root: Arc<RwLock<Option<PathBuf>>>,
    /// Persistence placement selected for the currently bound project.
    ///
    /// Kept beside `repo_root` so checkpoint/reset paths consume the same typed
    /// placement selected during binding instead of reconstructing
    /// `<source>/.symforge`. A mixed root/placement observation during a
    /// concurrent rebind is fail-closed by the persistence root-ID check.
    pub(crate) state_placement: Arc<RwLock<Option<StatePlacement>>>,
    /// Process-global coordination namespace selected once for daemon/sidecar
    /// discovery. It is independent from the bound project's persistence
    /// placement and must never be reconstructed from the source root.
    pub(crate) control_state_dir: Option<ControlStateDir>,
    /// Runtime durability of the selected project-state owner. Placement is
    /// stable for the binding lifetime; a later write failure changes only this
    /// health signal and the capabilities derived from it.
    pub(crate) persistence_health: Arc<RwLock<CapabilityStatus>>,
    /// One ledger-mutation coordinator shared by every session bound to the
    /// same project runtime. It owns preview/apply serialization, durability
    /// probe caching, durable replay, and crash recovery for Gate K.
    pub(crate) curation_coordinator: Arc<knowledge_curation::KnowledgeCurationCoordinator>,
    /// Shared token stats from the HTTP sidecar. Present when the sidecar is running.
    /// The health tool reads this to display token savings accumulated during the session.
    pub(crate) token_stats: Option<Arc<TokenStats>>,
    /// Optional daemon-backed proxy session. When present, tool calls are forwarded to the
    /// shared daemon-owned project runtime instead of the local in-process index.
    /// Wrapped in `tokio::sync::RwLock` so reconnection can swap in a fresh client.
    pub(crate) daemon_client: Option<Arc<tokio::sync::RwLock<crate::daemon::DaemonSessionClient>>>,
    /// Daemon-proxy degradation state. Replaces the former bare AtomicBool:
    /// a degraded client must perform BOUNDED rediscovery (one reconnect per
    /// cooldown) instead of probing a dead endpoint forever, and health must
    /// be able to render the failure class, the failed endpoint, and the next
    /// retry eligibility.
    pub(crate) daemon_degraded: Arc<Mutex<DaemonDegradation>>,
    /// Descriptor republish context: the process control-state dir this
    /// adapter's session descriptor lives in. Set by the bootstrap (main.rs)
    /// so a successful reconnect can republish the descriptor with the NEW
    /// session id and endpoint.
    pub(crate) descriptor_state_dir: Arc<RwLock<Option<ControlStateDir>>>,
    /// The workspace root the MCP client DECLARED via `roots/list`, when one
    /// was declared. Health compares it against the root actually serving
    /// unqualified reads and renders a loud `project_mismatch` warning when
    /// they disagree (the wrong-repo incident class).
    pub(crate) caller_declared_root: Arc<RwLock<Option<PathBuf>>>,
    /// Session context tracking: records what the LLM has fetched this session.
    pub(crate) session_context: Arc<session::SessionContext>,
    /// Per-session CCR blob store for reversible bulk compression (011).
    pub(crate) ccr_store: Arc<Mutex<ccr::CcrStore>>,
    /// In-memory STEL L4 ledger for compact `symforge` invocations (no persistence yet).
    pub(crate) stel_ledger: Arc<Mutex<crate::stel::ledger::SessionLedger>>,
    /// Feature 032 (US1): the session-scoped repeat-call tracker. Every clone
    /// of this server (the HTTP factory clones per request, the daemon per
    /// project) shares the ONE map behind this `Arc`; the `call_tool` seam
    /// locks it synchronously after the awaited dispatch and never holds it
    /// across an `.await`.
    pub(crate) repeat_tracker: Arc<Mutex<repeat::RepeatTracker>>,
    /// Feature 032 (US1, F3): the transport this server was WIRED for,
    /// declared at construction and never inferred from a request. Defaults to
    /// [`repeat::TransportLane::Shared`] (inert) so a transport that reaches
    /// `call_tool` without declaring itself single-client gets no repeat
    /// notice, rather than silently becoming one shared accumulating bucket
    /// for every client behind it. Only [`Self::with_stdio_transport_lane`]
    /// moves it, and only the two stdio entry points call that.
    pub(crate) transport_lane: repeat::TransportLane,
    /// Tracks edit-tool calls that omitted `working_directory` while the
    /// transitional worktree observability knob was on. Surfaced by the
    /// `health` tool as a rolling "last hour" signal.
    pub(crate) worktree_misuse: Arc<crate::worktree::WorktreeMisuseCounter>,
    /// Bounded analytics queue. Disabled by default until an explicit local
    /// analytics configuration installs an enabled recorder.
    pub(crate) analytics_recorder: Arc<RwLock<crate::analytics::AnalyticsRecorder>>,
    /// Durable STEL L4 economics ledger. `Some` when `serve::run` (US3) or the
    /// stdio/daemon-proxy bootstrap (US1 T020/T021) wires the opened store in;
    /// `None` otherwise. The same `Arc` is shared with `ServerRuntime` so there
    /// is exactly one durable ledger path (no economics double-count). When
    /// `Some` it may be [`crate::stel::ledger_store::StelLedgerStore::Disabled`]
    /// if the DB could not open — write-through then degrades to a logged no-op
    /// (FR-011).
    ///
    /// Server-gated: embed durability is DEFERRED — `protocol` is crate-root
    /// server-gated (`src/lib.rs`), so an `any(server, embed)` cfg here would be
    /// dead under embed. Reaching the store from embed needs a structural
    /// protocol-free seam (out of US1 scope; spec FR-001 note).
    #[cfg(feature = "server")]
    pub(crate) stel_ledger_store: Option<Arc<crate::stel::ledger_store::StelLedgerStore>>,
    /// In-flight durable-ledger write tracker (P2-3): lets `serve::run` drain
    /// pending `spawn_blocking` economics writes on shutdown so events accepted
    /// just before SIGINT/SIGTERM are not lost.
    #[cfg(feature = "server")]
    pub(crate) ledger_writes: Arc<LedgerWriteTracker>,
    /// #875: the operator-fixed repositories of a `symforge serve`. `Some` only
    /// on the one server `/mcp` dispatches through, which routes each call to a
    /// registry entry; the entries themselves carry `None`.
    pub(crate) serve_projects: Option<Arc<serve_projects::ServeProjects>>,
}

fn default_analytics_db_path(project_state_dir: Option<&ProjectStateDir>) -> PathBuf {
    project_state_dir
        .map(|state_dir| {
            crate::paths::project_state_path(state_dir, crate::paths::ANALYTICS_DB_NAME)
        })
        // Disabled analytics performs no I/O. With no durable project-state
        // owner, retain an empty diagnostic path instead of inventing a
        // CWD-relative fallback.
        .unwrap_or_default()
}

fn disabled_analytics_recorder(
    project_state_dir: Option<&ProjectStateDir>,
) -> crate::analytics::AnalyticsRecorder {
    crate::analytics::AnalyticsRecorder::disabled(default_analytics_db_path(project_state_dir))
}

impl SymForgeServer {
    pub(crate) fn tool_router() -> ToolRouter<Self> {
        Self::core_tool_router() + Self::edit_tool_router() + Self::secret_remediate_tool_router()
    }

    /// Create a new server with the given shared index, project name, and watcher state.
    ///
    /// `token_stats` is optional — when `Some`, the health tool will include a token savings
    /// section showing per-hook-type fire counts and estimated tokens saved this session.
    pub fn new(
        index: SharedIndex,
        project_name: String,
        watcher_info: Arc<Mutex<WatcherInfo>>,
        repo_root: Option<PathBuf>,
        token_stats: Option<Arc<TokenStats>>,
    ) -> Self {
        let (repo_root, state_placement) = match repo_root.as_deref() {
            Some(root) => match crate::discovery::resolve_root_candidate(
                root,
                crate::domain::RootCandidateSource::LaunchCwd,
                crate::domain::RootRequestMode::Automatic,
            ) {
                crate::domain::RootResolution::Bound(binding) => {
                    let placement = crate::discovery::resolve_state_placement(&binding);
                    (Some(binding.canonical_root), Some(placement))
                }
                crate::domain::RootResolution::Unbound { .. } => (None, None),
            },
            None => (None, None),
        };
        Self::new_with_state_placement(
            index,
            project_name,
            watcher_info,
            repo_root,
            state_placement,
            token_stats,
        )
    }

    /// Create a server with an already-resolved project state placement.
    ///
    /// Production bind paths use this constructor so root authorization and
    /// state placement run once and every persistence consumer receives the
    /// same typed result. [`Self::new`] remains the compatibility constructor
    /// for callers that only have an automatically authorized normal root.
    pub fn new_with_state_placement(
        index: SharedIndex,
        project_name: String,
        watcher_info: Arc<Mutex<WatcherInfo>>,
        repo_root: Option<PathBuf>,
        state_placement: Option<StatePlacement>,
        token_stats: Option<Arc<TokenStats>>,
    ) -> Self {
        crate::worktree::register_if_feature_enabled();
        let analytics_recorder = disabled_analytics_recorder(
            state_placement.as_ref().and_then(StatePlacement::directory),
        );
        let persistence_health = if matches!(
            state_placement.as_ref(),
            Some(StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. })
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        // This constructor is 99.1% of `serve: runtime built` on a cold index
        // (2.91s of 2.94s) but is ~free when the index came from a snapshot
        // restore. Only ONE thing in here takes the index, so name it: the
        // routers below are static and would cost the same on both paths.
        let curation_coordinator =
            Arc::new(knowledge_curation::KnowledgeCurationCoordinator::default());
        let phase = std::time::Instant::now();
        if let Some(root) = repo_root.as_deref()
            && let Err(error) = curation_coordinator.recover_on_project_load(
                &index,
                root,
                state_placement.as_ref(),
                persistence_health,
            )
        {
            tracing::warn!("knowledge curation startup recovery remained fail-closed: {error}");
        }
        tracing::info!(
            "serve: protocol/curation recover_on_project_load in {:?}",
            phase.elapsed()
        );

        let phase = std::time::Instant::now();
        let tool_router = Self::tool_router();
        let prompt_router = Self::prompt_router();
        tracing::info!("serve: protocol/routers in {:?}", phase.elapsed());
        Self {
            index: crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(
                index,
            ),
            tool_router,
            prompt_router,
            project_name,
            watcher_info,
            watcher_handle: Arc::new(Mutex::new(None)),
            repo_root: Arc::new(RwLock::new(repo_root)),
            state_placement: Arc::new(RwLock::new(state_placement)),
            control_state_dir: crate::paths::process_control_state_placement()
                .directory()
                .cloned(),
            persistence_health: Arc::new(RwLock::new(persistence_health)),
            curation_coordinator,
            token_stats,
            daemon_client: None,
            daemon_degraded: Arc::new(Mutex::new(DaemonDegradation::default())),
            descriptor_state_dir: Arc::new(RwLock::new(None)),
            caller_declared_root: Arc::new(RwLock::new(None)),
            session_context: Arc::new(session::SessionContext::new()),
            ccr_store: Arc::new(Mutex::new(ccr::CcrStore::new())),
            stel_ledger: Arc::new(Mutex::new(crate::stel::ledger::SessionLedger::new())),
            repeat_tracker: Arc::new(Mutex::new(repeat::RepeatTracker::default())),
            transport_lane: repeat::TransportLane::default(),
            worktree_misuse: Arc::new(crate::worktree::WorktreeMisuseCounter::new()),
            analytics_recorder: Arc::new(RwLock::new(analytics_recorder)),
            #[cfg(feature = "server")]
            stel_ledger_store: None,
            #[cfg(feature = "server")]
            ledger_writes: Arc::new(LedgerWriteTracker::default()),
            serve_projects: None,
        }
    }

    pub fn new_daemon_proxy(daemon_client: crate::daemon::DaemonSessionClient) -> Self {
        let repo_root = daemon_client.project_root().map(|p| p.to_path_buf());
        let state_placement = repo_root.as_deref().and_then(|root| {
            match crate::discovery::resolve_root_candidate(
                root,
                crate::domain::RootCandidateSource::LaunchCwd,
                crate::domain::RootRequestMode::Automatic,
            ) {
                crate::domain::RootResolution::Bound(binding) => {
                    Some(crate::discovery::resolve_state_placement(&binding))
                }
                crate::domain::RootResolution::Unbound { .. } => None,
            }
        });
        Self::new_daemon_proxy_with_state_placement(daemon_client, state_placement)
    }

    /// Create a daemon proxy with a placement already resolved by the adapter.
    ///
    /// This keeps every adapter-side persistence consumer on the same typed
    /// owner instead of resolving state independently from the source root.
    pub fn new_daemon_proxy_with_state_placement(
        daemon_client: crate::daemon::DaemonSessionClient,
        state_placement: Option<StatePlacement>,
    ) -> Self {
        use crate::watcher::WatcherInfo;

        crate::worktree::register_if_feature_enabled();
        let project_name = daemon_client.project_name().to_string();
        let repo_root = daemon_client.project_root().map(|p| p.to_path_buf());
        let analytics_recorder = disabled_analytics_recorder(
            state_placement.as_ref().and_then(StatePlacement::directory),
        );
        let persistence_health = if matches!(
            state_placement.as_ref(),
            Some(StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. })
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        Self {
            index: crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(
                crate::live_index::LiveIndex::empty(),
            ),
            tool_router: Self::tool_router(),
            prompt_router: Self::prompt_router(),
            project_name,
            watcher_info: Arc::new(Mutex::new(WatcherInfo::default())),
            watcher_handle: Arc::new(Mutex::new(None)),
            repo_root: Arc::new(RwLock::new(repo_root)),
            state_placement: Arc::new(RwLock::new(state_placement)),
            control_state_dir: Some(daemon_client.control_state_dir().clone()),
            persistence_health: Arc::new(RwLock::new(persistence_health)),
            curation_coordinator: Arc::new(
                knowledge_curation::KnowledgeCurationCoordinator::default(),
            ),
            token_stats: None,
            daemon_client: Some(Arc::new(tokio::sync::RwLock::new(daemon_client))),
            daemon_degraded: Arc::new(Mutex::new(DaemonDegradation::default())),
            descriptor_state_dir: Arc::new(RwLock::new(None)),
            caller_declared_root: Arc::new(RwLock::new(None)),
            session_context: Arc::new(session::SessionContext::new()),
            ccr_store: Arc::new(Mutex::new(ccr::CcrStore::new())),
            stel_ledger: Arc::new(Mutex::new(crate::stel::ledger::SessionLedger::new())),
            repeat_tracker: Arc::new(Mutex::new(repeat::RepeatTracker::default())),
            transport_lane: repeat::TransportLane::default(),
            worktree_misuse: Arc::new(crate::worktree::WorktreeMisuseCounter::new()),
            analytics_recorder: Arc::new(RwLock::new(analytics_recorder)),
            #[cfg(feature = "server")]
            stel_ledger_store: None,
            #[cfg(feature = "server")]
            ledger_writes: Arc::new(LedgerWriteTracker::default()),
            serve_projects: None,
        }
    }

    /// Attach a durable STEL economics ledger store to this server (US3/T028).
    ///
    /// Builder-style; consumed by `server::serve::build_serve_runtime` so the
    /// same `Arc<StelLedgerStore>` is shared with `ServerRuntime`. This is the
    /// single durable ledger path — the in-memory `SessionLedger` write and the
    /// durable write-through both happen in `finalize_symforge_with_ledger`, so
    /// no economics row is counted twice.
    #[cfg(feature = "server")]
    pub fn with_stel_ledger_store(
        mut self,
        store: Arc<crate::stel::ledger_store::StelLedgerStore>,
    ) -> Self {
        self.stel_ledger_store = Some(store);
        self
    }

    /// Feature 032 (F3): declare this server's transport as single-client
    /// stdio, the ONE condition under which the repeat tracker may attribute
    /// a run to a session.
    ///
    /// Called only by the two stdio entry points (`src/cli/entry.rs`: the
    /// local server and the daemon-proxy adapter), where one process serves
    /// exactly one client, so the server instance IS the session. Every other
    /// wiring leaves the lane [`repeat::TransportLane::Shared`] and never
    /// accumulates — a lane that cannot be attributed produces no notice
    /// instead of a count shared across clients (spec FR-002 / Scenario 5).
    pub fn with_stdio_transport_lane(mut self) -> Self {
        self.transport_lane = repeat::TransportLane::Stdio;
        self
    }

    /// Write one finalized ledger event through to the durable store (US3/T028).
    ///
    /// Called from `finalize_symforge_with_ledger` AFTER the in-memory
    /// `SessionLedger` push. The durable write degrades to a logged no-op on a
    /// store error and never fails the request (FR-011): `StelLedgerStore::record`
    /// no-ops when `Disabled` and logs-and-continues on an insert error. On
    /// stdio/embed builds (`server` feature off) this is a compile-time no-op.
    ///
    /// P2-C (resolved — non-blocking durable write): `StelLedgerStore::record`
    /// takes a `std::sync::Mutex<Connection>` and runs a sync INSERT under an
    /// up-to-5000ms busy-timeout. Running that inline on the tokio worker serving
    /// `/mcp` could stall concurrent HTTP clients. So when a tokio runtime is
    /// present we offload the blocking write onto `spawn_blocking` (the store is
    /// behind `Arc`, the event is cloned), and the request task returns without
    /// waiting on the DB lock. The in-memory `SessionLedger` push stays
    /// synchronous/immediate in `finalize_symforge_with_ledger`; only this
    /// durable write moves off the hot path. When no runtime is present (sync
    /// tests / embed call sites) we record synchronously so events are never
    /// lost. Either way `record` degrades silently on store error.
    #[cfg(feature = "server")]
    fn persist_ledger_event_durably(&self, event: &crate::stel::types::StelLedgerEvent) {
        let Some(store) = self.stel_ledger_store.as_ref() else {
            return;
        };
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                // Offload the blocking SQLite write off the request task so the
                // DB lock / busy-timeout never stalls the tokio worker serving
                // MCP. Fire-and-forget: the durable write is best-effort and
                // degrades silently inside `record` on any store error.
                let store = Arc::clone(store);
                let event = event.clone();
                // P2-3: register the write so serve::run can drain in-flight
                // durable writes on shutdown instead of dropping them.
                let guard = self.ledger_writes.begin();
                handle.spawn_blocking(move || {
                    let _guard = guard; // decrements the in-flight count on completion
                    store.record(&event);
                    // T031: after the new sample lands, run the tuning pass and
                    // persist an accepted candidate — off the hot path, in the
                    // same blocking task, so the auto-tune never stalls the MCP
                    // worker. Degrades silently on any store error.
                    Self::maybe_persist_tuning(&store);
                });
            }
            Err(_) => {
                // No tokio runtime (sync test / embed context): record inline so
                // events are never dropped. There is no async worker to protect
                // here, so blocking is acceptable.
                crate::stel::runtime::record_durably_inline(store, event);
            }
        }
    }

    /// The in-flight durable-ledger write tracker (P2-3), exposed so
    /// `serve::run` can drain pending economics writes on shutdown.
    #[cfg(feature = "server")]
    pub(crate) fn ledger_write_tracker(&self) -> &Arc<LedgerWriteTracker> {
        &self.ledger_writes
    }

    /// Run a tuning pass over the durable samples and persist an accepted
    /// candidate (feature 013, T031 / FR-008 audited gated action).
    ///
    /// Reads the current-estimator samples, derives + held-out-validates a
    /// candidate `response_correction_factor` against the correction currently in
    /// force (identity `1.0`, or the active tuning's factor — the D13 hysteresis
    /// anchor), and on an accepted `Tuned` verdict writes it via
    /// `store_active_tuning` with the audit fields (factor, sample_size,
    /// error_before/after, tuned_at). Idempotent: when the accepted candidate's
    /// factor equals the already-stored one, it is NOT re-written (no SQLite
    /// churn, no oscillation). Non-blocking off the hot path (called inside the durable
    /// write's `spawn_blocking`); a `Disabled`/absent store degrades to a no-op
    /// and never serves a bad tuning. NO frecency bump (Principle V).
    #[cfg(feature = "server")]
    fn maybe_persist_tuning(store: &crate::stel::ledger_store::StelLedgerStore) {
        crate::stel::runtime::maybe_persist_tuning(store)
    }

    /// The validated tuned-constant set currently IN FORCE for the current
    /// estimator version (feature 013, T032 / FR-006), or `None`.
    ///
    /// Loads the active tuning from the durable store and applies the R3 in-force
    /// rule via [`active_tuning_in_force`]: a tuning whose `estimator_version`
    /// does not match the current estimator is NOT returned, so a stale-version
    /// set never silently applies. A `Disabled`/absent store yields `None` and
    /// the economics fall back to the static floors — never serves a bad tuning
    /// (FR-003). Read-only; no frecency bump (Principle V).
    ///
    /// [`active_tuning_in_force`]: crate::stel::controller::active_tuning_in_force
    #[cfg(feature = "server")]
    pub(crate) fn active_tuning_for_economics(
        &self,
    ) -> Option<crate::stel::ledger_store::TunedEstimateConstants> {
        crate::stel::runtime::active_tuning_for_economics(self.stel_ledger_store.as_deref())
    }

    /// Compute the honest [`CalibrationVerdict`] from the DURABLE calibration
    /// state for the `status` surface (feature 013, T033 / FR-009).
    ///
    /// `Tuned` is returned ONLY when an active tuning is in force AND it carries a
    /// before/after held-out error artifact (`error_before > error_after`),
    /// reading the artifact straight off the persisted set so the surface never
    /// claims `tuned` without it. Otherwise the verdict reflects the durable
    /// sample count (`Deferred` / `Accumulating(n/min)`). When no durable store is
    /// wired, returns `None` so the caller keeps the in-memory view. When a wired
    /// store cannot answer the sample query, pins the verdict to `Deferred` so a
    /// stale in-memory session cannot claim `Tuned` while no validated tuning is
    /// readable. Read-only; no frecency bump.
    ///
    /// [`CalibrationVerdict`]: crate::stel::calibration::CalibrationVerdict
    #[cfg(feature = "server")]
    pub(crate) fn durable_calibration_verdict(
        &self,
    ) -> Option<crate::stel::calibration::CalibrationVerdict> {
        crate::stel::runtime::durable_calibration_verdict(self.stel_ledger_store.as_deref())
    }

    /// Clear accumulated calibration for the current estimator (feature 013,
    /// T037 / FR-011 operator reset). Returns the number of sample rows cleared,
    /// or `None` when no durable store is wired. Never rebuilds the index.
    #[cfg(feature = "server")]
    pub(crate) fn reset_calibration(&self) -> Option<usize> {
        crate::stel::runtime::reset_calibration(self.stel_ledger_store.as_deref())
    }

    #[cfg(not(feature = "server"))]
    #[inline]
    fn persist_ledger_event_durably(&self, _event: &crate::stel::types::StelLedgerEvent) {}

    /// Durable-ledger subsystem state for the `status` tool (US3/T029
    /// restart-survival; N-3 / TR-17 / FR-008).
    ///
    /// Maps the wired durable store's [`subsystem_state`] onto the
    /// feature-independent surface enum. Reports `Unavailable` when no store is
    /// attached, `Disabled { reason }` for a wired-but-failing store (open failed
    /// at startup or live query failed — N-3, never swallowed), and `Durable`
    /// otherwise. On embed builds (`server` feature off) this is a compile-time
    /// `Unavailable`.
    ///
    /// Reachability note (honest scope of N-3/FR-008): a durable store is wired by
    /// `server::serve::run` (the `/mcp` surface) AND by the stdio + daemon-proxy
    /// bootstrap (US1 T020/T021). On the daemon-proxy `status` path the proxy
    /// itself holds the store, so `status_stel_tool` overlays THIS value (among
    /// all proxy-owned lines) onto the proxied worker body
    /// (`overlay_proxy_status_lines`) — the operator sees the proxy's real
    /// `Durable`/`Disabled` state, not the storeless worker's `unavailable`
    /// (D2-ROOT). It stays `Unavailable` only when no store is attached anywhere.
    ///
    /// [`subsystem_state`]: crate::stel::ledger_store::StelLedgerStore::subsystem_state
    #[cfg(feature = "server")]
    fn durable_ledger_summary_for_status(&self) -> crate::stel::status::DurableLedgerState {
        crate::stel::runtime::durable_ledger_state(self.stel_ledger_store.as_deref())
    }

    #[cfg(not(feature = "server"))]
    #[inline]
    fn durable_ledger_summary_for_status(&self) -> crate::stel::status::DurableLedgerState {
        crate::stel::status::DurableLedgerState::Unavailable
    }

    /// Accessor for tests: the project runtime handle owning the index.
    pub fn index(&self) -> &crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle {
        &self.index
    }

    /// Accessor for STEL ledger integration tests.
    #[doc(hidden)]
    pub fn stel_ledger(&self) -> &Arc<Mutex<crate::stel::ledger::SessionLedger>> {
        &self.stel_ledger
    }

    /// Test-only: drop a stored CCR blob so the next matching read must re-serve.
    #[doc(hidden)]
    pub fn drop_ccr_blob_for_tests(&self, handle: &str) -> bool {
        self.ccr_store.lock().remove_blob(handle)
    }

    /// Return the MCP tool definitions advertised by this server.
    ///
    /// This is a read-only view over the generated router metadata so integration
    /// tests and diagnostics can validate client compatibility without spinning up
    /// a full stdio transport.
    pub fn tool_definitions() -> Vec<Tool> {
        Self::tool_router().list_all()
    }

    pub(crate) fn capture_repo_root(&self) -> Option<PathBuf> {
        self.repo_root.read().clone()
    }

    pub(crate) fn capture_state_placement(&self) -> Option<StatePlacement> {
        self.state_placement.read().clone()
    }

    pub(crate) fn capture_control_state_dir(&self) -> Option<ControlStateDir> {
        self.control_state_dir.clone()
    }

    #[cfg(test)]
    pub(crate) fn with_control_state_dir_for_test(
        mut self,
        control_state_dir: ControlStateDir,
    ) -> Self {
        self.control_state_dir = Some(control_state_dir);
        self
    }

    pub(crate) fn capture_project_state_dir(&self) -> Option<ProjectStateDir> {
        self.state_placement
            .read()
            .as_ref()
            .and_then(StatePlacement::directory)
            .cloned()
    }

    /// Record a frecency bump for the given paths against the bound workspace.
    ///
    /// No-op when no repo root is bound (the feature has nothing to anchor
    /// the per-workspace store to). Forwards to
    /// [`crate::live_index::frecency::bump`], which itself resolves session,
    /// persistent, or disabled collection policy.
    pub(crate) fn bump_frecency(&self, paths: &[PathBuf]) {
        if let Some(root) = self.capture_repo_root() {
            let project_state = self.capture_project_state_dir();
            crate::live_index::frecency::bump(&root, project_state.as_ref(), paths);
        }
    }

    pub(crate) fn effective_repo_root_for_git_tools(&self) -> Option<PathBuf> {
        self.capture_repo_root()
            .or_else(crate::discovery::find_project_root)
    }

    pub(crate) fn set_repo_root(&self, repo_root: Option<PathBuf>) {
        *self.repo_root.write() = repo_root.clone();
        if self.analytics_recorder.read().status().disabled {
            let state_dir = self.capture_project_state_dir();
            *self.analytics_recorder.write() = disabled_analytics_recorder(state_dir.as_ref());
        }
    }

    pub(crate) fn set_bound_project_state(
        &self,
        repo_root: Option<PathBuf>,
        state_placement: Option<StatePlacement>,
    ) {
        *self.persistence_health.write() = if matches!(
            state_placement.as_ref(),
            Some(StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. })
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        *self.state_placement.write() = state_placement;
        self.set_repo_root(repo_root);
    }

    /// Bump the worktree-awareness misuse counter when an edit handler
    /// was called without `working_directory` while worktree routing is active.
    /// No-op when the caller supplied the parameter or policy disables routing.
    /// The counter surfaces in `health` output as a rolling "last hour" signal
    /// for callers that should already be passing worktree routing context.
    pub(crate) fn note_worktree_misuse_if_active(&self, working_directory: Option<&str>) {
        if working_directory.is_none()
            && crate::worktree::routing_policy_from_env()
                == crate::capability::WorktreeRoutingPolicy::ExplicitCallTime
        {
            self.worktree_misuse.record_missing_working_directory();
        }
    }

    /// Record token savings from an MCP tool response so the health counter accumulates.
    pub(crate) fn record_read_savings(&self, saved_tokens: u64) {
        if let Some(ref stats) = self.token_stats {
            stats
                .read_saved_tokens
                .fetch_add(saved_tokens, std::sync::atomic::Ordering::Relaxed);
            stats
                .read_fires
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
    }

    /// Record token savings from a named MCP tool, tracking per-tool breakdown.
    pub(crate) fn record_tool_savings_named(
        &self,
        tool_name: &str,
        estimated_raw_tokens: u64,
        output_tokens: u64,
    ) {
        if let Some(ref stats) = self.token_stats {
            let saved = estimated_raw_tokens.saturating_sub(output_tokens);
            stats
                .read_saved_tokens
                .fetch_add(saved, std::sync::atomic::Ordering::Relaxed);
            stats
                .read_fires
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            stats.record_tool_tokens(tool_name, output_tokens, saved);
        }
    }

    /// The current publication identity for CCR handle minting: the source
    /// digest plus content generation of the bound index's published
    /// generation. `None` for an unbound session (nothing to encode).
    pub(crate) fn ccr_publication_identity(&self) -> Option<ccr::CcrPublicationIdentity> {
        let published = self.index.data_plane().published_generation();
        let source = published.source.as_deref()?;
        let bytes = serde_json::to_vec(source).ok()?;
        Some(ccr::CcrPublicationIdentity {
            source_digest: crate::hash::digest_hex(&bytes),
            content_generation: published.content_generation,
        })
    }

    /// Apply token budget with CCR offload for eligible discovery tools (011).
    pub(crate) fn apply_ccr_budget(
        &self,
        tool_name: &str,
        result: String,
        max_tokens: Option<u64>,
    ) -> String {
        let budget = ccr::resolve_tool_max_tokens(tool_name, max_tokens);
        if ccr::profile_for_tool(tool_name).is_some_and(|p| p.ccr_eligible) {
            let publication = self.ccr_publication_identity();
            let mut store = self.ccr_store.lock();
            return ccr::enforce_token_budget_with_ccr(
                &mut store,
                tool_name,
                result,
                budget,
                publication,
            );
        }
        format::enforce_token_budget(result, budget)
    }

    /// Apply the normal CCR policy and report whether its exact byte threshold
    /// caused truncation. This is used by callers whose leading metadata makes
    /// a completeness claim that must be downgraded after a post-assembly cut.
    pub(crate) fn apply_ccr_budget_with_truncation_status(
        &self,
        tool_name: &str,
        result: String,
        max_tokens: Option<u64>,
    ) -> (String, bool) {
        let budget = ccr::resolve_tool_max_tokens(tool_name, max_tokens);
        let truncated = budget
            .is_some_and(|tokens| tokens > 0 && result.len() > (tokens as usize).saturating_mul(4));
        (
            self.apply_ccr_budget(tool_name, result, max_tokens),
            truncated,
        )
    }

    /// Apply a token budget using a caller-provided, block-safe summary before
    /// CCR stores the complete output. This is used by structured multi-line
    /// results whose generic line cut could otherwise expose half a record.
    pub(crate) fn apply_ccr_budget_with_summary(
        &self,
        tool_name: &str,
        result: String,
        summary: String,
        max_tokens: Option<u64>,
    ) -> String {
        let budget = ccr::resolve_tool_max_tokens(tool_name, max_tokens);
        let Some(tokens) = budget.filter(|tokens| *tokens > 0) else {
            return result;
        };
        if ccr::profile_for_tool(tool_name).is_some_and(|profile| profile.ccr_eligible) {
            let summary = format::enforce_token_budget(summary, Some(tokens));
            let publication = self.ccr_publication_identity();
            let mut store = self.ccr_store.lock();
            return ccr::apply_ccr_overflow(
                &mut store,
                tool_name,
                summary,
                result,
                tokens,
                publication,
            );
        }
        format::enforce_token_budget(result, Some(tokens))
    }

    pub(crate) fn format_read_cache_hit(
        &self,
        meta: &crate::protocol::session::SessionCacheHitMeta,
        reason: &str,
    ) -> Option<String> {
        self.ccr_store.lock().get(&meta.retrieve_handle)?;
        self.session_context.record_cache_hit();
        Some(format::format_session_cache_hit_body(meta, reason))
    }

    pub(crate) fn compression_economics(&self) -> crate::protocol::ccr::CcrEconomics {
        self.ccr_store.lock().economics()
    }

    pub fn session_compression_heuristic(
        &self,
    ) -> crate::protocol::ccr::SessionCompressionHeuristic {
        let cache_hits = self.session_context.snapshot().cache_hit_count;
        crate::protocol::ccr::SessionCompressionHeuristic::from_parts(
            cache_hits,
            self.compression_economics(),
        )
    }

    pub(crate) fn record_tool_completion(
        &self,
        tool_name: &'static str,
        response_text: &str,
        duration: Duration,
        outcome_class: OutcomeClass,
    ) {
        self.record_tool_completion_with_success(
            tool_name,
            response_text,
            duration,
            outcome_class,
            !outcome_class.is_error(),
        );
    }

    /// Mutation tools pass their own `success`: the usage record must agree
    /// with the wire, and a not-found write is `isError:true` there while a
    /// not-found read is not.
    pub(crate) fn record_tool_completion_with_success(
        &self,
        tool_name: &'static str,
        response_text: &str,
        duration: Duration,
        outcome_class: OutcomeClass,
        success: bool,
    ) {
        let recorder = self.analytics_recorder.read().clone();
        let response_bytes = response_text.len() as u64;
        let observation = crate::analytics::AnalyticsObservation::new(
            tool_name,
            crate::analytics::AnalyticsSurface::Tool,
            recorder.configured_scope(),
            response_bytes,
            Some(crate::stel::handler::estimate_tokens_from_bytes(
                response_bytes,
            )),
            duration,
            success,
            outcome_class,
        );
        let _ = recorder.enqueue(observation);
    }

    #[cfg(test)]
    pub(crate) fn set_analytics_recorder_for_tests(
        &self,
        recorder: crate::analytics::AnalyticsRecorder,
    ) {
        *self.analytics_recorder.write() = recorder;
    }

    #[cfg(test)]
    pub(crate) fn analytics_queue_status_for_tests(
        &self,
    ) -> crate::analytics::AnalyticsQueueStatus {
        self.analytics_recorder.read().status()
    }

    fn restore_local_project_evidence(&self) {
        if let Some(evidence) = self.local_project_evidence() {
            result_status::record_project_evidence(evidence);
        } else {
            result_status::clear_project_evidence();
        }
    }

    /// Bind a daemon receipt to the selector serialized for this exact call.
    /// Set-valued reads cannot be represented by the single-project evidence
    /// schema, and a scalar mismatch must never inherit authority merely
    /// because the transport returned a syntactically valid header.
    fn validate_daemon_project_evidence(
        &self,
        params: &serde_json::Value,
        expected_project_id: Option<&str>,
    ) {
        // Any present set-valued selector is outside the single-project receipt
        // schema, including empty/malformed sets that a downstream decoder will
        // reject. Likewise, a present non-string scalar must not be treated as
        // omission and inherit the daemon ACTIVE project's receipt.
        if params
            .get("projects")
            .is_some_and(|projects| !projects.is_null())
        {
            result_status::clear_project_evidence();
            return;
        }
        let selector = match params.get("project") {
            None | Some(serde_json::Value::Null) => None,
            Some(serde_json::Value::String(project)) => {
                Some(project.as_str()).filter(|project| !project.trim().is_empty())
            }
            Some(_) => {
                result_status::clear_project_evidence();
                return;
            }
        };
        let receipt_selector = expected_project_id.or(selector);
        let valid = result_status::current_project_evidence().is_some_and(|evidence| {
            result_status::project_evidence_matches_selector(&evidence, receipt_selector)
        });
        if !valid {
            result_status::clear_project_evidence();
        }
    }

    /// Seed the dispatch scope only when the raw request still targets this
    /// adapter's local project. This runs before router deserialization, so a
    /// malformed foreign request or admitted relay cannot inherit HOME merely
    /// because it returned before the handler-level selector guard.
    async fn initial_project_evidence_for_call(
        &self,
        arguments: Option<&serde_json::Map<String, serde_json::Value>>,
    ) -> Option<result_status::ProjectEvidence> {
        fn object_matches_local(
            object: &serde_json::Map<String, serde_json::Value>,
            local: &result_status::ProjectEvidence,
        ) -> bool {
            if object
                .get("projects")
                .is_some_and(|projects| !projects.is_null())
            {
                return false;
            }
            if let Some(project) = object.get("project")
                && !project.is_null()
            {
                let Some(project) = project.as_str() else {
                    return false;
                };
                if !project.trim().is_empty()
                    && !result_status::project_evidence_matches_selector(local, Some(project))
                {
                    return false;
                }
            }
            if let Some(nested) = object
                .get("_probe_legacy_args")
                .and_then(serde_json::Value::as_object)
                && !object_matches_local(nested, local)
            {
                return false;
            }
            true
        }

        fn explicit_scalar_selector(
            object: &serde_json::Map<String, serde_json::Value>,
        ) -> Option<&str> {
            object
                .get("project")
                .and_then(serde_json::Value::as_str)
                .filter(|project| !project.trim().is_empty())
                .or_else(|| {
                    object
                        .get("_probe_legacy_args")
                        .and_then(serde_json::Value::as_object)
                        .and_then(explicit_scalar_selector)
                })
        }

        let local = self.local_project_evidence()?;
        if arguments.is_some_and(|arguments| !object_matches_local(arguments, &local)) {
            return None;
        }
        if let Some(daemon_lock) = self.daemon_client.as_ref() {
            let client = daemon_lock.read().await;
            let targets_home = match arguments.and_then(explicit_scalar_selector) {
                Some(selector) => client
                    .opened_project_for_selector(Some(selector))
                    .is_some_and(|(_, _, is_home)| is_home),
                None => client.active_project_is_home(),
            };
            if !targets_home {
                return None;
            }
        }
        Some(local)
    }

    /// Forward a tool call to the daemon. Returns:
    /// - `Some(result)` on success
    /// - `None` on connection failure (after one reconnect attempt), signalling
    ///   the caller to fall through to local execution
    ///
    /// Degraded recovery contract: a degraded client still makes ONE success
    /// probe per call; when it fails, rediscovery (reconnect) is attempted at
    /// most once per [`DAEMON_RECONNECT_COOLDOWN`] — a daemon restarted on a
    /// NEW endpoint must be found without an MCP client restart (the
    /// sticky-degraded incident class), while a permanently dead daemon must
    /// not turn every call into a reconnect storm.
    pub(crate) async fn proxy_tool_call<T>(&self, tool_name: &str, params: &T) -> Option<String>
    where
        T: serde::Serialize,
    {
        let daemon_lock = self.daemon_client.as_ref()?;

        let was_degraded = self.daemon_degraded.lock().degraded;

        let mut value = match serde_json::to_value(params) {
            Ok(value) => value,
            Err(error) => {
                result_status::record_read_outcome(result_status::ReadOutcome::InvalidRequest);
                return Some(format!("Daemon proxy serialization failed: {error}"));
            }
        };
        // A daemon session may target an ACTIVE sibling even when the caller
        // omitted `project`. If transport recovery ultimately fails, executing
        // the same request against this adapter's immutable HOME would return
        // or mutate the wrong repository. Precompute the safe fallback policy
        // from the exact serialized selector and the client's pinned working
        // set; a successful initial/retry daemon call is unaffected.
        let (local_fallback_refusal, expected_daemon_project_id) = {
            let client = daemon_lock.read().await;
            let has_project_topology =
                client.project_root().is_some() || client.activated_root().is_some();
            if value
                .get("projects")
                .is_some_and(|projects| !projects.is_null())
            {
                (
                    Some(format!(
                        "Error: project_routing: a set-valued daemon request cannot fall back to \
                         adapter HOME project '{}'. Restore daemon routing and retry.",
                        client.project_id()
                    )),
                    None,
                )
            } else {
                match value.get("project") {
                    Some(serde_json::Value::String(selector)) if !selector.trim().is_empty() => {
                        match client.opened_project_for_selector(Some(selector)) {
                            Some((project_id, _, true)) => (None, Some(project_id)),
                            Some((project_id, _, false)) => (
                                Some(format!(
                                    "Error: project_routing: daemon project '{project_id}' cannot \
                                     fall back to adapter HOME project '{}'. Restore daemon routing \
                                     and retry.",
                                    client.project_id()
                                )),
                                Some(project_id),
                            ),
                            None => (
                                Some(format!(
                                    "Error: project_routing: project selector '{}' cannot be resolved \
                                     for safe HOME fallback. Restore daemon routing and retry.",
                                    selector
                                )),
                                Some(if has_project_topology {
                                    // NUL cannot occur in an OS path-derived project ID or
                                    // name. Keep this non-empty so selector normalization can
                                    // never reinterpret an unresolved explicit selector as
                                    // omission.
                                    "\0unresolved-project-selector".to_string()
                                } else {
                                    selector.to_string()
                                }),
                            ),
                        }
                    }
                    Some(serde_json::Value::Null) | None => {
                        let active_project_id = client.active_project_id();
                        (
                            (!client.active_project_is_home()).then(|| {
                                format!(
                                    "Error: project_routing: ACTIVE daemon project '{}' cannot fall \
                                     back to adapter HOME project '{}'. Restore daemon routing and \
                                     retry.",
                                    active_project_id,
                                    client.project_id()
                                )
                            }),
                            has_project_topology.then_some(active_project_id),
                        )
                    }
                    Some(_) => (
                        Some(format!(
                            "Error: project_routing: a malformed project selector cannot inherit \
                             adapter HOME project '{}'. Correct the selector and retry.",
                            client.project_id()
                        )),
                        None,
                    ),
                }
            }
        };
        // Omission means the session ACTIVE project, but ACTIVE can change in
        // another concurrent request after the snapshot above. Pin every
        // selector-capable scalar call to that canonical project ID before the
        // first attempt and reuse the same value for the reconnect retry. A
        // post-call receipt check is too late for structural edits: it cannot
        // undo a write that raced onto a newly activated sibling.
        if let Some(object) = value.as_object_mut() {
            // Never forward a caller-supplied internal route pin. Only this
            // trusted adapter seam may synthesize it from the connection's
            // canonical ACTIVE snapshot.
            object.remove(crate::daemon::PRIVATE_PROJECT_ROUTE_PIN);
            if let Some(project) = object.get_mut("project")
                && project.is_null()
                && let Some(expected_project_id) = expected_daemon_project_id.as_ref()
            {
                *project = serde_json::Value::String(expected_project_id.clone());
            } else if !object.contains_key("project")
                && crate::daemon::private_project_routed_tool(tool_name)
                && let Some(expected_project_id) = expected_daemon_project_id.as_ref()
            {
                // These tools deliberately have no public selector. Carry a
                // daemon-private pin so a concurrent ACTIVE change cannot move
                // the already-snapshotted operation onto another repository.
                object.insert(
                    crate::daemon::PRIVATE_PROJECT_ROUTE_PIN.to_string(),
                    serde_json::Value::String(expected_project_id.clone()),
                );
            }
        }
        // The call seam seeds this slot with adapter-local evidence. Once a
        // daemon hop begins, only a fully observed daemon receipt may describe
        // a successful proxy result. Clear HOME up front; explicit local
        // fallback paths restore a fresh local capture below.
        result_status::clear_project_evidence();

        // First attempt.
        // IMPORTANT: The read lock on daemon_lock is held for the duration of
        // the HTTP call. If this hangs, it blocks reconnect (which needs a
        // write lock). We wrap in a timeout so read locks release promptly
        // on failure — the reqwest client also has its own timeout as a
        // backstop, but this ensures lock release within a tighter window.
        //
        // 30s (matching the post-reconnect retry and the governor's execution
        // bound), NOT tighter: a legitimately heavy read (get_repo_map full
        // outline on a large index) must not be misclassified as transport
        // death — that was the delayed-refusal incident. A DEAD endpoint
        // still fails fast (connect refused), so this costs nothing there.
        {
            let client = daemon_lock.read().await;
            match tokio::time::timeout(
                std::time::Duration::from_secs(30),
                client.call_tool_value(tool_name, value.clone()),
            )
            .await
            {
                Ok(Ok(result)) => {
                    self.validate_daemon_project_evidence(
                        &value,
                        expected_daemon_project_id.as_deref(),
                    );
                    self.note_daemon_recovered();
                    return Some(result);
                }
                Ok(Err(error)) => {
                    self.note_daemon_failure(client.base_url(), error.to_string());
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call failed, attempting reconnect: {error}"
                    );
                }
                Err(_elapsed) => {
                    self.note_daemon_failure(
                        client.base_url(),
                        "probe timed out after 30s".to_string(),
                    );
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call timed out after 30s, attempting reconnect"
                    );
                }
            }
        }

        if was_degraded {
            // Bounded rediscovery: inside the cooldown, serve locally; past
            // it, fall through to the single-flight reconnect below so a
            // replacement daemon on a NEW endpoint is found without an MCP
            // client restart.
            let cooling = self
                .daemon_degraded
                .lock()
                .last_reconnect_attempt
                .map(|attempt| attempt.elapsed() < DAEMON_RECONNECT_COOLDOWN)
                .unwrap_or(false);
            if cooling {
                tracing::warn!(
                    tool = tool_name,
                    "daemon proxy probe failed while degraded (reconnect cooldown active), falling back to local execution"
                );
                if let Some(refusal) = local_fallback_refusal.clone() {
                    result_status::clear_project_evidence();
                    // A routing refusal: the request named a project this lane
                    // cannot serve.
                    result_status::record_read_outcome(result_status::ReadOutcome::InvalidRequest);
                    return Some(refusal);
                }
                self.ensure_local_index().await;
                self.restore_local_project_evidence();
                return None;
            }
            tracing::info!(
                "daemon degraded past reconnect cooldown; attempting bounded rediscovery"
            );
        }

        // A generic reconnect replaces the daemon session and restores the
        // ACTIVE project from the adapter mirror. It must not interpose after
        // an `index_folder` daemon response but before that call records its
        // mirror. The index-folder handler already owns this lane; every other
        // tool takes it before the daemon-client write lock. Lock order is
        // therefore always activation lane -> daemon client.
        let _reconnect_activation_guard = if tool_name == "index_folder" {
            None
        } else {
            let lane = daemon_lock.read().await.activation_lane();
            Some(lane.lock_owned().await)
        };

        // Reconnect attempt — take a write lock so only one caller does this.
        let reconnected = {
            let mut client = daemon_lock.write().await;
            self.daemon_degraded.lock().last_reconnect_attempt = Some(std::time::Instant::now());
            match client.reconnect().await {
                Ok(new_client) => {
                    tracing::info!("daemon reconnected successfully");
                    let old_client = std::mem::replace(&mut *client, new_client);
                    // Feature 032 (F2): a replacement daemon session is a new
                    // index incarnation whose evidence can be byte-equal to
                    // the dead daemon's (`generation` is a per-process
                    // counter). A repeat run must not survive it: drop every
                    // run before anything is served through the new client.
                    self.repeat_tracker.lock().clear();
                    // Lifecycle fence: republish this adapter's session
                    // descriptor for the NEW session/endpoint, then close the
                    // previous session best-effort (the old daemon is usually
                    // dead; when it is alive, closing frees the working set
                    // instead of leaking it until the 24h reaper).
                    self.republish_session_descriptor(&client);
                    if let Err(error) = old_client.close().await {
                        tracing::debug!(
                            "previous daemon session close after reconnect failed (usually dead endpoint): {error}"
                        );
                    }
                    self.note_daemon_recovered();
                    true
                }
                Err(reconnect_error) => {
                    tracing::warn!(
                        "daemon reconnect failed, falling back to local execution: {reconnect_error}"
                    );
                    self.note_daemon_failure(
                        client.base_url(),
                        format!("reconnect failed: {reconnect_error}"),
                    );
                    if local_fallback_refusal.is_none() {
                        self.ensure_local_index().await;
                    }
                    false
                }
            }
        };

        if !reconnected {
            if let Some(refusal) = local_fallback_refusal.clone() {
                result_status::clear_project_evidence();
                // A routing refusal: the request named a project this lane
                // cannot serve.
                result_status::record_read_outcome(result_status::ReadOutcome::InvalidRequest);
                return Some(refusal);
            }
            self.restore_local_project_evidence();
            return None;
        }

        // Retry with the fresh client.
        {
            let client = daemon_lock.read().await;
            match tokio::time::timeout(
                std::time::Duration::from_secs(30),
                client.call_tool_value(tool_name, value.clone()),
            )
            .await
            {
                Ok(Ok(result)) => {
                    self.validate_daemon_project_evidence(
                        &value,
                        expected_daemon_project_id.as_deref(),
                    );
                    self.note_daemon_recovered();
                    Some(result)
                }
                Ok(Err(error)) => {
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call failed after reconnect, falling back to local: {error}"
                    );
                    self.note_daemon_failure(client.base_url(), error.to_string());
                    if let Some(refusal) = local_fallback_refusal.clone() {
                        result_status::clear_project_evidence();
                        // A routing refusal: the request named a project this lane
                        // cannot serve.
                        result_status::record_read_outcome(
                            result_status::ReadOutcome::InvalidRequest,
                        );
                        return Some(refusal);
                    }
                    self.ensure_local_index().await;
                    self.restore_local_project_evidence();
                    None
                }
                Err(_elapsed) => {
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call timed out after reconnect, falling back to local"
                    );
                    self.note_daemon_failure(
                        client.base_url(),
                        "post-reconnect call timed out after 30s".to_string(),
                    );
                    if let Some(refusal) = local_fallback_refusal {
                        result_status::clear_project_evidence();
                        // A routing refusal: the request named a project this lane
                        // cannot serve.
                        result_status::record_read_outcome(
                            result_status::ReadOutcome::InvalidRequest,
                        );
                        return Some(refusal);
                    }
                    self.ensure_local_index().await;
                    self.restore_local_project_evidence();
                    None
                }
            }
        }
    }

    /// Mark the daemon proxy healthy again (successful call or reconnect).
    fn note_daemon_recovered(&self) {
        let was_degraded = {
            let mut state = self.daemon_degraded.lock();
            let was_degraded = state.degraded;
            if was_degraded {
                tracing::info!("daemon proxy recovered; clearing degraded state");
            }
            *state = DaemonDegradation::default();
            was_degraded
        };
        // Feature 032 (F2): locally-served -> daemon-served is an incarnation
        // change. A repeat run must not survive a change of the index
        // instance it was observed against, so every run is dropped here
        // (a false negative at worst, never a false claim).
        if was_degraded {
            self.repeat_tracker.lock().clear();
        }
    }

    /// Record a proxy failure with endpoint provenance (base URL only — never
    /// auth material) for health rendering and rediscovery decisions.
    fn note_daemon_failure(&self, endpoint: &str, failure: String) {
        let was_healthy = {
            let mut state = self.daemon_degraded.lock();
            let was_healthy = !state.degraded;
            state.degraded = true;
            state.last_failure = Some(failure);
            state.last_failure_at = Some(std::time::Instant::now());
            state.last_endpoint = Some(endpoint.to_string());
            was_healthy
        };
        // Feature 032 (F2): daemon-served -> degraded is an incarnation
        // change: whatever serves next (a replacement daemon or the local
        // fallback) is not the index the runs were observed against, so every
        // run is dropped. Repeated failures while already degraded change
        // nothing and keep the local lane's runs intact.
        if was_healthy {
            self.repeat_tracker.lock().clear();
        }
    }

    /// Health surface hook: the current degradation snapshot, or `None` when
    /// the daemon proxy is healthy (or absent).
    pub(crate) fn daemon_degradation_snapshot(&self) -> Option<DaemonDegradationSnapshot> {
        let state = self.daemon_degraded.lock();
        if !state.degraded {
            return None;
        }
        Some(DaemonDegradationSnapshot {
            endpoint: state
                .last_endpoint
                .clone()
                .unwrap_or_else(|| "(unknown)".to_string()),
            last_failure: state
                .last_failure
                .clone()
                .unwrap_or_else(|| "(unrecorded)".to_string()),
            retry_after_secs: state
                .last_reconnect_attempt
                .map(|attempt| {
                    DAEMON_RECONNECT_COOLDOWN
                        .as_secs()
                        .saturating_sub(attempt.elapsed().as_secs())
                })
                .unwrap_or(0),
        })
    }

    /// After a successful reconnect, republish this adapter's session
    /// descriptor so sidecar/hook discovery resolves the NEW session id and
    /// endpoint instead of the stale pre-reconnect ones.
    fn republish_session_descriptor(&self, client: &crate::daemon::DaemonSessionClient) {
        let state_dir = self.descriptor_state_dir.read().clone();
        let (Some(state_dir), Some(port)) = (state_dir, client.port()) else {
            return;
        };
        if let Err(error) = crate::sidecar::port_file::write_session_descriptor(
            &state_dir,
            port,
            Some(client.session_id()),
            client.project_root(),
            client.daemon_started_at(),
        ) {
            tracing::warn!("failed to republish session descriptor after reconnect: {error}");
        }
    }

    /// The shared daemon-client slot, so process-lifecycle tasks (heartbeat,
    /// shutdown close) follow the CURRENT session across reconnects instead
    /// of a stale clone of the original.
    pub fn daemon_client_slot(
        &self,
    ) -> Option<Arc<tokio::sync::RwLock<crate::daemon::DaemonSessionClient>>> {
        self.daemon_client.clone()
    }

    /// Install the descriptor republish context (called by the stdio
    /// bootstrap once the control-state dir is known).
    pub fn set_descriptor_state_dir(&self, state_dir: ControlStateDir) {
        *self.descriptor_state_dir.write() = Some(state_dir);
    }

    pub(crate) async fn proxy_tool_call_without_params(&self, tool_name: &str) -> Option<String> {
        self.proxy_tool_call(tool_name, &serde_json::json!({}))
            .await
    }

    /// Lazily initialize the local index when the daemon is unreachable.
    /// Uses `SharedIndexHandle::reload` to populate the empty in-process index
    /// from disk, enabling graceful degradation to local-only mode.
    ///
    /// Root-mismatch invalidation: the early return fires only when the index is
    /// non-empty AND was built from the SAME root we are now targeting. If the
    /// target `repo_root` changed (a project switch via any `set_repo_root`
    /// caller) the recorded root no longer matches, so we fall through and
    /// reload from the current root instead of serving the previous project.
    /// This closes the stale-project class structurally — no caller has to
    /// remember to call `reset_to_empty` for correctness (that path still works
    /// and remains as defense in depth). Both roots are normalized via the same
    /// [`normalize_root`](crate::live_index::store::normalize_root) helper so the
    /// steady state (same project, repeated calls) never reloads on a cosmetic
    /// `\\?\` / trailing-slash / separator / case difference.
    async fn ensure_local_index(&self) {
        {
            let mut watcher = self.watcher_info.lock();
            *watcher = WatcherInfo::detached_local_fallback();
        }

        let repo_root = self.capture_repo_root();

        // Early return only when the index is non-empty AND its recorded root
        // matches the current target root (normalized compare). A non-empty
        // index built from a different root is stale: fall through to reload.
        let published = self.index.data_plane().published_state();
        if published.file_count > 0 {
            let target_root = repo_root
                .as_deref()
                .map(crate::live_index::store::normalize_root);
            match (&published.indexed_root, &target_root) {
                // Same project: serve the loaded index, no reload.
                (Some(indexed), Some(target)) if indexed == target => return,
                // No target root to compare against (cannot do better than the
                // already-loaded index): keep serving it rather than dropping to
                // an empty index we cannot repopulate.
                (_, None) => return,
                // Root mismatch (or an index with no recorded root): stale —
                // fall through and reload from the current target root.
                _ => {}
            }
        }

        if let Some(root) = repo_root {
            tracing::info!(
                root = %root.display(),
                "daemon unreachable — loading local index as fallback"
            );
            match self.index.data_plane().reload(&root) {
                Ok(()) => {
                    let published = self.index.data_plane().published_state();
                    tracing::info!(
                        files = published.file_count,
                        symbols = published.symbol_count,
                        "local fallback index loaded"
                    );
                    // Feature 032 (F2): a reloaded local index is a new
                    // incarnation; runs observed against the previous
                    // publication (daemon or local) must not survive it.
                    self.repeat_tracker.lock().clear();

                    // Spawn git temporal computation so co-change queries work
                    // after daemon degradation (mirrors index_folder behaviour).
                    let expected_gen = self.index.data_plane().current_project_generation();
                    crate::live_index::git_temporal::spawn_git_temporal_computation(
                        self.index.shared(),
                        root,
                        expected_gen,
                    );
                }
                Err(error) => {
                    tracing::error!("failed to load local fallback index: {error}");
                }
            }
        } else {
            tracing::warn!("daemon unreachable and no repo root available for local fallback");
        }
    }

    /// Bind the workspace from MCP client-declared roots when nothing else did.
    ///
    /// Called from [`ServerHandler::on_initialized`] after the client sends
    /// `notifications/initialized`, this queries the client's `roots/list` and
    /// resolves a workspace root with strict precedence:
    /// `SYMFORGE_WORKSPACE_ROOT` > client roots > launch-CWD walk
    /// ([`crate::discovery::resolve_workspace_root`]).
    ///
    /// Precedence is honored against the *already-bound* server state rather
    /// than re-deciding it: startup resolved the env override and the CWD walk
    /// before the transport came up. The env override always wins — if it is set
    /// and valid the bound root came from it and this is a deliberate no-op.
    ///
    /// Two paths let declared client roots bind/retarget despite an existing
    /// binding, both narrowly gated (see the body):
    ///   - the keystone home-CWD case where neither env nor CWD bound anything
    ///     (Cursor from a home directory: `repo_root: None`, empty index); and
    ///   - (012 D4-A) a daemon-proxy session that came up bound to a CWD-derived
    ///     root with NO env override — there client roots are authoritative
    ///     (`roots > CWD`) and retarget the live session, fixing the wrong-repo
    ///     binding that a stale launch CWD would otherwise pin forever.
    ///
    /// In both cases the resolved root drives the existing [`Self::index_folder`]
    /// path, which loads the local in-process index or, in a daemon-proxy server,
    /// proxies the rebind to `index_folder_for_session` (the per-session retarget).
    /// A local (non-proxy) server that is already bound still returns immediately,
    /// preserving its loaded index byte-for-byte.
    ///
    /// Failures are logged and swallowed: a client that declares no roots, an
    /// unreachable `roots/list`, or a forbidden root must never break the
    /// session — the server simply stays in its existing (empty) state, exactly
    /// as before this hook existed.
    // ponytail: SEP-2577 deprecates the entire MCP Roots capability (Root,
    // ListRootsResult, peer.list_roots()) with NO replacement in rmcp 2.0 — it is
    // slated for removal from the spec, not renamed. `roots/list` is still the only
    // way a client can declare its workspace, so we keep using it and scope the
    // allow to this fn. Upgrade path: when the spec settles on a successor
    // capability (or rmcp removes Roots), migrate this single function.
    // https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577
    /// Ask the client for its `roots/list` URIs without binding yet.
    ///
    /// Used by the deferred stdio front so `roots/list` is solicited as soon as
    /// `notifications/initialized` arrives — in parallel with daemon session
    /// setup — rather than waiting for `StdioStartup::Ready`. Env authority and
    /// a missing roots capability still skip the round-trip. The single
    /// `Peer::list_roots` solicitation lives here (FR-314).
    #[allow(deprecated)]
    pub(crate) async fn fetch_client_root_uris(
        peer: &rmcp::Peer<RoleServer>,
    ) -> Option<Vec<String>> {
        // Env override always wins: never bother the client for roots.
        if crate::discovery::workspace_root_env_is_authoritative() {
            tracing::debug!(
                "workspace environment authority prevents client-roots retarget or fallback"
            );
            return None;
        }

        // Spec correctness: only issue `roots/list` when the client actually
        // declared the `roots` capability at `initialize`. A client that did not
        // advertise roots (capabilities `{}`) has no obligation to answer a
        // `roots/list` request and may never reply, which would hang this hook
        // (and the session) indefinitely. `peer_info()` is the client's stored
        // `InitializeRequestParams`; absent or roots-less capabilities => skip.
        let declares_roots = peer
            .peer_info()
            .map(|info| info.capabilities.roots.is_some())
            .unwrap_or(false);
        if !declares_roots {
            tracing::debug!("client did not declare the roots capability; workspace stays unbound");
            return None;
        }

        // Defense in depth: even a roots-declaring client could stall. Bound the
        // request so a non-answering peer cannot hang the session — on timeout we
        // simply leave the workspace unbound, identical to the no-roots path.
        let roots = match tokio::time::timeout(std::time::Duration::from_secs(5), peer.list_roots())
            .await
        {
            Ok(Ok(result)) => result.roots,
            Ok(Err(error)) => {
                // Client declined / transport error. Stay unbound (pre-hook behavior).
                tracing::debug!(%error, "client roots/list failed; workspace stays unbound");
                return None;
            }
            Err(_elapsed) => {
                tracing::warn!(
                    "client roots/list did not respond within 5s; workspace stays unbound"
                );
                return None;
            }
        };

        if roots.is_empty() {
            tracing::debug!("client declared no roots; workspace stays unbound");
            return None;
        }

        Some(roots.into_iter().map(|root| root.uri).collect())
    }

    /// Apply previously fetched client root URIs to this server.
    ///
    /// Re-checks the local-already-bound gate (which needs the live server) so a
    /// prefetch that raced ahead of Ready cannot reload a local index. Daemon
    /// proxies may still retarget when the declared root differs.
    pub(crate) async fn apply_prefetched_client_roots(&self, root_uris: Option<Vec<String>>) {
        let Some(root_uris) = root_uris else {
            return;
        };
        if crate::discovery::workspace_root_env_is_authoritative() {
            return;
        }
        if self.capture_repo_root().is_some() {
            let is_daemon_proxy = self.daemon_client.is_some();
            if !is_daemon_proxy {
                return;
            }
            tracing::debug!(
                "daemon-proxy bound from CWD (no env override); allowing client roots to retarget"
            );
        }

        // Reaching this point means env is not authoritative; Passing None for
        // the env slot therefore cannot let a client root jump ahead of an
        // authoritative environment decision — `env > roots` holds.
        let Some(resolved) = crate::discovery::resolve_workspace_root(None, &root_uris, None)
        else {
            tracing::info!(
                roots = ?root_uris,
                "no usable workspace among client roots (forbidden/unparseable); staying unbound"
            );
            return;
        };

        let _ = self.bind_declared_client_root(resolved).await;
    }

    async fn bind_workspace_from_client_roots(&self, peer: &rmcp::Peer<RoleServer>) {
        // Precedence: `SYMFORGE_WORKSPACE_ROOT (env) > client roots > CWD walk`.
        //
        // Two cases let declared client roots win over an already-bound root, both
        // gated so the single-harness happy path and the local (non-daemon) loaded
        // index are never disturbed:
        //
        //   1. Nothing was bound at startup (env + CWD both resolved nothing):
        //      client roots are the only signal — bind from them. This is the
        //      original home-CWD launcher fix (Cursor) and is unconditional.
        //
        //   2. (012 D4-A, per-connection RETARGET) A daemon-proxy session is
        //      ALWAYS bound at startup (to whatever the launch CWD resolved), so
        //      case 1 never fires for it and a stale CWD binding would silently
        //      win forever — the #1 field wrong-repo bug. When the bound root did
        //      NOT come from the env override, the client's declared roots are
        //      authoritative (`roots > CWD`) and must retarget the session via the
        //      existing `index_folder` → `index_folder_for_session` path.
        //
        // The env override always wins (case skipped) so `env > roots` holds, and
        // a local (non-proxy) server keeps its exact prior behavior: it returns
        // here whenever it is already bound, never reloading a loaded index.
        if self.capture_repo_root().is_some() {
            let is_daemon_proxy = self.daemon_client.is_some();
            if !is_daemon_proxy {
                return;
            }
            tracing::debug!(
                "daemon-proxy bound from CWD (no env override); allowing client roots to retarget"
            );
        }

        let uris = Self::fetch_client_root_uris(peer).await;
        self.apply_prefetched_client_roots(uris).await;
    }

    /// Bind this connection to `resolved`, the workspace its client's roots
    /// named, through [`Self::index_folder`]. Returns the `index_folder`
    /// outcome, or `None` when nothing needed to change: a daemon session
    /// already bound to that root keeps its index, because re-indexing it would
    /// rebuild and re-snapshot the project its session open just loaded.
    pub(crate) async fn bind_declared_client_root(&self, resolved: PathBuf) -> Option<String> {
        // Record the declared root first so health can flag a serving-root
        // mismatch even if the bind itself fails.
        *self.caller_declared_root.write() = Some(resolved.clone());
        if let Some(daemon_lock) = self.daemon_client.as_ref() {
            let active = daemon_lock.read().await.active_project_id();
            if crate::daemon::project_key(&resolved) == active {
                tracing::info!(
                    root = %resolved.display(),
                    "client roots name the root this session is already bound to; skipped the rebind"
                );
                return None;
            }
            tracing::info!(
                root = %resolved.display(),
                "client roots name a different root than this session's; retargeting"
            );
        } else {
            tracing::info!(
                root = %resolved.display(),
                "binding workspace from MCP client roots (no env/CWD root at startup)"
            );
        }

        // Drive the existing index path. `index_folder` handles both the local
        // in-process reload (this server) and, in a daemon-proxy server, the
        // proxied session rebind — so no new index plumbing is introduced.
        let input = crate::protocol::tools::IndexFolderInput {
            path: resolved.display().to_string(),
            idempotency_key: None,
            add: None,
            allow_protected_root: None,
        };
        let result = self
            .index_folder(rmcp::handler::server::wrapper::Parameters(input))
            .await;
        tracing::info!(outcome = %result, "workspace bind from client roots complete");
        Some(result)
    }

    /// Legacy-renderer dispatcher used by tests and the constrained A-019 relay.
    ///
    /// This broad dispatcher is not the production safety boundary. The facade
    /// relay checks its source-mutation-safe allowlist before calling here.
    ///
    /// Mirrors the tool-name match in `daemon::execute_tool_call`, but takes
    /// `&self` so parity tests can exercise handlers directly without a live
    /// daemon or MCP transport. Only the tools needed by the `tests/` suites
    /// are wired up here.
    #[doc(hidden)]
    pub async fn dispatch_tool_for_tests(
        &self,
        tool_name: &str,
        params: serde_json::Value,
    ) -> String {
        use rmcp::handler::server::wrapper::Parameters;
        fn decode<T: serde::de::DeserializeOwned>(params: serde_json::Value) -> Result<T, String> {
            serde_json::from_value(params).map_err(|e| format!("invalid tool parameters: {e}"))
        }
        macro_rules! call {
            ($method:ident, $input:ty) => {{
                match decode::<$input>(params) {
                    Ok(input) => self.$method(Parameters(input)).await,
                    Err(e) => e,
                }
            }};
        }
        match tool_name {
            "replace_symbol_body" => call!(replace_symbol_body, edit::ReplaceSymbolBodyInput),
            "insert_symbol" => call!(insert_symbol, edit::InsertSymbolInput),
            "delete_symbol" => call!(delete_symbol, edit::DeleteSymbolInput),
            "edit_within_symbol" => call!(edit_within_symbol, edit::EditWithinSymbolInput),
            "batch_edit" => call!(batch_edit, edit::BatchEditInput),
            "batch_rename" => call!(batch_rename, edit::BatchRenameInput),
            "batch_insert" => call!(batch_insert, edit::BatchInsertInput),
            "search_files" => call!(search_files, tools::SearchFilesInput),
            "search_text" => call!(search_text, tools::SearchTextInput),
            "search_knowledge" => call!(search_knowledge, tools::SearchKnowledgeInput),
            "review_knowledge" => call!(review_knowledge, tools::ReviewKnowledgeInput),
            "curate_knowledge" => call!(curate_knowledge, tools::CurateKnowledgeInput),
            "search_symbols" => call!(search_symbols, tools::SearchSymbolsInput),
            "get_file_context" => call!(get_file_context, tools::GetFileContextInput),
            "get_file_content" => call!(get_file_content, tools::GetFileContentInput),
            "get_symbol" => call!(get_symbol, tools::GetSymbolInput),
            "get_symbol_context" => call!(get_symbol_context, tools::GetSymbolContextInput),
            "find_references" => call!(find_references, tools::FindReferencesInput),
            "find_dependents" => call!(find_dependents, tools::FindDependentsInput),
            "inspect_match" => call!(inspect_match, tools::InspectMatchInput),
            "analyze_file_impact" => call!(analyze_file_impact, tools::AnalyzeFileImpactInput),
            "edit_plan" => call!(edit_plan, tools::EditPlanInput),
            "index_folder" => call!(index_folder, tools::IndexFolderInput),
            "detect_impact" => call!(detect_impact, tools::DetectImpactInput),
            "what_changed" => call!(what_changed, tools::WhatChangedInput),
            "diff_symbols" => call!(diff_symbols, tools::DiffSymbolsInput),
            "explore" => call!(explore, tools::ExploreInput),
            "ask" => call!(ask, tools::SmartQueryInput),
            "get_repo_map" => call!(get_repo_map, tools::GetRepoMapInput),
            "context_inventory" => self.context_inventory().await,
            "symforge_retrieve" => call!(symforge_retrieve, read_tools::SymforgeRetrieveInput),
            "health" => call!(health, tools::HealthInput),
            "health_compact" => self.health_compact().await,
            "conventions" => self.conventions().await,
            other => format!("dispatch_tool_for_tests: unknown tool '{other}'"),
        }
    }

    /// Test-only dispatcher that preserves public `CallToolResult` status metadata.
    ///
    /// This intentionally wires only handlers that already emit the SFB09 result-status
    /// contract. It lets conformance tests replay canonical JSON requests without
    /// starting an MCP transport or accepting string-only fake success paths.
    #[doc(hidden)]
    pub async fn dispatch_tool_result_for_tests(
        &self,
        tool_name: &str,
        params: serde_json::Value,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        // Feature 034: mirror production call_tool withheld scope so unit
        // harnesses observe `symforge/withheld` meta on admission refusals.
        withheld::with_withheld_scope(self.dispatch_tool_result_for_tests_inner(tool_name, params))
            .await
    }

    async fn dispatch_tool_result_for_tests_inner(
        &self,
        tool_name: &str,
        params: serde_json::Value,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        use rmcp::handler::server::wrapper::Parameters;

        fn invalid_request_result(
            tool_name: &str,
            message: impl Into<String>,
        ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
            let text = format!(
                "Invalid request for tool `{tool_name}`: {}\nRecovery: compare the request JSON with the advertised input schema from tool_definitions().",
                message.into()
            );
            Ok(
                result_status::ResultStatus::new(result_status::OutcomeClass::InvalidRequest)
                    .into_call_tool_result(text),
            )
        }

        fn decode<T: serde::de::DeserializeOwned>(params: serde_json::Value) -> Result<T, String> {
            serde_json::from_value(params).map_err(|e| format!("invalid tool parameters: {e}"))
        }

        macro_rules! call_statused {
            ($method:ident, $input:ty) => {{
                match decode::<$input>(params) {
                    Ok(input) => self.$method(Parameters(input)).await,
                    Err(error) => invalid_request_result(tool_name, error),
                }
            }};
        }

        match tool_name {
            "replace_symbol_body" => {
                call_statused!(replace_symbol_body_tool, edit::ReplaceSymbolBodyInput)
            }
            "batch_edit" => call_statused!(batch_edit_tool, edit::BatchEditInput),
            "insert_symbol" => call_statused!(insert_symbol_tool, edit::InsertSymbolInput),
            "delete_symbol" => call_statused!(delete_symbol_tool, edit::DeleteSymbolInput),
            "edit_within_symbol" => {
                call_statused!(edit_within_symbol_tool, edit::EditWithinSymbolInput)
            }
            "batch_rename" => call_statused!(batch_rename_tool, edit::BatchRenameInput),
            "batch_insert" => call_statused!(batch_insert_tool, edit::BatchInsertInput),
            "search_files" => call_statused!(search_files_tool, tools::SearchFilesInput),
            "search_text" => call_statused!(search_text_tool, tools::SearchTextInput),
            "search_symbols" => call_statused!(search_symbols_tool, tools::SearchSymbolsInput),
            "get_file_content" => {
                call_statused!(get_file_content_tool, tools::GetFileContentInput)
            }
            "get_symbol" => call_statused!(get_symbol_tool, tools::GetSymbolInput),
            "get_symbol_context" => {
                call_statused!(get_symbol_context_tool, tools::GetSymbolContextInput)
            }
            "find_references" => call_statused!(find_references_tool, tools::FindReferencesInput),
            "symforge" => call_statused!(symforge_facade_tool, crate::stel::SymforgeCallInput),
            "symforge_edit" => {
                call_statused!(symforge_edit_facade_tool, crate::stel::StelEditRequest)
            }
            "status" => call_statused!(status_stel_tool, crate::stel::StelStatusRequest),
            "secret_remediate" => {
                call_statused!(
                    secret_remediate_tool,
                    secret_remediate::SecretRemediateInput
                )
            }
            other => {
                let text = format!(
                    "Unsupported tool `{other}` in public conformance harness.\nRecovery: add a statused dispatcher branch before adding the case, or remove the case from the public corpus."
                );
                Ok(
                    result_status::ResultStatus::new(result_status::OutcomeClass::InvalidRequest)
                        .into_call_tool_result(text),
                )
            }
        }
    }
}

/// Wire `SymForgeServer` as an MCP `ServerHandler`.
///
/// The `#[tool_handler]` macro delegates tool dispatch to `self.tool_router`
/// and supplies the `call_tool` / `list_tools` implementations automatically.
///
/// The prompt methods are hand-written (no `#[prompt_handler]`): unlike
/// `#[tool_handler]`, which defers to a manually defined method, the 3.x
/// `#[prompt_handler]` macro REPLACES a manual `list_prompts` in the annotated
/// impl block with its generated body (rmcp-macros 3.1.0
/// `prompt_handler.rs:85-87`), which would silently clobber the FR-310
/// cache-hint override. `get_prompt`/`list_prompts` below carry the exact
/// router delegation the macro would have generated.
#[tool_handler(router = self.tool_router)]
impl ServerHandler for SymForgeServer {
    fn get_info(&self) -> ServerConfig {
        // Override rmcp's `from_build_env` default, which expands
        // `CARGO_CRATE_NAME`/`CARGO_PKG_VERSION` inside the rmcp crate and would
        // otherwise identify this server as "rmcp"/<rmcp version>. `env!` here
        // expands in the symforge crate, staying in sync with Cargo.toml.
        let config = ServerConfig::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .enable_resources()
                .build(),
        )
        .with_server_info(rmcp::model::Implementation::new(
            "symforge",
            env!("CARGO_PKG_VERSION"),
        ));
        // SF-ADOPT-04: same env-driven profile `list_tools` serves, so the
        // instructions only name tools this connection can call (#874: with a
        // tool allow-list set, a generated line names exactly those tools).
        match surface_probe::connection_instructions() {
            Some(text) => config.with_instructions(text),
            None => config,
        }
    }

    /// FR-307 allow-list freeze (spec 025). rmcp 3.5.0's default already
    /// returns `KNOWN_VERSIONS` including `V_2026_07_28`; this override pins
    /// TODAY'S set explicitly so a future rmcp `"3.5"` semver update cannot
    /// auto-advertise a protocol revision symforge has never tested. Protocol
    /// exposure changes only by deliberate edit here. Extend, never shrink.
    fn supported_protocol_versions(
        &self,
    ) -> std::borrow::Cow<'static, [rmcp::model::ProtocolVersion]> {
        use rmcp::model::ProtocolVersion;
        std::borrow::Cow::Borrowed(&[
            ProtocolVersion::V_2024_11_05,
            ProtocolVersion::V_2025_03_26,
            ProtocolVersion::V_2025_06_18,
            ProtocolVersion::V_2025_11_25,
            ProtocolVersion::V_2026_07_28,
        ])
    }

    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourcesResult, rmcp::ErrorData>> + Send + '_
    {
        // FR-310/FR-311: static list surface — constructor seeds
        // `result_type: Some(COMPLETE)` (FR-305 pinned shape); 1h TTL, Public
        // (`resource_definitions()` embeds no workspace data). The #874 tool
        // allow-list filter is per process, so Public still holds.
        // #875: a multi-repository serve lists repository resources per alias.
        // The list is a function of the process's fixed set, so Public still holds.
        let resources = match self.serve_projects.as_ref() {
            Some(projects) if projects.serves_several() => {
                projects.per_alias_resources(self.advertised_resource_definitions())
            }
            _ => self.advertised_resource_definitions(),
        };
        std::future::ready(Ok(ListResourcesResult::with_all_items(resources)
            .with_ttl_ms(3_600_000)
            .with_cache_scope(rmcp::model::CacheScope::Public)))
    }

    fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourceTemplatesResult, rmcp::ErrorData>>
    + Send
    + '_ {
        // FR-310/FR-311: static list surface — same cache policy as
        // `list_resources`.
        let templates = match self.serve_projects.as_ref() {
            Some(projects) if projects.serves_several() => {
                projects.project_templates(self.advertised_resource_template_definitions())
            }
            _ => self.advertised_resource_template_definitions(),
        };
        std::future::ready(Ok(ListResourceTemplatesResult::with_all_items(templates)
            .with_ttl_ms(3_600_000)
            .with_cache_scope(rmcp::model::CacheScope::Public)))
    }

    fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<
        Output = Result<rmcp::model::ReadResourceResponse, rmcp::ErrorData>,
    > + Send
    + '_ {
        let uri = request.uri;
        // INV-1: the response enum exists only at this trait boundary; all
        // internal resource logic (and the spec-023 admission gating it wraps)
        // stays on `ReadResourceResult`.
        //
        // FR-319: resource reads never pass through `ResultStatus`, so project
        // evidence is attached here at the seam, inside the same evidence
        // scope `tools/call` uses (an inner daemon-proxied handler may
        // overwrite the seeded local evidence with its receipt).
        async move {
            // #875: a multi-repository serve routes the read by its `project` query.
            // The reply keeps the URI the client asked for, `?project=` included, so
            // two repositories' contents never share one URI.
            let requested = uri.clone();
            let (server, uri) = match self.serve_projects.as_ref() {
                Some(projects) => projects.route_resource(self, &uri)?,
                None => (self, uri),
            };
            result_status::with_project_evidence_scope(server.local_project_evidence(), async {
                server.read_resource_uri(&uri).await.map(|mut result| {
                    if uri != requested {
                        for contents in &mut result.contents {
                            match contents {
                                rmcp::model::ResourceContents::TextResourceContents {
                                    uri, ..
                                }
                                | rmcp::model::ResourceContents::BlobResourceContents {
                                    uri, ..
                                } => *uri = requested.clone(),
                                // ponytail: a future content kind keeps its own URI.
                                _ => {}
                            }
                        }
                    }
                    result_status::attach_project_evidence_meta(&mut result.meta);
                    rmcp::model::ReadResourceResponse::Complete(result)
                })
            })
            .await
        }
    }

    /// MCP `tools/call` dispatch with a central compact-surface gate (P1-A).
    ///
    /// The `#[tool_handler]` macro only generates `call_tool` when the impl block
    /// does not already define one; by providing this method we replace the
    /// generated body while preserving its exact router delegation. The added
    /// gate enforces FR-008 at dispatch (not just at `tools/list`): when the
    /// active surface is [`crate::protocol::surface_probe::SurfaceProfile::Compact`], a `tools/call` for any tool
    /// name NOT in the advertised compact-3 set
    /// ([`crate::stel::surface::COMPACT_TOOL_NAMES`]) is rejected with an MCP
    /// `InvalidRequest` error. Core, Full and Meta surfaces are unaffected, so the
    /// default full surface and the opt-in core profile (which lists only
    /// some tools) reach every legacy tool; `SYMFORGE_SURFACE=compact` is the opt-in escape hatch
    /// that gates them. This is shared by both transports because stdio and the HTTP `/mcp`
    /// serve path dispatch through the same `ServerHandler::call_tool`.
    async fn call_tool(
        &self,
        request: rmcp::model::CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
        surface_probe::enforce_compact_surface(request.name.as_ref())?;
        // #875: a `symforge serve` with operator-fixed repositories routes the
        // call to one of them here, after the gate above and before any evidence,
        // so each answer names its own repository. The gate runs exactly once.
        if let Some(projects) = self.serve_projects.as_ref() {
            return projects.route_tool_call(self, request, context).await;
        }
        self.dispatch_gated_tool_call(request, context).await
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, rmcp::ErrorData> {
        let tools = surface_probe::advertised_tools();
        // FR-305 pinned struct shape: the constructor seeds
        // `result_type: Some(COMPLETE)`. FR-310/FR-311: 1h TTL, Public — the
        // surface is fixed per-process (`SYMFORGE_SURFACE` is env-driven), and a
        // Public cache assumes ONE profile per HTTP origin (FR-311c). If core,
        // full and compact servers share an origin, a cached list from one is
        // served to the others: core<->full only hides or shows callable tools
        // (core refuses nothing); a core or full list reaching a compact client
        // discloses schemas the compact dispatch gate will refuse; a compact
        // list reaching core or full hides callable tools. Ordering is
        // deterministic (router insertion order), verified by test (SC-313).
        // The #874 tool allow-list (`SYMFORGE_TOOLS` / `serve --tools`) keeps
        // Public correct for the same reason: it is per process, never per
        // request or per API key, so one origin still serves one list.
        Ok(ListToolsResult::with_all_items(tools)
            .with_ttl_ms(3_600_000)
            .with_cache_scope(rmcp::model::CacheScope::Public))
    }

    /// Hand-written prompt dispatch — identical to what `#[prompt_handler]`
    /// would generate (see the impl-block doc comment for why the macro is not
    /// used).
    async fn get_prompt(
        &self,
        request: rmcp::model::GetPromptRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::GetPromptResponse, rmcp::ErrorData> {
        if let Some(projects) = self.serve_projects.as_ref()
            && projects.serves_several()
        {
            return Err(rmcp::ErrorData::invalid_request(
                projects.prompts_refusal(),
                None,
            ));
        }
        let prompt_context = rmcp::handler::server::prompt::PromptContext::new(
            self,
            request.name,
            request.arguments,
            context,
        );
        self.prompt_router.get_prompt(prompt_context).await
    }

    /// Manual `list_prompts` override (FR-310): the macro body plus the
    /// FR-311 static-list cache hints.
    async fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::ListPromptsResult, rmcp::ErrorData> {
        // #875: a multi-repository serve lists none (it refuses them); the
        // list stays constant per process, so the Public cache still holds.
        let prompts = match self.serve_projects.as_ref() {
            Some(projects) if projects.serves_several() => Vec::new(),
            _ => self.prompt_router.list_all(),
        };
        Ok(rmcp::model::ListPromptsResult::with_all_items(prompts)
            .with_ttl_ms(3_600_000)
            .with_cache_scope(rmcp::model::CacheScope::Public))
    }

    /// React to the client's `notifications/initialized`.
    ///
    /// After the handshake completes, the client's MCP `roots` capability (the
    /// open workspace folder it declared) becomes queryable via `roots/list`.
    /// We use it to bind the workspace when the launch CWD and
    /// `SYMFORGE_WORKSPACE_ROOT` resolved nothing at startup — the keystone
    /// "index won't load" case for home-CWD launchers (Cursor). Precedence
    /// (`SYMFORGE_WORKSPACE_ROOT` > client roots > launch-CWD walk) is enforced
    /// inside [`Self::bind_workspace_from_client_roots`], which is a deliberate
    /// no-op whenever startup already bound a root.
    ///
    /// Scope (FR-316, spec 025): this hook fires only for stdio /
    /// legacy-lifecycle clients that send `notifications/initialized`. The
    /// stateless HTTP `/mcp` path serves requests directly with no handshake
    /// enforcement, so this hook never runs there; modern discover-lifecycle
    /// clients are bound by the fallback chain (`SYMFORGE_WORKSPACE_ROOT` >
    /// `index_folder` > CWD walk), with the residual wrong-binding case
    /// disclosed via `_meta` project evidence (FR-319).
    async fn on_initialized(&self, context: rmcp::service::NotificationContext<RoleServer>) {
        tracing::info!("client initialized");
        self.bind_workspace_from_client_roots(&context.peer).await;
    }
}

impl SymForgeServer {
    /// The `tools/call` body behind the surface gate: argument checks, evidence,
    /// dispatch, result typing and the repeat notice. Reached from `call_tool`
    /// after `enforce_compact_surface`, directly or through serve routing.
    pub(crate) async fn dispatch_gated_tool_call(
        &self,
        mut request: rmcp::model::CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
        // Feature 036 (FR-001/FR-002): an argument the tool does not define, or one
        // outside its mode, refuses the call here, BEFORE the repeat tracker observes it,
        // so a refused call can never count toward the repeat notice. A mode that a lone
        // argument selects is written into the arguments for the handler.
        let (selected_modes, value_notes) =
            match self.refuse_invalid_arguments(request.name.as_ref(), &mut request.arguments) {
                Ok(selected) => selected,
                Err(mut refusal) => {
                    // Like every other result, a refusal names the project it was judged for.
                    let evidence = self
                        .initial_project_evidence_for_call(request.arguments.as_ref())
                        .await;
                    result_status::with_project_evidence_scope(evidence, async {
                        result_status::attach_project_evidence_meta(&mut refusal.meta);
                    })
                    .await;
                    return Ok(rmcp::model::CallToolResponse::Complete(refusal));
                }
            };
        // The admitted A-019 relay deliberately returns exact legacy renderer
        // bytes with no semantic result status. Record that fact from the typed
        // request before the router consumes it: the central plain-String
        // error heuristic must not reinterpret valid source text such as a file
        // beginning `Error:`. Denied or malformed relay requests remain outside
        // this exemption and retain their typed InvalidRequest result.
        let admitted_raw_measurement_relay = request.name.as_ref() == "symforge"
            && request
                .arguments
                .as_ref()
                .and_then(|arguments| {
                    serde_json::from_value::<crate::stel::SymforgeCallInput>(
                        serde_json::Value::Object(arguments.clone()),
                    )
                    .ok()
                })
                .and_then(|input| Some((input.probe_legacy_tool?, input.probe_legacy_args?)))
                .is_some_and(|(tool, args)| Self::facade_probe_is_measurement_safe(&tool, &args));
        // Feature 032 (US1): observe the lane and fingerprint the request
        // BEFORE `ToolCallContext::new` moves it. `None` means this call never
        // touches the tracker: an inert lane (no observable session identity),
        // an ineligible tool, or a set-valued `projects` fan-out.
        //
        // F2: the tracker's incarnation epoch is read HERE, before dispatch,
        // and carried on the key. rmcp runs each request in its own task, so a
        // concurrent request's transition `clear()` can land between this read
        // and the post-dispatch record; a key stamped with the superseded
        // epoch is refused there instead of anchoring a run across the change.
        // The epoch is read under the same lock that owns the run map — one
        // owner, so a reader can never see a bumped epoch beside stale runs.
        // Read unconditionally rather than behind an eligibility pre-check so
        // `RepeatKey::observe` stays the single owner of "does this call touch
        // the tracker"; an uncontended `parking_lot` lock on a `u64` is far
        // below the per-call budget of a handler that queries the index.
        let repeat_key = repeat::RepeatKey::observe(
            repeat::SessionDiscriminator::observe(self.transport_lane, &context),
            self.repeat_tracker.lock().epoch(),
            request.name.as_ref(),
            request.arguments.as_ref(),
        );
        let initial_project_evidence = self
            .initial_project_evidence_for_call(request.arguments.as_ref())
            .await;
        let tool_name = request.name.clone();
        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
        // Task 7: bind the selected-project evidence slot for this dispatch,
        // seeded with the LOCAL bound project; the daemon proxy layer
        // overwrites it with the daemon's receipt when it answers. Statused
        // results attach whatever is current at render time.
        result_status::with_project_evidence_scope(initial_project_evidence, async {
            withheld::with_withheld_scope(async {
                // The outcome the tool's own code decided, when it recorded one.
                let (response, recorded) =
                    result_status::with_read_outcome_scope(self.tool_router.call(tcc)).await;
                // FR-319 central evidence attachment (plan D1): statused results
                // already attached evidence inside `into_call_tool_result`
                // (single-writer wins — this seam never overwrites); plain-String
                // tools gain it here, and an unbound server discloses the explicit
                // unbound marker. Runs INSIDE the scope so a daemon receipt
                // recorded during the call is what gets attached. Wildcard arm per
                // FR-A2: this server only ever emits `Complete`.
                response.map(|response| match response {
                    rmcp::model::CallToolResponse::Complete(mut result) => {
                        result_status::attach_project_evidence_meta(&mut result.meta);
                        if result.is_error == Some(true) {
                            append_required_fields_hint(
                                self.tool_router.get(&tool_name),
                                &mut result,
                            );
                        }
                        // Semantic-error typing (worktree-routing incident): most
                        // primitive tools return plain String bodies, so a
                        // routing refusal or tool error reached the wire as
                        // isError:false — an authoritative-looking "failure read
                        // as success". Reclassify centrally via the ONE shared
                        // error-shape predicate so every tool inherits it without
                        // per-handler signature churn.
                        // Covered facade steps type their own status; their
                        // bodies can contain text that resembles a status line.
                        let typed_facade_step =
                            crate::stel::planner::FacadeStepTool::from_name(tool_name.as_ref())
                                .is_some();
                        // Typed status is authoritative on covered tools. Missing
                        // status is an internal failure, never a text-classified answer.
                        if !admitted_raw_measurement_relay
                            && (recorded.is_some() || typed_facade_step)
                            && result_status::observed_outcome_class(result.meta.as_ref()).is_none()
                        {
                            let class = recorded
                                .map(|outcome| outcome.class())
                                .unwrap_or(OutcomeClass::InternalFailure);
                            if class.is_error() {
                                result.is_error = Some(true);
                            }
                            result.meta.get_or_insert_with(Default::default).0.insert(
                                result_status::RESULT_STATUS_META_KEY.to_string(),
                                serde_json::to_value(result_status::ResultStatus::new(class))
                                    .expect("ResultStatus must serialize to JSON"),
                            );
                        }
                        let typed_result = typed_facade_step || recorded.is_some();
                        if !admitted_raw_measurement_relay
                            && !typed_result
                            && result.is_error != Some(true)
                        {
                            let body = result
                                .content
                                .iter()
                                .filter_map(|block| block.as_text().map(|text| text.text.as_str()))
                                .collect::<Vec<_>>()
                                .join("\n");
                            if !body.is_empty() && tools::is_error_output(&body) {
                                result.is_error = Some(true);
                            } else if tools::is_index_unavailable_output(&body) {
                                // The index could not serve (loading, not loaded,
                                // degraded), so the call did not run. Statused tools
                                // already type this `internal_failure`; a plain-String
                                // tool reached the wire as isError:false, which reads
                                // exactly like a real empty answer. Never overwrite a
                                // status a statused tool wrote itself.
                                result.is_error = Some(true);
                                result
                                    .meta
                                    .get_or_insert_with(Default::default)
                                    .0
                                    .entry(result_status::RESULT_STATUS_META_KEY.to_string())
                                    .or_insert_with(|| {
                                        serde_json::to_value(result_status::ResultStatus::new(
                                            OutcomeClass::InternalFailure,
                                        ))
                                        .expect("ResultStatus must serialize to JSON")
                                    });
                            }
                        }
                        // Feature 036: a mode the server chose for the caller is named in
                        // the answer. After the error classification above (the note
                        // must not reach `is_error_output`), before the repeat tracker
                        // reads the body.
                        tool_contract::append_selection_note(&mut result, &selected_modes);
                        tool_contract::append_value_notes(&mut result, &value_notes);
                        // Feature 032 (US1): AFTER evidence attachment (the
                        // tracker reads the evidence this response actually
                        // carries) and AFTER the error reclassification (the
                        // notice text must never reach `is_error_output`). The
                        // lock is taken and released right here, synchronously.
                        if let Some(key) = repeat_key {
                            let observation = repeat::ServeObservation::from_result(&result);
                            let notice = self.repeat_tracker.lock().record_serve(key, observation);
                            if let Some(notice) = notice {
                                notice.attach(&mut result);
                            }
                        }
                        // Feature 034: plain-String tools may still hold pending
                        // withheld meta (statused path already drained it).
                        withheld::drain_pending_into_meta(&mut result.meta);
                        rmcp::model::CallToolResponse::Complete(result)
                    }
                    other => other,
                })
            })
            .await
        })
        .await
    }
}

/// rmcp's prefix for a tool-argument decode failure (`missing field`, wrong type).
const PARAMETER_DECODE_ERROR_PREFIX: &str = "failed to deserialize parameters:";

/// The required top-level fields of `tool`'s input schema, in schema order.
fn required_field_names(tool: &Tool) -> Vec<&str> {
    tool.input_schema
        .get("required")
        .and_then(serde_json::Value::as_array)
        .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
        .unwrap_or_default()
}

/// A parameter decode failure reaches the caller as serde text alone
/// (`missing field ...`), which does not say what the tool expects. Reword it through the
/// shared `decode_failure_text` (the embed lane prints the same bytes): serde's text first,
/// with every argument VALUE serde quoted in it removed, then one line naming the tool's
/// required top-level fields when it has any. Results that are not decode failures are
/// left byte-for-byte untouched.
fn append_required_fields_hint(tool: Option<&Tool>, result: &mut rmcp::model::CallToolResult) {
    for block in &mut result.content {
        if let rmcp::model::ContentBlock::Text(text) = block
            && let Some(message) = text.text.strip_prefix(PARAMETER_DECODE_ERROR_PREFIX)
        {
            let required = tool.map(required_field_names).unwrap_or_default();
            let name = tool.map_or("", |tool| tool.name.as_ref());
            text.text = crate::index_lifecycle::guidance::request_refusal::decode_failure_text(
                name,
                message.trim_start(),
                &required,
            );
            return;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::extract::{Path as AxumPath, State};
    use axum::http::{HeaderMap, HeaderValue, StatusCode};
    use axum::routing::post;
    use axum::{Json, Router};
    use rmcp::handler::server::wrapper::Parameters;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::net::TcpListener;

    fn only_text(result: &rmcp::model::CallToolResult) -> &str {
        match result.content.as_slice() {
            [rmcp::model::ContentBlock::Text(text)] => &text.text,
            other => panic!("expected exactly one text block, got {other:?}"),
        }
    }

    #[test]
    fn decode_error_gains_the_required_field_names_after_the_serde_text() {
        let router = SymForgeServer::tool_router();
        let serde_text = "failed to deserialize parameters: missing field `name`";
        let mut result =
            rmcp::model::CallToolResult::error(vec![rmcp::model::ContentBlock::text(serde_text)]);

        append_required_fields_hint(router.get("find_references"), &mut result);

        let text = only_text(&result);
        assert!(
            text.starts_with(serde_text),
            "serde text must stay first: {text}"
        );
        assert!(
            text.ends_with("\nRequired fields for `find_references`: name."),
            "one line naming the required fields must follow: {text}"
        );
    }

    #[test]
    fn non_decode_errors_and_unknown_tools_are_left_untouched() {
        let router = SymForgeServer::tool_router();
        let mut other = rmcp::model::CallToolResult::error(vec![rmcp::model::ContentBlock::text(
            "Error: symbol not found",
        )]);
        append_required_fields_hint(router.get("find_references"), &mut other);
        assert_eq!(only_text(&other), "Error: symbol not found");

        let mut unknown =
            rmcp::model::CallToolResult::error(vec![rmcp::model::ContentBlock::text(
                "failed to deserialize parameters: x",
            )]);
        append_required_fields_hint(router.get("no_such_tool"), &mut unknown);
        assert_eq!(only_text(&unknown), "failed to deserialize parameters: x");
    }

    #[derive(Clone)]
    struct FakeToolState {
        calls: Arc<AtomicUsize>,
        body: Arc<String>,
        read_outcome_header: Option<String>,
    }

    async fn fake_tool_handler(
        State(state): State<FakeToolState>,
        _body: axum::body::Bytes,
    ) -> (HeaderMap, String) {
        state.calls.fetch_add(1, Ordering::Relaxed);
        let mut headers = HeaderMap::new();
        if let Some(outcome) = state.read_outcome_header {
            headers.insert(
                result_status::READ_OUTCOME_HEADER,
                HeaderValue::from_str(&outcome).expect("valid fake outcome header"),
            );
        }
        (headers, state.body.as_ref().clone())
    }

    async fn spawn_fake_tool_server(
        body: &str,
    ) -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        Arc<AtomicUsize>,
        tokio::task::JoinHandle<()>,
    ) {
        spawn_fake_tool_server_with_read_outcome_header(body, None).await
    }

    async fn spawn_fake_tool_server_with_read_outcome_header(
        body: &str,
        read_outcome_header: Option<&str>,
    ) -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        Arc<AtomicUsize>,
        tokio::task::JoinHandle<()>,
    ) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind fake daemon tool server");
        let base_url = format!("http://{}", listener.local_addr().expect("listener addr"));
        let calls = Arc::new(AtomicUsize::new(0));
        let state = FakeToolState {
            calls: Arc::clone(&calls),
            body: Arc::new(body.to_string()),
            read_outcome_header: read_outcome_header.map(str::to_string),
        };
        let app = Router::new()
            .route(
                "/v1/sessions/{session_id}/tools/{tool_name}",
                post(fake_tool_handler),
            )
            .with_state(state);
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
        // Join handle: callers await after shutdown so the listen socket is gone
        // before the next suite-ordered test rebinds (SO_REUSEADDR race).
        let server_task = tokio::spawn(async move {
            let shutdown = async move {
                let _ = shutdown_rx.await;
            };
            let _ = axum::serve(listener, app)
                .with_graceful_shutdown(shutdown)
                .await;
        });
        (base_url, shutdown_tx, calls, server_task)
    }

    #[derive(Clone)]
    struct BlockingIndexFolderState {
        calls: Arc<AtomicUsize>,
        paths: Arc<Mutex<Vec<String>>>,
        first_entered: Arc<tokio::sync::Notify>,
        second_entered: Arc<tokio::sync::Notify>,
        release_first: Arc<tokio::sync::Notify>,
    }

    async fn blocking_index_folder_handler(
        State(state): State<BlockingIndexFolderState>,
        Json(args): Json<serde_json::Value>,
    ) -> String {
        let call = state.calls.fetch_add(1, Ordering::SeqCst);
        state.paths.lock().push(
            args.get("path")
                .and_then(serde_json::Value::as_str)
                .expect("index_folder path")
                .to_string(),
        );
        if call == 0 {
            state.first_entered.notify_one();
            state.release_first.notified().await;
        } else {
            state.second_entered.notify_one();
        }
        "Indexed 0 files, 0 symbols.".to_string()
    }

    async fn spawn_blocking_index_folder_server() -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        BlockingIndexFolderState,
    ) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind blocking index-folder server");
        let base_url = format!("http://{}", listener.local_addr().expect("listener addr"));
        let state = BlockingIndexFolderState {
            calls: Arc::new(AtomicUsize::new(0)),
            paths: Arc::new(Mutex::new(Vec::new())),
            first_entered: Arc::new(tokio::sync::Notify::new()),
            second_entered: Arc::new(tokio::sync::Notify::new()),
            release_first: Arc::new(tokio::sync::Notify::new()),
        };
        let app = Router::new()
            .route(
                "/v1/sessions/{session_id}/tools/index_folder",
                post(blocking_index_folder_handler),
            )
            .with_state(state.clone());
        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;
        });
        (base_url, shutdown_tx, state)
    }

    #[derive(Clone)]
    struct ProjectEchoState {
        requests: Arc<Mutex<Vec<(String, serde_json::Value)>>>,
        evidence_project_override: Option<String>,
        omit_evidence_for_tool: Option<String>,
        different_generation_for_tool: Option<String>,
        malformed_evidence_for_tool: Option<String>,
        incoherent_evidence_for_tool: Option<String>,
    }

    async fn project_echo_handler(
        AxumPath((_session_id, tool_name)): AxumPath<(String, String)>,
        State(state): State<ProjectEchoState>,
        Json(args): Json<serde_json::Value>,
    ) -> (HeaderMap, String) {
        state
            .requests
            .lock()
            .push((tool_name.clone(), args.clone()));
        let project = args
            .get("project")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("<daemon-home>");
        let evidence_project = state
            .evidence_project_override
            .as_deref()
            .unwrap_or(project);
        let canonical_root = format!("C:/FOREIGN_ROOT/{evidence_project}");
        let evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: if state.incoherent_evidence_for_tool.as_deref() == Some(tool_name.as_str())
            {
                "project-v1-incoherent".to_string()
            } else {
                crate::daemon::project_key(std::path::Path::new(&canonical_root))
            },
            project_name: evidence_project.to_string(),
            canonical_root: Some(canonical_root),
            generation: if state.different_generation_for_tool.as_deref()
                == Some(tool_name.as_str())
            {
                8
            } else {
                7
            },
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "fake-daemon".to_string(),
            index_files: 11,
            index_symbols: 13,
        };
        let mut headers = HeaderMap::new();
        if state.malformed_evidence_for_tool.as_deref() == Some(tool_name.as_str()) {
            headers.insert(
                crate::protocol::result_status::PROJECT_EVIDENCE_HEADER,
                HeaderValue::from_static("{"),
            );
        } else if state.omit_evidence_for_tool.as_deref() != Some(tool_name.as_str()) {
            headers.insert(
                crate::protocol::result_status::PROJECT_EVIDENCE_HEADER,
                HeaderValue::from_str(
                    &serde_json::to_string(&evidence).expect("serialize fake project evidence"),
                )
                .expect("fake project evidence is a valid header value"),
            );
        }
        // A current daemon types every answer it serves.
        headers.insert(
            crate::protocol::result_status::READ_OUTCOME_HEADER,
            HeaderValue::from_str(
                &serde_json::to_string(&crate::protocol::result_status::ReadOutcome::Found)
                    .expect("serialize read outcome"),
            )
            .expect("read outcome is a valid header value"),
        );
        let body = if tool_name == "index_folder" {
            "Indexed 0 files, 0 symbols.".to_string()
        } else {
            format!("selected-project={project}; tool={tool_name}")
        };
        (headers, body)
    }

    async fn spawn_project_echo_tool_server() -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        Arc<Mutex<Vec<(String, serde_json::Value)>>>,
        tokio::task::JoinHandle<()>,
    ) {
        spawn_project_echo_tool_server_with_policy(None, None, None, None, None).await
    }

    async fn spawn_project_echo_tool_server_with_evidence_project(
        evidence_project_override: Option<&str>,
    ) -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        Arc<Mutex<Vec<(String, serde_json::Value)>>>,
        tokio::task::JoinHandle<()>,
    ) {
        spawn_project_echo_tool_server_with_policy(
            evidence_project_override,
            None,
            None,
            None,
            None,
        )
        .await
    }

    async fn spawn_project_echo_tool_server_with_policy(
        evidence_project_override: Option<&str>,
        omit_evidence_for_tool: Option<&str>,
        different_generation_for_tool: Option<&str>,
        malformed_evidence_for_tool: Option<&str>,
        incoherent_evidence_for_tool: Option<&str>,
    ) -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        Arc<Mutex<Vec<(String, serde_json::Value)>>>,
        tokio::task::JoinHandle<()>,
    ) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind project echo daemon tool server");
        let base_url = format!("http://{}", listener.local_addr().expect("listener addr"));
        let requests = Arc::new(Mutex::new(Vec::new()));
        let app = Router::new()
            .route(
                "/v1/sessions/{session_id}/tools/{tool_name}",
                post(project_echo_handler),
            )
            .with_state(ProjectEchoState {
                requests: Arc::clone(&requests),
                evidence_project_override: evidence_project_override.map(str::to_string),
                omit_evidence_for_tool: omit_evidence_for_tool.map(str::to_string),
                different_generation_for_tool: different_generation_for_tool.map(str::to_string),
                malformed_evidence_for_tool: malformed_evidence_for_tool.map(str::to_string),
                incoherent_evidence_for_tool: incoherent_evidence_for_tool.map(str::to_string),
            });
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
        // Join handle: callers await after shutdown so the listen socket is gone
        // before the next suite-ordered test rebinds (SO_REUSEADDR race).
        let server_task = tokio::spawn(async move {
            let shutdown = async move {
                let _ = shutdown_rx.await;
            };
            let _ = axum::serve(listener, app)
                .with_graceful_shutdown(shutdown)
                .await;
        });
        (base_url, shutdown_tx, requests, server_task)
    }

    #[derive(Clone)]
    struct FailingAskThenEchoState {
        requests: Arc<Mutex<Vec<(String, serde_json::Value)>>>,
        ask_entered: Arc<tokio::sync::Notify>,
        release_ask: Arc<tokio::sync::Notify>,
    }

    async fn failing_ask_then_echo_handler(
        AxumPath((_session_id, tool_name)): AxumPath<(String, String)>,
        State(state): State<FailingAskThenEchoState>,
        Json(args): Json<serde_json::Value>,
    ) -> Result<String, StatusCode> {
        state
            .requests
            .lock()
            .push((tool_name.clone(), args.clone()));
        if tool_name == "ask" {
            state.ask_entered.notify_one();
            state.release_ask.notified().await;
            return Err(StatusCode::SERVICE_UNAVAILABLE);
        }

        let project = args
            .get("project")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("<daemon-active>");
        Ok(format!("selected-project={project}; tool={tool_name}"))
    }

    async fn spawn_failing_ask_then_echo_server() -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        tokio::task::JoinHandle<()>,
        FailingAskThenEchoState,
    ) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind failing ask daemon tool server");
        let base_url = format!("http://{}", listener.local_addr().expect("listener addr"));
        let state = FailingAskThenEchoState {
            requests: Arc::new(Mutex::new(Vec::new())),
            ask_entered: Arc::new(tokio::sync::Notify::new()),
            release_ask: Arc::new(tokio::sync::Notify::new()),
        };
        let app = Router::new()
            .route(
                "/v1/sessions/{session_id}/tools/{tool_name}",
                post(failing_ask_then_echo_handler),
            )
            .with_state(state.clone());
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
        let task = tokio::spawn(async move {
            let shutdown = async move {
                let _ = shutdown_rx.await;
            };
            let _ = axum::serve(listener, app)
                .with_graceful_shutdown(shutdown)
                .await;
        });
        (base_url, shutdown_tx, task, state)
    }

    #[tokio::test]
    async fn daemon_proxy_resolves_index_folder_path_once_before_dispatch_and_mirroring() {
        let cwd = std::env::current_dir().expect("test current directory");
        let target = tempfile::Builder::new()
            .prefix("symforge-index-folder-relative-")
            .tempdir_in(&cwd)
            .expect("relative index target under the adapter cwd");
        let relative = target
            .path()
            .strip_prefix(&cwd)
            .expect("temp target is beneath adapter cwd")
            .to_string_lossy()
            .into_owned();
        assert!(
            std::path::Path::new(&relative).is_relative(),
            "fixture must exercise a relative caller spelling: {relative}"
        );

        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let client_state = client.clone();
        let server = SymForgeServer::new_daemon_proxy(client);

        let result = server
            .index_folder(Parameters(crate::protocol::tools::IndexFolderInput {
                path: relative,
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(result.starts_with("Indexed 0 files"), "{result}");

        let expected = target.path().canonicalize().expect("canonical test target");
        {
            let captured = requests.lock();
            assert_eq!(captured.len(), 1);
            assert_eq!(captured[0].0, "index_folder");
            let forwarded = captured[0]
                .1
                .get("path")
                .and_then(serde_json::Value::as_str)
                .map(std::path::PathBuf::from)
                .expect("index_folder forwards a path string");
            assert!(
                forwarded.is_absolute(),
                "the daemon must never resolve the caller's relative spelling: {}",
                forwarded.display()
            );
            assert_eq!(forwarded, expected);
            assert_eq!(
                client_state.activated_root().as_deref(),
                Some(expected.as_path()),
                "the adapter ACTIVE mirror must record the exact root sent to the daemon"
            );
        }

        let missing = target.path().join("missing-project");
        let missing_relative = missing
            .strip_prefix(&cwd)
            .expect("missing target is beneath adapter cwd")
            .to_string_lossy()
            .into_owned();
        assert!(!missing.try_exists().expect("observe missing fixture"));
        let refused = server
            .index_folder(Parameters(crate::protocol::tools::IndexFolderInput {
                path: missing_relative,
                idempotency_key: None,
                add: None,
                allow_protected_root: None,
            }))
            .await;
        assert!(refused.starts_with("Path does not exist:"), "{refused}");
        assert_eq!(
            requests.lock().len(),
            1,
            "an unresolved relative path must fail before any daemon request"
        );
        assert_eq!(
            client_state.activated_root().as_deref(),
            Some(expected.as_path()),
            "a failed preflight must preserve the prior ACTIVE mirror"
        );

        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_index_folder_serializes_response_and_active_mirror_order() {
        let first_root = tempfile::TempDir::new().expect("first index root");
        let second_root = tempfile::TempDir::new().expect("second index root");
        let first_root = first_root
            .path()
            .canonicalize()
            .expect("canonical first root");
        let second_root = second_root
            .path()
            .canonicalize()
            .expect("canonical second root");
        let (base_url, shutdown, fake) = spawn_blocking_index_folder_server().await;
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let client_state = client.clone();
        let server = SymForgeServer::new_daemon_proxy(client);

        let first = tokio::spawn({
            let server = server.clone();
            let path = first_root.to_string_lossy().into_owned();
            async move {
                server
                    .index_folder(Parameters(crate::protocol::tools::IndexFolderInput {
                        path,
                        idempotency_key: None,
                        add: None,
                        allow_protected_root: None,
                    }))
                    .await
            }
        });
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            fake.first_entered.notified(),
        )
        .await
        .expect("first daemon request entered");

        // Queue a daemon-client writer behind the in-flight proxy read. Once
        // the HTTP response is released, Tokio's fair RwLock gives the queued
        // writer priority, deterministically holding the first index call in
        // the response-to-mirror gap.
        let writer_started = Arc::new(tokio::sync::Notify::new());
        let writer_acquired = Arc::new(tokio::sync::Notify::new());
        let release_writer = Arc::new(tokio::sync::Notify::new());
        let writer = tokio::spawn({
            let slot = server.daemon_client_slot().expect("daemon client slot");
            let writer_started = Arc::clone(&writer_started);
            let writer_acquired = Arc::clone(&writer_acquired);
            let release_writer = Arc::clone(&release_writer);
            async move {
                writer_started.notify_one();
                let _guard = slot.write().await;
                writer_acquired.notify_one();
                release_writer.notified().await;
            }
        });
        writer_started.notified().await;
        tokio::task::yield_now().await;
        fake.release_first.notify_one();
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            writer_acquired.notified(),
        )
        .await
        .expect("queued writer acquired after the proxy response");
        assert!(
            client_state.activation_lane().try_lock().is_err(),
            "the activation lane must remain held until the ACTIVE mirror write completes"
        );

        let second = tokio::spawn({
            let server = server.clone();
            let path = second_root.to_string_lossy().into_owned();
            async move {
                server
                    .index_folder(Parameters(crate::protocol::tools::IndexFolderInput {
                        path,
                        idempotency_key: None,
                        add: None,
                        allow_protected_root: None,
                    }))
                    .await
            }
        });
        assert!(
            tokio::time::timeout(
                std::time::Duration::from_millis(100),
                fake.second_entered.notified(),
            )
            .await
            .is_err(),
            "the second default open must not reach the daemon while the first mirror is pending"
        );

        release_writer.notify_one();
        writer.await.expect("writer task");
        let first_result = first.await.expect("first index task");
        assert!(
            first_result.starts_with("Indexed 0 files"),
            "{first_result}"
        );
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            fake.second_entered.notified(),
        )
        .await
        .expect("second daemon request entered after the first mirror");
        let second_result = second.await.expect("second index task");
        assert!(
            second_result.starts_with("Indexed 0 files"),
            "{second_result}"
        );

        assert_eq!(
            fake.paths.lock().as_slice(),
            &[
                first_root.to_string_lossy().into_owned(),
                second_root.to_string_lossy().into_owned(),
            ]
        );
        assert_eq!(
            client_state.activated_root().as_deref(),
            Some(second_root.as_path()),
            "daemon and adapter ACTIVE order must match completed call order"
        );
        let _ = shutdown.send(());
    }

    #[tokio::test]
    async fn daemon_proxy_ask_routes_the_whole_query_after_the_local_no_echo_guard() {
        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(client);

        let explicit = server
            .ask(Parameters(crate::protocol::tools::SmartQueryInput {
                project: Some("foreign-project".to_string()),
                query: "which tool should I use for impact analysis?".to_string(),
                max_tokens: None,
            }))
            .await;
        assert_eq!(
            explicit, "selected-project=foreign-project; tool=ask",
            "the selected daemon project must own ask route classification"
        );

        let implicit = server
            .ask(Parameters(crate::protocol::tools::SmartQueryInput {
                project: None,
                query: "which tool should I use for code search?".to_string(),
                max_tokens: None,
            }))
            .await;
        assert_eq!(
            implicit, "selected-project=<daemon-home>; tool=ask",
            "an omitted selector must still proxy the whole ask request"
        );

        let canary = ["runtime", "-", "ask", "-", "canary"].concat();
        let rejected = server
            .ask(Parameters(crate::protocol::tools::SmartQueryInput {
                project: Some("foreign-project".to_string()),
                query: format!("token={canary}"),
                max_tokens: None,
            }))
            .await;
        assert!(rejected.contains("sensitive query rejected"), "{rejected}");
        assert!(!rejected.contains(&canary), "sensitive input must not echo");

        {
            let captured = requests.lock();
            assert_eq!(
                captured.len(),
                2,
                "the safety guard must reject before the daemon hop"
            );
            assert!(captured.iter().all(|(tool, _)| tool == "ask"));
            assert_eq!(captured[0].1["project"], "foreign-project");
            assert!(captured[1].1["project"].is_null());
        }
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_proxy_ask_fallback_keeps_explicit_home_for_nested_route() {
        let home = tempfile::TempDir::new().expect("HOME project root");
        let sibling = tempfile::TempDir::new().expect("sibling project root");
        let home = home.path().canonicalize().expect("canonical HOME root");
        let sibling = sibling
            .path()
            .canonicalize()
            .expect("canonical sibling root");
        let home_id = crate::daemon::project_key(&home);
        let sibling_id = crate::daemon::project_key(&sibling);
        let (base_url, shutdown, daemon_task, fake) = spawn_failing_ask_then_echo_server().await;
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            home_id.clone(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        client.record_opened_root(home.clone());
        client.record_opened_root(sibling.clone());
        client.record_active_root(sibling);
        let server = SymForgeServer::new_daemon_proxy(client);
        *server.repo_root.write() = Some(home);
        {
            let mut degraded = server.daemon_degraded.lock();
            degraded.degraded = true;
            degraded.last_reconnect_attempt = Some(std::time::Instant::now());
        }

        let ask = tokio::spawn({
            let server = server.clone();
            let home_id = home_id.clone();
            async move {
                server
                    .ask(Parameters(crate::protocol::tools::SmartQueryInput {
                        project: Some(home_id),
                        query: "find symbol ask_fallback_target".to_string(),
                        max_tokens: None,
                    }))
                    .await
            }
        });
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            fake.ask_entered.notified(),
        )
        .await
        .expect("outer ask reached daemon");
        fake.release_ask.notify_one();
        let result = ask.await.expect("ask task");

        assert!(
            result.contains(&format!("selected-project={home_id}; tool=search_symbols")),
            "the nested route must stay pinned to the HOME used for fallback: {result}"
        );
        assert!(
            !result.contains(&format!("selected-project={sibling_id}")),
            "the nested route must not inherit daemon ACTIVE: {result}"
        );
        {
            let requests = fake.requests.lock();
            assert_eq!(requests.len(), 2, "outer ask plus one nested route");
            assert_eq!(requests[0].0, "ask");
            assert_eq!(requests[0].1["project"], home_id);
            assert_eq!(requests[1].0, "search_symbols");
            assert_eq!(requests[1].1["project"], home_id);
        }

        let _ = shutdown.send(());
        tokio::time::timeout(std::time::Duration::from_secs(1), daemon_task)
            .await
            .expect("fake daemon shutdown")
            .expect("fake daemon task");
    }

    #[tokio::test]
    async fn daemon_proxy_ask_fallback_pins_omitted_home_across_active_retarget() {
        let home = tempfile::TempDir::new().expect("HOME project root");
        let sibling = tempfile::TempDir::new().expect("sibling project root");
        let home = home.path().canonicalize().expect("canonical HOME root");
        let sibling = sibling
            .path()
            .canonicalize()
            .expect("canonical sibling root");
        let home_id = crate::daemon::project_key(&home);
        let sibling_id = crate::daemon::project_key(&sibling);
        let (base_url, shutdown, daemon_task, fake) = spawn_failing_ask_then_echo_server().await;
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            home_id.clone(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        client.record_opened_root(home.clone());
        client.record_opened_root(sibling.clone());
        client.record_active_root(home.clone());
        let client_state = client.clone();
        let server = SymForgeServer::new_daemon_proxy(client);
        *server.repo_root.write() = Some(home);
        {
            let mut degraded = server.daemon_degraded.lock();
            degraded.degraded = true;
            degraded.last_reconnect_attempt = Some(std::time::Instant::now());
        }

        let ask = tokio::spawn({
            let server = server.clone();
            async move {
                server
                    .ask(Parameters(crate::protocol::tools::SmartQueryInput {
                        project: None,
                        query: "find symbol ask_fallback_target".to_string(),
                        max_tokens: None,
                    }))
                    .await
            }
        });
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            fake.ask_entered.notified(),
        )
        .await
        .expect("outer ask reached daemon after snapshotting HOME");
        client_state.record_active_root(sibling);
        fake.release_ask.notify_one();
        let result = ask.await.expect("ask task");

        assert!(
            result.contains(&format!("selected-project={home_id}; tool=search_symbols")),
            "the nested route must stay pinned to the snapshotted HOME: {result}"
        );
        assert!(
            !result.contains(&format!("selected-project={sibling_id}")),
            "the nested route must not inherit the concurrently activated sibling: {result}"
        );
        {
            let requests = fake.requests.lock();
            assert_eq!(requests.len(), 2, "outer ask plus one nested route");
            assert_eq!(requests[0].0, "ask");
            assert_eq!(requests[0].1["project"], home_id);
            assert_eq!(requests[1].0, "search_symbols");
            assert_eq!(requests[1].1["project"], home_id);
        }

        let _ = shutdown.send(());
        tokio::time::timeout(std::time::Duration::from_secs(1), daemon_task)
            .await
            .expect("fake daemon shutdown")
            .expect("fake daemon task");
    }

    async fn spawn_truncated_project_evidence_server(
        evidence: crate::protocol::result_status::ProjectEvidence,
    ) -> (String, tokio::task::JoinHandle<()>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind truncated daemon tool server");
        let base_url = format!("http://{}", listener.local_addr().expect("listener addr"));
        let task = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.expect("accept daemon tool call");
            let mut request_prefix = [0u8; 4096];
            let _ = socket
                .read(&mut request_prefix)
                .await
                .expect("read daemon request prefix");
            let receipt = serde_json::to_string(&evidence).expect("serialize project evidence");
            let response = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\n{}: {}\r\n\
                 content-length: 256\r\nconnection: close\r\n\r\npartial-body",
                crate::protocol::result_status::PROJECT_EVIDENCE_HEADER,
                receipt
            );
            socket
                .write_all(response.as_bytes())
                .await
                .expect("write deliberately truncated daemon response");
            socket.shutdown().await.expect("close truncated response");
        });
        (base_url, task)
    }

    #[tokio::test]
    async fn daemon_receipt_is_not_recorded_before_body_is_observed() {
        let target_evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: "foreign-project-id".to_string(),
            project_name: "foreign-project".to_string(),
            canonical_root: Some("C:/FOREIGN_ROOT/foreign-project".to_string()),
            generation: 7,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "truncated-daemon".to_string(),
            index_files: 11,
            index_symbols: 13,
        };
        let (base_url, server_task) =
            spawn_truncated_project_evidence_server(target_evidence).await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let home_evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: "home-project-id".to_string(),
            project_name: "home-project".to_string(),
            canonical_root: Some("C:/HOME_ROOT/home-project".to_string()),
            generation: 3,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "home-seed".to_string(),
            index_files: 5,
            index_symbols: 8,
        };

        crate::protocol::result_status::with_project_evidence_scope(Some(home_evidence), async {
            // The facade clears HOME immediately before a foreign daemon hop.
            crate::protocol::result_status::clear_project_evidence();
            daemon_client
                .call_tool_value("find_references", serde_json::json!({}))
                .await
                .expect_err("a truncated response body must fail observation");
            assert!(
                crate::protocol::result_status::current_project_evidence().is_none(),
                "a receipt is not trustworthy until its response body is fully observed"
            );
        })
        .await;
        server_task.await.expect("truncated daemon server task");
    }

    #[tokio::test]
    async fn daemon_proxy_success_without_receipt_does_not_reuse_home_evidence() {
        // Isolation: seed coherent HOME evidence (project_id == project_key(root))
        // so a missed clear-at-hop cannot hide behind validate()'s incoherence
        // reject. Use a private control-state dir via new_for_test_at so this
        // case never shares the process-global OnceLock placement with sibling
        // daemon tests. Await the fake server JoinHandle after shutdown so the
        // listen socket is gone before the next suite-ordered test rebinds.
        let control_home = tempfile::TempDir::new().expect("isolated control-state home");
        let control_state = crate::domain::ControlStateDir::new(control_home.path().to_path_buf());
        let (base_url, shutdown, calls, server_task) =
            spawn_fake_tool_server("daemon-read-without-receipt").await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test_at(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
            control_state,
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let home_root = tempfile::TempDir::new().expect("coherent home root");
        let home_root_path = home_root.path().to_path_buf();
        let home_id = crate::daemon::project_key(&home_root_path);
        let home_canon = crate::daemon::normalized_path_string(&home_root_path);
        let home_evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: home_id,
            project_name: "home-project".to_string(),
            canonical_root: Some(home_canon),
            generation: 3,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "home-seed".to_string(),
            index_files: 5,
            index_symbols: 8,
        };

        crate::protocol::result_status::with_project_evidence_scope(Some(home_evidence), async {
            let body = server
                .proxy_tool_call("find_references", &serde_json::json!({ "name": "cfg_if" }))
                .await;
            assert_eq!(body.as_deref(), Some("daemon-read-without-receipt"));
            let leftover = crate::protocol::result_status::current_project_evidence();
            assert!(
                leftover.is_none(),
                "a successful proxy response without a daemon receipt must not reuse HOME; leftover={leftover:?}"
            );
        })
        .await;
        assert_eq!(calls.load(Ordering::Relaxed), 1);
        let _ = shutdown.send(());
        server_task.await.expect("fake tool server task");
        drop((control_home, home_root));
    }

    #[tokio::test]
    async fn daemon_proxy_facade_calls_fail_closed_on_missing_or_malformed_outcome_header() {
        for (header, body) in [
            (
                None,
                "Error: this source file begins with an error-like line",
            ),
            (
                Some("{"),
                "Index is loading... this is source text, not daemon status",
            ),
            (None, "No matches found for query `Error: missing file`"),
        ] {
            let control_home = tempfile::TempDir::new().expect("isolated control-state home");
            let control_state =
                crate::domain::ControlStateDir::new(control_home.path().to_path_buf());
            let (base_url, shutdown, calls, server_task) =
                spawn_fake_tool_server_with_read_outcome_header(body, header).await;
            let daemon_client = crate::daemon::DaemonSessionClient::new_for_test_at(
                base_url,
                "home-project-id".to_string(),
                "session-id".to_string(),
                "home-project".to_string(),
                control_state,
            );
            let server = SymForgeServer::new_daemon_proxy(daemon_client);

            let result = server
                .get_file_content_tool(Parameters(
                    serde_json::from_value(serde_json::json!({ "path": "notes/error.txt" }))
                        .expect("file content input"),
                ))
                .await
                .expect("get_file_content tool result");
            assert_eq!(only_text(&result), body);
            assert_eq!(result.is_error, Some(true));
            assert_eq!(
                result_status::observed_outcome_class(result.meta.as_ref()),
                Some(result_status::OutcomeClass::InternalFailure)
            );

            let (facade_body, facade_class) = server
                .facade_step(
                    "get_file_content",
                    serde_json::json!({ "path": "notes/error.txt" }),
                )
                .await;
            assert_eq!(facade_body, body);
            assert_eq!(facade_class, result_status::OutcomeClass::InternalFailure);

            let uri = "symforge://file/content?path=notes%2Ferror.txt";
            let resource_error = server
                .read_resource_uri(uri)
                .await
                .expect_err("typed read without a valid outcome must fail closed");
            assert_eq!(resource_error.code, rmcp::model::ErrorCode::INTERNAL_ERROR);
            assert_eq!(resource_error.message, body);
            assert_eq!(
                resource_error.data,
                Some(serde_json::json!({
                    "uri": uri,
                    "reason": "index_unavailable",
                    "retryable": false,
                }))
            );

            for tool in crate::stel::planner::FacadeStepTool::ALL {
                let tool = tool.as_str();
                let (proxied_body, outcome) = result_status::with_read_outcome_scope(
                    server.proxy_tool_call(tool, &serde_json::json!({})),
                )
                .await;
                assert_eq!(proxied_body.as_deref(), Some(body), "{tool}");
                assert_eq!(
                    outcome.map(result_status::ReadOutcome::class),
                    Some(result_status::OutcomeClass::InternalFailure),
                    "{tool} must not classify source text when its typed header is absent or malformed"
                );
            }

            assert_eq!(
                calls.load(Ordering::Relaxed),
                3 + crate::stel::planner::FacadeStepTool::ALL.len(),
            );
            let _ = shutdown.send(());
            server_task.await.expect("fake daemon tool server task");
            drop(control_home);
        }
    }

    #[tokio::test]
    async fn daemon_proxy_rejects_mismatched_or_set_valued_project_evidence() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_evidence_project(Some("home-project")).await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let home_evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: "home-project-id".to_string(),
            project_name: "home-project".to_string(),
            canonical_root: Some("C:/HOME".to_string()),
            generation: 3,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "home-seed".to_string(),
            index_files: 5,
            index_symbols: 8,
        };
        let cases = [
            serde_json::json!({
                "path": "src/lib.rs",
                "project": "foreign-project",
            }),
            serde_json::json!({
                "query": "thing",
                "projects": ["foreign-project", "other-project"],
            }),
            serde_json::json!({
                "query": "thing",
                "project": 7,
            }),
            serde_json::json!({
                "query": "thing",
                "projects": [],
            }),
            serde_json::json!({
                "query": "thing",
                "projects": [""],
            }),
            serde_json::json!({
                "query": "thing",
                "projects": "foreign-project",
            }),
        ];

        for params in cases {
            let (body, evidence, meta) =
                crate::protocol::result_status::with_project_evidence_scope(
                    Some(home_evidence.clone()),
                    async {
                        let body = server
                            .proxy_tool_call("search_text", &params)
                            .await
                            .expect("fake daemon response");
                        let evidence = crate::protocol::result_status::current_project_evidence();
                        let mut meta = None;
                        crate::protocol::result_status::attach_project_evidence_meta(&mut meta);
                        (body, evidence, meta)
                    },
                )
                .await;
            assert!(body.contains("tool=search_text"), "fake body: {body}");
            assert!(
                evidence.is_none(),
                "a scalar mismatch or set-valued result cannot carry one project receipt"
            );
            let meta = serde_json::to_value(meta).expect("serialize project evidence metadata");
            assert_eq!(
                meta["symforge/project_evidence"],
                serde_json::json!({
                    "bound": false,
                    "reason": "project_evidence_unavailable",
                }),
                "the public seam must disclose unavailable evidence exactly: {meta}"
            );
        }
        assert_eq!(requests.lock().len(), 6);
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_proxy_binds_an_omitted_selector_to_the_active_project() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_evidence_project(Some("home-project")).await;
        let active = tempfile::TempDir::new().expect("active sibling root");
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        client.record_opened_root(active.path().to_path_buf());
        client.record_active_root(active.path().to_path_buf());
        let expected_active_id = client.active_project_id();
        assert_ne!(expected_active_id, client.project_id());
        let server = SymForgeServer::new_daemon_proxy(client);

        let (body, evidence, meta) =
            crate::protocol::result_status::with_project_evidence_scope(None, async {
                let body = server
                    .proxy_tool_call(
                        "replace_symbol_body",
                        &serde_json::json!({
                            "path": "src/lib.rs",
                            "name": "thing",
                            "body": "fn thing() {}",
                            "project": null,
                        }),
                    )
                    .await
                    .expect("fake daemon response");
                let evidence = crate::protocol::result_status::current_project_evidence();
                let mut meta = None;
                crate::protocol::result_status::attach_project_evidence_meta(&mut meta);
                (body, evidence, meta)
            })
            .await;

        assert!(
            body.contains("tool=replace_symbol_body"),
            "fake body: {body}"
        );
        assert!(
            evidence.is_none(),
            "an omitted selector must accept only the ACTIVE project's canonical receipt"
        );
        let meta = serde_json::to_value(meta).expect("serialize project evidence metadata");
        assert_eq!(
            meta["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            })
        );
        {
            let captured = requests.lock();
            assert_eq!(captured.len(), 1);
            assert_eq!(
                captured[0].1["project"], expected_active_id,
                "the omitted edit must be pinned to the ACTIVE snapshot before dispatch"
            );
        }

        for tool_name in [
            "inspect_match",
            "checkpoint_now",
            "detect_impact",
            "conventions",
            "health",
            "health_compact",
            "status",
            "context_inventory",
            "symforge_retrieve",
        ] {
            let body = server
                .proxy_tool_call(tool_name, &serde_json::json!({}))
                .await
                .expect("fake daemon response");
            assert!(body.contains(&format!("tool={tool_name}")), "{body}");
        }
        {
            let requests = requests.lock();
            assert_eq!(requests.len(), 10);
            for (tool_name, args) in requests.iter().skip(1) {
                assert_eq!(
                    args[crate::daemon::PRIVATE_PROJECT_ROUTE_PIN],
                    expected_active_id,
                    "selector-less {tool_name} must carry the canonical ACTIVE snapshot"
                );
                assert!(
                    args.get("project").is_none(),
                    "the private route pin must not widen the public {tool_name} schema"
                );
            }
        }
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn call_scope_does_not_seed_home_evidence_for_omitted_active_sibling_requests() {
        let active = tempfile::TempDir::new().expect("active sibling root");
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            "http://127.0.0.1:1".to_string(),
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        client.record_opened_root(active.path().to_path_buf());
        client.record_active_root(active.path().to_path_buf());
        let server = SymForgeServer::new_daemon_proxy(client);
        let omitted = serde_json::json!({"query": "invalid early request"})
            .as_object()
            .expect("arguments object")
            .clone();
        assert!(
            server
                .initial_project_evidence_for_call(Some(&omitted))
                .await
                .is_none(),
            "an omitted selector targets ACTIVE, so an active sibling cannot inherit HOME evidence"
        );
    }

    #[tokio::test]
    async fn daemon_proxy_rejects_a_coherent_receipt_for_an_unresolved_selector() {
        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let active = tempfile::TempDir::new().expect("active sibling root");
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        client.record_opened_root(active.path().to_path_buf());
        client.record_active_root(active.path().to_path_buf());
        let server = SymForgeServer::new_daemon_proxy(client);

        crate::protocol::result_status::with_project_evidence_scope(None, async {
            let body = server
                .proxy_tool_call(
                    "search_text",
                    &serde_json::json!({
                        "query": "thing",
                        "project": "not-an-open-project",
                    }),
                )
                .await
                .expect("fake daemon response");
            assert!(body.contains("selected-project=not-an-open-project"));
            assert!(
                crate::protocol::result_status::current_project_evidence().is_none(),
                "a syntactically coherent receipt cannot authorize an unresolved selector"
            );
        })
        .await;
        assert_eq!(requests.lock().len(), 1);
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_proxy_never_falls_back_to_home_for_an_active_sibling() {
        let active = tempfile::TempDir::new().expect("active sibling root");
        let client = crate::daemon::DaemonSessionClient::new_for_test(
            "http://127.0.0.1:1".to_string(),
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        client.record_opened_root(active.path().to_path_buf());
        client.record_active_root(active.path().to_path_buf());
        assert!(!client.active_project_is_home());
        let server = SymForgeServer::new_daemon_proxy(client);
        {
            let mut degraded = server.daemon_degraded.lock();
            degraded.degraded = true;
            degraded.last_reconnect_attempt = Some(std::time::Instant::now());
        }

        let (result, evidence) = crate::protocol::result_status::with_project_evidence_scope(
            server.local_project_evidence(),
            async {
                let result = server
                    .proxy_tool_call(
                        "search_text",
                        &serde_json::json!({"query": "active sibling marker"}),
                    )
                    .await;
                let evidence = crate::protocol::result_status::current_project_evidence();
                (result, evidence)
            },
        )
        .await;
        let refusal = result.expect(
            "an unqualified ACTIVE-sibling call must refuse instead of falling back to HOME",
        );
        assert!(
            refusal.starts_with("Error: project_routing:")
                && refusal.contains("ACTIVE daemon project"),
            "unexpected active-project fallback refusal: {refusal}"
        );
        assert!(
            evidence.is_none(),
            "a failed ACTIVE-sibling route must never retain HOME evidence"
        );
    }

    /// Feature 032 (F3): repeat runs accumulate only on a lane an entry point
    /// positively DECLARED single-client. Every constructor therefore leaves
    /// the lane shared/inert; only [`SymForgeServer::with_stdio_transport_lane`]
    /// moves it, and only the two stdio entry points in `src/cli/entry.rs`
    /// call that. A new transport that forgets to declare itself gets no
    /// notice rather than one shared accumulating bucket.
    #[test]
    fn constructed_servers_default_to_an_inert_transport_lane() {
        let local = make_local_server(None);
        assert_eq!(
            local.transport_lane,
            repeat::TransportLane::Shared,
            "new_with_state_placement must leave the lane inert"
        );
        assert_eq!(
            local.clone().transport_lane,
            repeat::TransportLane::Shared,
            "a clone (the HTTP factory clones per request) inherits the lane"
        );

        let proxy =
            SymForgeServer::new_daemon_proxy(crate::daemon::DaemonSessionClient::new_for_test(
                "http://127.0.0.1:1".to_string(),
                "project-id".to_string(),
                "session-id".to_string(),
                "project-name".to_string(),
            ));
        assert_eq!(
            proxy.transport_lane,
            repeat::TransportLane::Shared,
            "new_daemon_proxy_with_state_placement must leave the lane inert"
        );

        // Positive control: the declaration is what moves it, and it survives
        // the clone the transports take.
        let declared = local.with_stdio_transport_lane();
        assert_eq!(declared.transport_lane, repeat::TransportLane::Stdio);
        assert_eq!(
            declared.clone().transport_lane,
            repeat::TransportLane::Stdio
        );
    }

    /// Feature 032 (F2): seed one repeat run at count 2 on `server`, as the
    /// seam would after two identical eligible serves, and return its key.
    fn seed_repeat_run(server: &SymForgeServer) -> repeat::RepeatKey {
        let args: rmcp::model::JsonObject =
            serde_json::from_value(serde_json::json!({ "query": "anchor" })).expect("object");
        let epoch = server.repeat_tracker.lock().epoch();
        let key = repeat::RepeatKey::observe(
            repeat::LaneWitness::assume(repeat::SessionDiscriminator::Stdio),
            epoch,
            "search_symbols",
            Some(&args),
        )
        .expect("an eligible stdio call keys the tracker");
        let evidence = result_status::ProjectEvidence {
            project_id: "project-v1-seed".to_string(),
            project_name: "seed".to_string(),
            canonical_root: Some("C:/seed".to_string()),
            generation: 1,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "memory".to_string(),
            index_files: 1,
            index_symbols: 1,
        };
        let observed = || {
            repeat::ServeObservation::observed_for_test(repeat::ObservedServe::for_test(
                evidence.clone(),
                &[rmcp::model::ContentBlock::text("body")],
            ))
        };
        let mut tracker = server.repeat_tracker.lock();
        assert!(tracker.record_serve(key.clone(), observed()).is_none());
        assert!(tracker.record_serve(key.clone(), observed()).is_none());
        assert_eq!(tracker.len(), 1, "one run seeded at count 2");
        key
    }

    #[tokio::test]
    async fn daemon_degraded_clears_on_next_success() {
        let (base_url, shutdown, calls, server_task) = spawn_fake_tool_server("daemon-ok").await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        server.daemon_degraded.lock().degraded = true;
        // Feature 032 (F2): runs accumulated while degraded (locally served)
        // must not survive the switch back to daemon-served responses.
        let _seeded = seed_repeat_run(&server);

        let result = server
            .proxy_tool_call("health", &serde_json::json!({}))
            .await;
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");

        assert_eq!(result.as_deref(), Some("daemon-ok"));
        assert_eq!(
            calls.load(Ordering::Relaxed),
            1,
            "degraded proxy should still probe the daemon once"
        );
        assert!(
            !server.daemon_degraded.lock().degraded,
            "successful proxy call should clear daemon_degraded"
        );
        assert!(
            server.repeat_tracker.lock().is_empty(),
            "the degraded -> daemon-served transition must clear every repeat run"
        );
    }

    /// Feature 032 (F2): the FIRST daemon failure of a healthy adapter flips
    /// serving from the daemon to a local fallback (or a replacement daemon).
    /// Runs observed against the dead daemon's index must not survive it: a
    /// replacement can return evidence byte-equal to the dead daemon's
    /// (generation is a per-process counter).
    #[tokio::test]
    async fn daemon_failure_transition_clears_repeat_runs() {
        // No listener on port 1: the probe fails fast, the reconnect fails
        // (auto-spawn disabled in tests), and the call falls back locally.
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            "http://127.0.0.1:1".to_string(),
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        assert!(!server.daemon_degraded.lock().degraded, "starts healthy");
        let _seeded = seed_repeat_run(&server);

        let result = server
            .proxy_tool_call("health", &serde_json::json!({}))
            .await;

        assert!(result.is_none(), "the failed daemon falls back locally");
        assert!(server.daemon_degraded.lock().degraded);
        assert!(
            server.repeat_tracker.lock().is_empty(),
            "the daemon-served -> locally-served transition must clear every repeat run"
        );
    }

    /// Sticky-degraded fix: inside the reconnect cooldown a degraded client
    /// serves the local fallback WITHOUT a reconnect attempt (no storm);
    /// observable via the untouched attempt marker.
    #[tokio::test]
    async fn degraded_dead_endpoint_respects_reconnect_cooldown() {
        // No listener on port 1: the probe fails fast with a connect error.
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            "http://127.0.0.1:1".to_string(),
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let attempt = std::time::Instant::now();
        {
            let mut state = server.daemon_degraded.lock();
            state.degraded = true;
            state.last_reconnect_attempt = Some(attempt);
        }

        let result = server
            .proxy_tool_call("health", &serde_json::json!({}))
            .await;

        assert!(result.is_none(), "cooldown must serve the local fallback");
        let state = server.daemon_degraded.lock();
        assert!(state.degraded, "failed probe keeps the degraded state");
        assert_eq!(
            state.last_reconnect_attempt,
            Some(attempt),
            "cooldown must suppress the reconnect attempt (no storm)"
        );
        assert_eq!(
            state.last_endpoint.as_deref(),
            Some("http://127.0.0.1:1"),
            "the failed endpoint must be recorded for health"
        );
    }

    /// Sticky-degraded fix: PAST the cooldown a degraded client MUST attempt
    /// bounded rediscovery (reconnect) instead of probing the dead endpoint
    /// forever. Here the replacement is absent (auto-spawn disabled in
    /// tests), so the attempt fails — but it must be ATTEMPTED, which the
    /// bumped attempt marker proves.
    #[tokio::test]
    async fn degraded_dead_endpoint_rediscovers_after_cooldown() {
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            "http://127.0.0.1:1".to_string(),
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let past_attempt = std::time::Instant::now()
            - DAEMON_RECONNECT_COOLDOWN
            - std::time::Duration::from_secs(1);
        {
            let mut state = server.daemon_degraded.lock();
            state.degraded = true;
            state.last_reconnect_attempt = Some(past_attempt);
        }

        let result = server
            .proxy_tool_call("health", &serde_json::json!({}))
            .await;

        assert!(
            result.is_none(),
            "failed rediscovery still falls back local"
        );
        let state = server.daemon_degraded.lock();
        let bumped = state
            .last_reconnect_attempt
            .expect("past cooldown must attempt bounded rediscovery");
        assert!(
            bumped > past_attempt,
            "the reconnect attempt marker must advance past the cooldown"
        );
        assert!(
            state.degraded,
            "failed rediscovery keeps the degraded state"
        );
    }

    /// Feature 013 US1 (T021): a daemon-PROXY server with a durable
    /// `StelLedgerStore` attached records the `symforge` economics event through
    /// to that store. This is the load-bearing invariant the daemon-default
    /// stdio wiring relies on: in the operator's real (daemon-backed) deployment
    /// the `symforge` compact tool — the ONLY ledger-recording tool — runs on
    /// the PROXY (the daemon worker's `execute_tool_call` has no `symforge`
    /// arm), so the durable store must be attached on the proxy path
    /// (`run_remote_mcp_server_async`) for durable accumulation to work. Here a
    /// fake daemon returns the served body for proxied primitives; the proxy
    /// itself captures the economics and write-throughs to the attached store.
    ///
    /// We call `symforge_stel_handler` directly (the inner handler, below the
    /// `SYMFORGE_SURFACE` facade gate) so the test needs no process-global env
    /// mutation and is deterministic under the parallel harness.
    #[tokio::test]
    async fn daemon_proxy_with_durable_store_records_symforge_event_through() {
        // Fake daemon returns a non-empty body for any proxied primitive so the
        // serve path produces a real served body to finalize.
        let (base_url, shutdown, _calls, server_task) =
            spawn_fake_tool_server("references to cfg_if:\n  src/lib.rs:1").await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );

        // Attach an in-memory durable store on the PROXY path — exactly what
        // `run_remote_mcp_server_async` does (T021), just in-memory for the test.
        let store = Arc::new(
            crate::stel::ledger_store::StelLedgerStore::open_in_memory("stdio-daemon-test")
                .expect("in-memory durable store"),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client)
            .with_stel_ledger_store(Arc::clone(&store));

        // The proxy holds the store; durable accumulation starts at zero.
        assert_eq!(store.summary().expect("summary").total_events, 0);

        // Drive a real economics invocation through the inner handler (skips the
        // env-gated facade). The proxy fetches the served body from the fake
        // daemon, then captures + write-throughs the economics event.
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            ..Default::default()
        };
        let _ = server
            .symforge_stel_handler(&request)
            .await
            .expect("symforge_stel_handler dispatch");
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");

        // The in-memory ledger recorded one event synchronously...
        assert_eq!(
            server.stel_ledger().lock().len(),
            1,
            "the proxy's in-memory ledger must record the event"
        );

        // ...and the DURABLE store on the proxy eventually holds it (the write is
        // offloaded onto spawn_blocking — poll briefly). This is the T021 proof:
        // durable accumulation works on the daemon-backed stdio path.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let total = loop {
            let total = store.summary().map(|s| s.total_events).unwrap_or(0);
            if total >= 1 || std::time::Instant::now() >= deadline {
                break total;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        };
        assert_eq!(
            total, 1,
            "the durable store attached on the daemon-proxy path must record the symforge event"
        );
        let recent = store.recent(10).expect("recent durable rows");
        assert_eq!(recent.len(), 1);
        assert_eq!(
            recent[0].session_id, "stdio-daemon-test",
            "the durable row carries the proxy store's session id"
        );
    }

    #[tokio::test]
    async fn daemon_facade_omission_routes_active_selectorless_steps_without_public_project() {
        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let active = tempfile::tempdir().expect("active project root");
        let active_root = active.path().canonicalize().expect("canonical active root");
        let active_id = crate::daemon::project_key(&active_root);
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        daemon_client.record_opened_root(active_root.clone());
        daemon_client.record_active_root(active_root);
        let server = SymForgeServer::new_daemon_proxy(daemon_client);

        for (query, intent) in [
            (
                "show the repository blast radius",
                crate::stel::IntentBucket::Impact,
            ),
            (
                "show current context inventory",
                crate::stel::IntentBucket::Meta,
            ),
        ] {
            let request = crate::stel::StelRequest {
                query: query.to_string(),
                intent: Some(intent),
                ..Default::default()
            };
            let result = server
                .symforge_stel_handler(&request)
                .await
                .expect("omitted-project facade dispatch");
            let serialized = serde_json::to_value(&result).expect("serialize facade result");
            let text = serialized["content"][0]["text"]
                .as_str()
                .expect("facade result text");
            assert!(
                !text.contains("cannot be routed through this plan"),
                "an omitted selector must use session routing instead of the explicit-selector refusal: {text}"
            );
        }

        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
        let captured = requests.lock();
        assert_eq!(captured.len(), 2, "both selectorless plans must dispatch");
        assert_eq!(captured[0].0, "detect_impact");
        assert_eq!(
            captured[0]
                .1
                .get(crate::daemon::PRIVATE_PROJECT_ROUTE_PIN)
                .and_then(serde_json::Value::as_str),
            Some(active_id.as_str()),
            "selectorless project-bound tools use the private ACTIVE pin"
        );
        assert!(captured[0].1.get("project").is_none());
        assert_eq!(captured[1].0, "context_inventory");
        assert!(captured[1].1.get("project").is_none());
        assert_eq!(
            captured[1]
                .1
                .get(crate::daemon::PRIVATE_PROJECT_ROUTE_PIN)
                .and_then(serde_json::Value::as_str),
            Some(active_id.as_str()),
            "selectorless session metadata is privately pinned to the snapshotted ACTIVE project"
        );
    }

    #[tokio::test]
    async fn daemon_facade_routes_foreign_project_into_served_primitive() {
        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        server.daemon_degraded.lock().degraded = true;
        let home_root = tempfile::tempdir().expect("home-project root");
        server.set_repo_root(Some(home_root.path().to_path_buf()));
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(
            None,
            server.symforge_stel_handler(&request),
        )
        .await
        .expect("healthy daemon facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("facade result has text");
        let home = home_root.path().display().to_string().replace('\\', "/");
        assert!(
            text.contains("project_root: C:/FOREIGN_ROOT/foreign-project"),
            "the facade must render the selected daemon project's root receipt: {text}"
        );
        assert!(
            !text.contains(&format!("project_root: {home}")),
            "the facade must not label a foreign result with its home root: {text}"
        );
        let evidence = &serialized["_meta"]["symforge/project_evidence"];
        assert_eq!(
            evidence["project_name"], "foreign-project",
            "typed evidence must name the selected daemon project: {serialized}"
        );
        assert_eq!(
            evidence["canonical_root"], "C:/FOREIGN_ROOT/foreign-project",
            "typed evidence must carry the selected daemon root: {serialized}"
        );
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");

        let requests = requests.lock();
        assert_eq!(
            requests.len(),
            1,
            "the healthy daemon facade must dispatch exactly one planned primitive"
        );
        let (tool, args) = &requests[0];
        assert_eq!(tool, "find_references");
        assert_eq!(
            args.get("project").and_then(serde_json::Value::as_str),
            Some("foreign-project"),
            "the facade must inject the selected project before daemon dispatch"
        );
        assert!(
            server.daemon_degradation_snapshot().is_none(),
            "a successful routed probe must recover the compact facade"
        );
    }

    #[tokio::test]
    async fn daemon_facade_never_reuses_home_evidence_when_foreign_receipt_is_missing() {
        let (base_url, shutdown, calls, server_task) =
            spawn_fake_tool_server("references to cfg_if:\n  foreign/src/lib.rs:1").await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let home_root = tempfile::tempdir().expect("home-project root");
        server.set_repo_root(Some(home_root.path().to_path_buf()));
        let home = home_root.path().display().to_string().replace('\\', "/");
        let home_evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: "home-project-id".to_string(),
            project_name: "home-project".to_string(),
            canonical_root: Some(home.clone()),
            generation: 3,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "home-seed".to_string(),
            index_files: 5,
            index_symbols: 8,
        };
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(
            Some(home_evidence),
            async {
                let mut result = server.symforge_stel_handler(&request).await?;
                crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
                Ok::<_, rmcp::ErrorData>(result)
            },
        )
        .await
        .expect("foreign facade dispatch without daemon evidence receipt");
        let serialized = serde_json::to_value(&result).expect("serialize foreign facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign facade result has text");
        assert!(
            text.contains(
                "project_root: (routed project foreign-project; daemon receipt unavailable)"
            ),
            "missing target evidence must be disclosed without substituting HOME: {text}"
        );
        assert!(
            !text.contains(&home),
            "foreign response body must never inherit the adapter home root: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "foreign result without a target receipt must disclose unavailable evidence: {serialized}"
        );
        assert_eq!(calls.load(Ordering::Relaxed), 1);
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_rejects_a_mismatched_foreign_project_receipt() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_evidence_project(Some("home-project")).await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(None, async {
            let mut result = server.symforge_stel_handler(&request).await?;
            crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
            Ok::<_, rmcp::ErrorData>(result)
        })
        .await
        .expect("foreign facade dispatch with mismatched daemon receipt");
        let serialized = serde_json::to_value(&result).expect("serialize foreign facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign facade result has text");
        assert!(
            text.contains(
                "project_root: (routed project foreign-project; daemon receipt unavailable)"
            ),
            "a mismatched receipt must be rejected rather than relabeled: {text}"
        );
        assert!(
            !text.contains("C:/FOREIGN_ROOT/home-project"),
            "a mismatched receipt must not leak into the response body: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "a mismatched receipt must disclose unavailable typed evidence: {serialized}"
        );
        assert_eq!(requests.lock().len(), 1);
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_requires_one_consistent_receipt_for_every_foreign_step() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_policy(
                None,
                Some("search_files"),
                None,
                None,
                None,
            )
            .await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let request = crate::stel::StelRequest {
            query: "widget routing".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(None, async {
            let mut result = server.symforge_stel_handler(&request).await?;
            crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
            Ok::<_, rmcp::ErrorData>(result)
        })
        .await
        .expect("foreign fused-find facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize foreign facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign facade result has text");
        assert!(
            text.contains("selected-project=foreign-project; tool=search_files")
                && text.contains("selected-project=foreign-project; tool=search_text"),
            "both foreign steps must remain visible in the semantic body: {text}"
        );
        assert!(
            text.contains(
                "project_root: (routed project foreign-project; daemon receipt unavailable)"
            ),
            "one unattested step makes the aggregate receipt unavailable: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "the public seam must disclose unavailable aggregate evidence exactly: {serialized}"
        );
        {
            let captured = requests.lock();
            assert_eq!(captured.len(), 2);
            assert_eq!(captured[0].0, "search_files");
            assert_eq!(captured[1].0, "search_text");
        }
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_requires_one_consistent_receipt_for_every_home_step() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_policy(
                None,
                Some("search_files"),
                None,
                None,
                None,
            )
            .await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let request = crate::stel::StelRequest {
            query: "widget routing".to_string(),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(None, async {
            let mut result = server.symforge_stel_handler(&request).await?;
            crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
            Ok::<_, rmcp::ErrorData>(result)
        })
        .await
        .expect("home fused-find facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize home facade result");
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "one unattested HOME step makes the aggregate receipt unavailable: {serialized}"
        );
        {
            let captured = requests.lock();
            assert_eq!(captured.len(), 2);
            assert_eq!(captured[0].0, "search_files");
            assert_eq!(captured[1].0, "search_text");
        }
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_rejects_same_project_receipts_from_different_generations() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_policy(None, None, Some("search_text"), None, None)
                .await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let request = crate::stel::StelRequest {
            query: "widget routing".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(None, async {
            let mut result = server.symforge_stel_handler(&request).await?;
            crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
            Ok::<_, rmcp::ErrorData>(result)
        })
        .await
        .expect("foreign fused-find facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize foreign facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign facade result has text");
        assert!(
            text.contains(
                "project_root: (routed project foreign-project; daemon receipt unavailable)"
            ),
            "same-project receipts from different generations cannot attest one body: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "cross-generation aggregate evidence must be unavailable: {serialized}"
        );
        {
            let captured = requests.lock();
            assert_eq!(captured.len(), 2);
            assert_eq!(captured[0].0, "search_files");
            assert_eq!(captured[1].0, "search_text");
        }
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_does_not_reuse_home_evidence_for_a_malformed_receipt() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_policy(
                None,
                None,
                None,
                Some("find_references"),
                None,
            )
            .await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let home_evidence = crate::protocol::result_status::ProjectEvidence {
            project_id: "home-project-id".to_string(),
            project_name: "home-project".to_string(),
            canonical_root: Some("C:/HOME".to_string()),
            generation: 3,
            index_state: "Ready".to_string(),
            trust: "Ready".to_string(),
            load_source: "home-seed".to_string(),
            index_files: 5,
            index_symbols: 8,
        };
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(
            Some(home_evidence),
            async {
                let mut result = server.symforge_stel_handler(&request).await?;
                crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
                Ok::<_, rmcp::ErrorData>(result)
            },
        )
        .await
        .expect("foreign facade dispatch with malformed receipt");
        let serialized = serde_json::to_value(&result).expect("serialize foreign facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign facade result has text");
        assert!(
            text.contains(
                "project_root: (routed project foreign-project; daemon receipt unavailable)"
            ) && !text.contains("C:/HOME"),
            "malformed target evidence must never retain HOME: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "malformed target evidence must be unavailable at the public seam: {serialized}"
        );
        assert_eq!(requests.lock().len(), 1);
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_rejects_a_selector_matching_receipt_with_an_incoherent_root() {
        let (base_url, shutdown, requests, server_task) =
            spawn_project_echo_tool_server_with_policy(
                None,
                None,
                None,
                None,
                Some("find_references"),
            )
            .await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };

        let result = crate::protocol::result_status::with_project_evidence_scope(None, async {
            let mut result = server.symforge_stel_handler(&request).await?;
            crate::protocol::result_status::attach_project_evidence_meta(&mut result.meta);
            Ok::<_, rmcp::ErrorData>(result)
        })
        .await
        .expect("foreign facade dispatch with incoherent receipt");
        let serialized = serde_json::to_value(&result).expect("serialize foreign facade result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign facade result has text");
        assert!(
            text.contains(
                "project_root: (routed project foreign-project; daemon receipt unavailable)"
            ),
            "a selector name cannot bless an incoherent ID/root pair: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"],
            serde_json::json!({
                "bound": false,
                "reason": "project_evidence_unavailable",
            }),
            "an incoherent receipt must be unavailable: {serialized}"
        );
        assert_eq!(requests.lock().len(), 1);
        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_never_augments_foreign_impact_with_home_cochanges() {
        use crate::live_index::git_temporal::{
            CoChangeEntry, CommitSummary, GitFileHistory, GitTemporalIndex, GitTemporalState,
            GitTemporalStats,
        };

        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        let home_root = tempfile::tempdir().expect("home-project root");
        server.set_repo_root(Some(home_root.path().to_path_buf()));
        let home_history = GitFileHistory {
            commit_count: 7,
            churn_score: 0.9,
            last_commit: CommitSummary {
                hash: "abc1234".to_string(),
                timestamp: "2026-06-01T12:00:00Z".to_string(),
                author: "Tester".to_string(),
                message_head: "touch widget".to_string(),
                days_ago: 2.0,
            },
            contributors: vec![],
            co_changes: vec![CoChangeEntry {
                path: "src/HOME_ONLY_PARTNER.rs".to_string(),
                coupling_score: 0.71,
                shared_commits: 5,
            }],
            weak_co_changes: vec![],
        };
        server
            .index
            .data_plane()
            .update_git_temporal(GitTemporalIndex {
                files: std::collections::HashMap::from([(
                    "src/widget.rs".to_string(),
                    home_history,
                )]),
                stats: GitTemporalStats {
                    total_commits_analyzed: 14,
                    analysis_window_days: 90,
                    hotspots: vec![],
                    most_coupled: vec![],
                    computed_at: std::time::SystemTime::now(),
                    compute_duration: std::time::Duration::ZERO,
                },
                state: GitTemporalState::Ready,
            });

        let foreign = crate::stel::StelRequest {
            query: "impact cfg_if".to_string(),
            intent: Some(crate::stel::IntentBucket::Impact),
            symbol: Some("cfg_if".to_string()),
            path: Some("src/widget.rs".to_string()),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };
        let result = crate::protocol::result_status::with_project_evidence_scope(
            None,
            server.symforge_stel_handler(&foreign),
        )
        .await
        .expect("foreign impact facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize foreign impact result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("foreign impact result has text");
        assert!(
            text.contains("selected-project=foreign-project; tool=find_dependents"),
            "the foreign impact result must come from the selected daemon project: {text}"
        );
        assert!(
            !text.contains("HOME_ONLY_PARTNER") && !text.contains("Co-changing files"),
            "foreign impact must not be augmented from the facade's home index: {text}"
        );

        let home = crate::stel::StelRequest {
            project: None,
            path: Some("src/widget.rs".to_string()),
            ..foreign
        };
        let result = crate::protocol::result_status::with_project_evidence_scope(
            None,
            server.symforge_stel_handler(&home),
        )
        .await
        .expect("home impact facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize home impact result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("home impact result has text");
        assert!(
            text.contains("HOME_ONLY_PARTNER") && text.contains("Co-changing files"),
            "home impact must retain the existing local co-change augmentation: {text}"
        );

        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
        let requests = requests.lock();
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].0, "find_dependents");
        assert_eq!(requests[1].0, "find_dependents");
        assert_eq!(
            requests[0]
                .1
                .get("project")
                .and_then(serde_json::Value::as_str),
            Some("foreign-project")
        );
    }

    #[tokio::test]
    async fn daemon_facade_never_rewrites_foreign_find_with_a_home_anchor() {
        let home_root = tempfile::tempdir().expect("home project root");
        std::fs::create_dir_all(home_root.path().join("src")).expect("home src directory");
        std::fs::write(
            home_root.path().join("src/homeanchor.rs"),
            "pub fn homeanchor() {}\n",
        )
        .expect("home anchor source");

        let (base_url, shutdown, requests, server_task) = spawn_project_echo_tool_server().await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "home-project-id".to_string(),
            "session-id".to_string(),
            "home-project".to_string(),
        );
        let mut server = SymForgeServer::new_daemon_proxy(daemon_client);
        server.index = crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(
            crate::live_index::LiveIndex::load(home_root.path()).expect("load home project index"),
        );

        let foreign = crate::stel::StelRequest {
            query: "homeanchor routing".to_string(),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };
        let result = crate::protocol::result_status::with_project_evidence_scope(
            None,
            server.symforge_stel_handler(&foreign),
        )
        .await
        .expect("foreign fused-find facade dispatch");
        let serialized = serde_json::to_value(&result).expect("serialize fused-find result");
        let text = serialized["content"][0]["text"]
            .as_str()
            .expect("fused-find result has text");
        assert!(
            text.contains("project_root: C:/FOREIGN_ROOT/foreign-project"),
            "equal receipts from every foreign step may attest the aggregate: {text}"
        );
        assert_eq!(
            serialized["_meta"]["symforge/project_evidence"]["project_name"],
            "foreign-project"
        );
        let foreign_requests = requests.lock().clone();
        assert_eq!(foreign_requests.len(), 2);
        let (tool, args) = &foreign_requests[0];
        assert_eq!(tool, "search_files");
        assert_eq!(
            args.get("project").and_then(serde_json::Value::as_str),
            Some("foreign-project")
        );
        assert_eq!(
            args.get("query").and_then(serde_json::Value::as_str),
            Some("homeanchor routing"),
            "a foreign find must retain the caller's query"
        );
        assert!(
            args.get("anchor_path")
                .is_none_or(serde_json::Value::is_null)
                && args.get("rank_by").is_none_or(serde_json::Value::is_null),
            "a foreign find must not carry a home-derived co-change anchor: {args}"
        );
        assert_eq!(foreign_requests[1].0, "search_text");
        assert_eq!(
            foreign_requests[1]
                .1
                .get("project")
                .and_then(serde_json::Value::as_str),
            Some("foreign-project")
        );

        requests.lock().clear();
        let home = crate::stel::StelRequest {
            project: None,
            ..foreign
        };
        crate::protocol::result_status::with_project_evidence_scope(
            None,
            server.symforge_stel_handler(&home),
        )
        .await
        .expect("home fused-find facade dispatch");
        let home_requests = requests.lock().clone();
        assert_eq!(home_requests.len(), 2);
        let (tool, args) = &home_requests[0];
        assert_eq!(tool, "search_files");
        assert_eq!(
            args.get("query").and_then(serde_json::Value::as_str),
            Some("homeanchor")
        );
        assert_eq!(
            args.get("anchor_path").and_then(serde_json::Value::as_str),
            Some("src/homeanchor.rs")
        );
        assert_eq!(
            args.get("rank_by").and_then(serde_json::Value::as_str),
            Some("path+cochange")
        );

        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    #[tokio::test]
    async fn daemon_facade_never_grounds_foreign_economics_from_home_bytes() {
        let home_root = tempfile::tempdir().expect("home project root");
        std::fs::create_dir_all(home_root.path().join("src")).expect("home src directory");
        let mut source = "// home-only economics bytes\n".repeat(4_096);
        source.push_str("pub fn shared() {}\n");
        std::fs::write(home_root.path().join("src/shared.rs"), source).expect("large home source");

        let (base_url, shutdown, _requests, server_task) = spawn_project_echo_tool_server().await;
        let make_server = || {
            let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
                base_url.clone(),
                "home-project-id".to_string(),
                "session-id".to_string(),
                "home-project".to_string(),
            );
            let mut server = SymForgeServer::new_daemon_proxy(daemon_client);
            server.index =
                crate::live_index::index_lifecycle::activation::ProjectRuntimeHandle::bind(
                    crate::live_index::LiveIndex::load(home_root.path())
                        .expect("load home project index"),
                );
            server
        };

        let foreign = crate::stel::StelRequest {
            query: "read shared file".to_string(),
            intent: Some(crate::stel::IntentBucket::Read),
            path: Some("src/shared.rs".to_string()),
            project: Some("foreign-project".to_string()),
            ..Default::default()
        };
        let floor_plan = crate::stel::planner::build_plan(&foreign);
        assert!(floor_plan.steps[0].index_refs.is_empty());
        let floor = crate::stel::controller::estimate_economics(&floor_plan);

        let foreign_server = make_server();
        crate::protocol::result_status::with_project_evidence_scope(
            None,
            foreign_server.symforge_stel_handler(&foreign),
        )
        .await
        .expect("foreign read facade dispatch");
        let foreign_event = foreign_server
            .stel_ledger()
            .lock()
            .last()
            .expect("foreign facade ledger event");
        assert_eq!(
            foreign_event.manual_baseline_tokens, floor.predicted_manual_tokens,
            "foreign economics must retain the ungrounded target-plan floor"
        );
        assert_eq!(
            foreign_event.predicted_response_tokens, floor.predicted_response_tokens,
            "foreign response economics must not use home file bytes"
        );

        let home_server = make_server();
        let home = crate::stel::StelRequest {
            project: None,
            ..foreign
        };
        crate::protocol::result_status::with_project_evidence_scope(
            None,
            home_server.symforge_stel_handler(&home),
        )
        .await
        .expect("home read facade dispatch");
        let home_event = home_server
            .stel_ledger()
            .lock()
            .last()
            .expect("home facade ledger event");
        assert_ne!(
            home_event.manual_baseline_tokens, floor.predicted_manual_tokens,
            "home reads must retain real-byte economics grounding"
        );

        let _ = shutdown.send(());
        server_task.await.expect("fake daemon server task");
    }

    // ── ensure_local_index: root-mismatch invalidation (M2) ──────────────────

    /// Build a local-mode server (no daemon proxy) starting from an empty index,
    /// targeting `repo_root`. Mirrors the production `SymForgeServer::new` wiring
    /// used by the local stdio path.
    fn make_local_server(repo_root: Option<std::path::PathBuf>) -> SymForgeServer {
        let index = crate::live_index::LiveIndex::empty();
        let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
        SymForgeServer::new(
            index,
            "test_project".to_string(),
            watcher_info,
            repo_root,
            None,
        )
    }

    /// Write a single `.rs` file under `dir` so a real local reload produces a
    /// non-empty index whose contents identify the project.
    fn seed_project(dir: &std::path::Path, file_name: &str, body: &str) {
        std::fs::write(dir.join(file_name), body).expect("seed project source file");
    }

    /// Core M2 regression: a changed `repo_root` (WITHOUT `reset_to_empty`) must
    /// force `ensure_local_index` to reload the new root instead of serving the
    /// previous project. Fails without the root-mismatch guard.
    #[tokio::test]
    async fn ensure_local_index_reloads_on_root_mismatch_without_reset() {
        let dir_a = tempfile::TempDir::new().expect("temp dir A");
        let dir_b = tempfile::TempDir::new().expect("temp dir B");
        seed_project(dir_a.path(), "alpha.rs", "fn alpha_only() {}\n");
        seed_project(dir_b.path(), "beta.rs", "fn beta_only() {}\n");

        // 1. Load project A.
        let server = make_local_server(Some(dir_a.path().to_path_buf()));
        server.ensure_local_index().await;

        let published_a = server.index.data_plane().published_state();
        assert!(
            published_a.file_count > 0,
            "project A should have loaded a non-empty index"
        );
        assert_eq!(
            published_a.indexed_root.as_deref(),
            Some(crate::live_index::store::normalize_root(dir_a.path()).as_path()),
            "loaded index must record project A's normalized root"
        );
        assert!(
            server
                .index
                .data_plane()
                .read()
                .get_file("alpha.rs")
                .is_some(),
            "project A's file should be present after the first load"
        );

        // Feature 032 (F2): runs observed against project A's index must not
        // survive the reload into project B's.
        let _seeded = seed_repeat_run(&server);

        // 2. Switch the target root to B WITHOUT calling reset_to_empty.
        server.set_repo_root(Some(dir_b.path().to_path_buf()));

        // 3. The next ensure_local_index must detect the root mismatch and reload B.
        server.ensure_local_index().await;
        assert!(
            server.repeat_tracker.lock().is_empty(),
            "a local index reload is a new incarnation: every repeat run must be cleared"
        );

        let published_b = server.index.data_plane().published_state();
        assert_eq!(
            published_b.indexed_root.as_deref(),
            Some(crate::live_index::store::normalize_root(dir_b.path()).as_path()),
            "after a root switch, ensure_local_index must serve project B's root"
        );
        assert!(
            server
                .index
                .data_plane()
                .read()
                .get_file("beta.rs")
                .is_some(),
            "project B's file must be present after the root-mismatch reload"
        );
        assert!(
            server
                .index
                .data_plane()
                .read()
                .get_file("alpha.rs")
                .is_none(),
            "project A's stale file must be gone after switching to project B"
        );
    }

    /// Steady-state guard: repeated `ensure_local_index` calls against the SAME
    /// root must NOT rebuild the index. A spurious reload bumps the project
    /// generation, so an unchanged generation (and unchanged recorded root)
    /// proves no reload occurred — verifying normalization makes the common path
    /// cheap rather than reloading on every call.
    #[tokio::test]
    async fn ensure_local_index_does_not_reload_on_repeated_same_root_calls() {
        let dir_a = tempfile::TempDir::new().expect("temp dir A");
        seed_project(dir_a.path(), "alpha.rs", "fn alpha_only() {}\n");

        let server = make_local_server(Some(dir_a.path().to_path_buf()));

        // First call performs the one and only load.
        server.ensure_local_index().await;
        let gen_after_first = server.index.data_plane().current_project_generation();
        let root_after_first = server
            .index
            .data_plane()
            .published_state()
            .indexed_root
            .clone();
        assert!(
            server.index.data_plane().published_state().file_count > 0,
            "first ensure_local_index call should have loaded project A"
        );

        // Feature 032 (F2) negative control: no reload means no incarnation
        // change, so runs observed against this index survive.
        let _seeded = seed_repeat_run(&server);

        // Repeated calls with the same root must be no-ops (no reload).
        for _ in 0..3 {
            server.ensure_local_index().await;
        }

        assert_eq!(
            server.repeat_tracker.lock().len(),
            1,
            "a same-root no-op must leave repeat runs untouched"
        );
        assert_eq!(
            server.index.data_plane().current_project_generation(),
            gen_after_first,
            "repeated same-root ensure_local_index calls must not reload (project generation must not change)"
        );
        assert_eq!(
            server.index.data_plane().published_state().indexed_root,
            root_after_first,
            "repeated same-root calls must leave the recorded root unchanged"
        );
    }

    /// SF-STRESS-022: `initialize` serverInfo must identify symforge, not the
    /// rmcp framework default. Without `with_server_info`, rmcp's
    /// `Implementation::from_build_env` reports "rmcp"/<rmcp version>.
    #[test]
    fn get_info_reports_symforge_name_and_crate_version() {
        let server = make_local_server(None);
        let info = ServerHandler::get_info(&server);
        assert_eq!(
            info.server_info.name, "symforge",
            "serverInfo.name must identify symforge, not the rmcp framework"
        );
        assert_eq!(
            info.server_info.version,
            env!("CARGO_PKG_VERSION"),
            "serverInfo.version must track the symforge crate version"
        );
    }
}