agentstatedeveloper-mcp 1.4.9

MCP server for AgentStateDeveloper — exposes asd tools over stdio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
//! AgentStateDeveloper MCP stdio server — exposes ASD read/write operations
//! as MCP tools for coding agents.
//!
//! Patterns mirror `agentstategraph-mcp::server` (same `rmcp` version).

use std::collections::{HashSet, VecDeque};
use std::path::PathBuf;
use std::process::Command as Proc;
use std::sync::Arc;

use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::{ServerHandler, tool, tool_handler, tool_router};
use tokio::sync::Mutex;

use agentstatedeveloper_adapters::default_adapters;
use agentstatedeveloper_core::{
    ASD_PATH_PREFIX, AsgEffectStore, AsgFeedbackStore, AsgIndexStore, AsgLedgerStore,
    AsgScratchStore, AuditEvent, Author, AuthorKind, CleanFilter, ConclusionClass, Decision,
    Effect, EffectCategory, EffectDecl, EffectStore, Engine, FeedbackEntry, FeedbackStore,
    FeedbackVerdict, FtsFilters, IndexStore, LedgerEntry, LedgerKind, LedgerStore, Mismatch,
    ParsedSymbol, ScratchEntry, ScratchFilter, ScratchStatus, ScratchStore, SearchDocsDb,
    SearchFtsDb, SidecarState, Situation, Symbol, Verification, VerificationSource,
    VerificationStatus, WorkflowSummary, actions, append_workflow_session,
    apply_feedback_adjustments, apply_file_scope_feedback, brief,
    build_feedback_state_from_entries, classify_layer_sym, compute_trust_score,
    compute_uncertainty, conclusions_export, confidence_reason, confidence_scores,
    derive_cold_hints, detect_ambiguous_tokens, detect_confidence_warnings, detect_possible_misses,
    detect_workflow, effect_detail_reason, emit_audit, estimate_tokens, event_types,
    explain_feedback_impacts, explain_match, extract_summary, find_candidates, gather_recency,
    git_dirty_files, hybrid_boost, intent_focus, intent_layer_order, kind_str,
    load_layer_overrides, load_scope_aliases, parse_intent, parse_query, paths, propose_test_path,
    recipes, resolve_scope, result_bucket, score_evidence_quality, sidecar_lifecycle_state,
    stale_warning, suggest_better_queries, suggest_scoped_queries, symbol_tier, thinking,
    trim_for_agent,
};

/// The AgentStateDeveloper MCP server.
///
/// `db_path` is stored inside an `Arc<RwLock<PathBuf>>` so the registry
/// watcher (see [`AsdMcpServer::with_registry_tracking`]) can swap it in
/// place when the user runs `asd repo use <other>`.  Reads are sync and
/// fast — we never hold the guard across `.await`.
#[derive(Clone)]
pub struct AsdMcpServer {
    engine: Arc<Mutex<Engine>>,
    db_path: Arc<std::sync::RwLock<PathBuf>>,
    audit_log_path: Option<PathBuf>,
    tool_router: ToolRouter<Self>,
}

// Plan M t-002 (1.0.92): MCP tool parameter types extracted to
// `crate::mcp_params`. Re-imported here so handler signatures
// (`Parameters<SearchParams>` etc.) keep working unchanged.
use crate::mcp_params::*;

#[tool_router]
impl AsdMcpServer {
    pub fn new(engine: Arc<Mutex<Engine>>, db_path: PathBuf) -> Self {
        Self::with_audit_log(engine, db_path, None)
    }

    pub fn with_audit_log(
        engine: Arc<Mutex<Engine>>,
        db_path: PathBuf,
        audit_log_path: Option<PathBuf>,
    ) -> Self {
        Self {
            engine,
            db_path: Arc::new(std::sync::RwLock::new(db_path)),
            audit_log_path,
            tool_router: Self::tool_router(),
        }
    }

    /// Build the server and spawn a background watcher on the shared registry
    /// at `~/.config/asd/repos.toml`. When the active repo changes, the
    /// watcher opens the new db and atomically swaps both the underlying
    /// `Engine` and `db_path` so subsequent tool calls hit the new repo
    /// without restarting the process.
    ///
    /// Pass `false` for `track_registry` when the caller fixed the db
    /// explicitly (e.g. `ASD_DB=...`) — in that case the user opted out of
    /// follow-the-active-repo behavior and we leave the engine alone.
    pub fn with_registry_tracking(
        engine: Arc<Mutex<Engine>>,
        db_path: PathBuf,
        audit_log_path: Option<PathBuf>,
        track_registry: bool,
    ) -> Self {
        let s = Self::with_audit_log(engine, db_path, audit_log_path);
        if track_registry {
            spawn_registry_watcher(s.engine.clone(), s.db_path.clone());
        }
        s
    }

    /// Clone of the currently-open db path. Cheap (one std::RwLock read + clone).
    pub fn db_path(&self) -> PathBuf {
        self.db_path.read().expect("db_path lock poisoned").clone()
    }

    // -- Read tools --

    #[tool(
        description = "Get exact syntax, examples, and gotchas for an asd/ctx feature ON DEMAND, instead of carrying every tool's full docs in context every turn. CALL THIS BEFORE using an asd feature whose exact syntax you're unsure of — it costs ~150-250 tokens and returns synopsis, syntax, params, examples, gotchas, and related features. Pass `topic` (a feature name like 'impact', or a phrase like 'blast radius' — it fuzzy-matches). Omit `topic` for the full grouped catalog of every feature; browse it to discover capabilities you'd miss. Docs are compiled into the running binary, so they always match the code. If nothing matches here it may be a `ctx` (CTXone) feature — the response says so. (CLI: `asd help`.)"
    )]
    async fn help(&self, params: Parameters<HelpParams>) -> String {
        // allow_proxy=true: an unknown topic falls through to `ctx help` so the
        // agent sees one seamless manual across both binaries.
        let result = agentstatedeveloper_core::help::resolve(params.0.topic.as_deref(), true);
        serde_json::to_string_pretty(&result).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Liveness check for the MCP server: reports server status, ASG db path, indexed symbol count, and total artifact counts (symbols + ledger + effects). CALL THIS WHEN you need to confirm the ASD server is reachable and pointed at a db. For index freshness / dirty files / concept gaps use `status`; for a single go/no-go reliability score before relying on ASD use `trust`. Takes no params."
    )]
    async fn health(&self) -> String {
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let prefix = format!("{}/index/by-qname", ASD_PATH_PREFIX);
        let symbol_count = match engine.repo.get_tree(&ref_name, &prefix) {
            Ok(serde_json::Value::Object(map)) => map.len(),
            _ => 0,
        };
        let raw_db_path = self.db_path();
        let db_path = raw_db_path
            .canonicalize()
            .unwrap_or(raw_db_path)
            .to_string_lossy()
            .to_string();
        let ledger_prefix = format!("{}/ledger", ASD_PATH_PREFIX);
        // Plan L t-010: walk the ledger tree once, derive BOTH the
        // orphan count and the total entry count from the same pass.
        // Orphan = ledger entries keyed by a symbol_id that isn't in
        // the qname index. Total entries = sum across all symbol
        // subtrees (one inner object per symbol; each value-of-key
        // is one entry).
        let (orphan_count, ledger_entry_count) =
            match engine.repo.get_tree(&ref_name, &ledger_prefix) {
                Ok(serde_json::Value::Object(by_symbol)) => {
                    let indexed_prefix = format!("{}/index/by-qname", ASD_PATH_PREFIX);
                    let indexed: std::collections::HashSet<String> =
                        match engine.repo.get_tree(&ref_name, &indexed_prefix) {
                            Ok(serde_json::Value::Object(m)) => m
                                .values()
                                .filter_map(|v| v.get("symbol_id")?.as_str().map(|s| s.to_string()))
                                .collect(),
                            _ => std::collections::HashSet::new(),
                        };
                    let mut orphans = 0usize;
                    let mut entries = 0usize;
                    for (sym_id, subtree) in &by_symbol {
                        if let serde_json::Value::Object(es) = subtree {
                            entries += es.len();
                        }
                        if !indexed.contains(sym_id) {
                            orphans += 1;
                        }
                    }
                    (orphans, entries)
                }
                _ => (0, 0),
            };
        // Plan L t-010: count symbols with at least one declared
        // effect. Top-level keys under /asd/v1/effects are symbol_ids.
        let effects_prefix = format!("{}/effects", ASD_PATH_PREFIX);
        let effects_count = match engine.repo.get_tree(&ref_name, &effects_prefix) {
            Ok(serde_json::Value::Object(map)) => map.len(),
            _ => 0,
        };
        let stale = stale_warning(&self.db_path(), 3600);
        // Plan J t-005: compute FTS-side symbol count so the
        // response can flag any divergence from the ASG-side count.
        // Field reports (M21) had agents seeing different numbers
        // from `asd status` (FTS) and `asd health` (ASG) on the
        // same repo with no explanation. Now both surfaces report
        // BOTH counts plus a consistency advisory string when they
        // diverge.
        let fts_symbol_count = SearchFtsDb::open(&self.db_path())
            .ok()
            .map(|f| f.symbol_count() as usize)
            .unwrap_or(0);
        let index_consistency =
            agentstatedeveloper_core::compute_index_consistency(symbol_count, fts_symbol_count);
        let payload = serde_json::json!({
            "status": "ok",
            "db_path": db_path,
            // Bare `symbol_count` kept for backward compatibility —
            // older callers (Plan L t-010 acceptance: "backward
            // compat: bare symbol_count keeps working") depend on it.
            "symbol_count": symbol_count,
            "orphaned_symbol_count": orphan_count,
            // Plan L t-010: total artifact rollup. Previously the
            // bare symbol_count was being misread as "total things in
            // the index" — it's only the qname count. This breakdown
            // makes the distinction explicit.
            "artifact_count": {
                "symbols": symbol_count,
                "ledger_entries": ledger_entry_count,
                "effects": effects_count,
            },
            "index_consistency": index_consistency,
            "stale": stale,
        });
        serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "State Trust Score for the current workspace: can I rely on ASD for this task right now? Returns score (0.0-1.0), level, reasons, a `blocking` flag, and signals (index freshness, ledger density, sidecar status, dirty files, concept gaps). Use as a pre-flight check before leaning on other ASD analysis. (CLI: `asd trust`.)"
    )]
    async fn trust(&self) -> String {
        let db_path = self.db_path();
        let trust = agentstatedeveloper_core::compute_trust_score(&db_path);
        serde_json::to_string(&trust.to_json()).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "One-call \"orient me\" overview for a cold start: languages, top packages, architectural layers, call-graph communities (functional clusters), inbound/outbound routes, and call-graph hotspots. Read-only — run this first in an unfamiliar repo. (CLI: `asd architecture`.)"
    )]
    async fn architecture(&self, params: Parameters<ArchitectureParams>) -> String {
        let top = params.0.top;
        let engine = self.engine.lock().await;
        let out = agentstatedeveloper_core::architecture_overview(&engine, top);
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Candidate dead code: functions/methods with no inbound call edges. Excludes HTTP route handlers, test functions (unless include_tests), and main/dunder methods. NOT definitive — the static call graph misses public API used by other repos, dynamic dispatch, and framework callbacks. (CLI: `asd dead-code`.)"
    )]
    async fn dead_code(&self, params: Parameters<DeadCodeParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let out = agentstatedeveloper_core::dead_code_report(&engine, p.limit, p.include_tests);
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "List cross-service endpoints (HTTP routes/clients, pub-sub) detected in this repo, plus in-repo matched edges (a client call and a server route sharing a contract). CALL THIS WHEN mapping how services talk to each other or auditing API surface before a contract change — an unmatched client edge is a candidate contract-drift signal. Cross-repo matching is a Team-tier feature. (CLI: `asd endpoints`.)"
    )]
    async fn endpoints(&self) -> String {
        let engine = self.engine.lock().await;
        let out = agentstatedeveloper_core::endpoints_report(&engine);
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Look up indexed symbols by exact structured filters — `name_contains` (substring on qualified name), `kind`, `language` — AND-combined. CALL THIS WHEN you already know part of a symbol's name or want to enumerate all symbols of a kind/language, and do NOT need relevance ranking. For concept/keyword discovery ('auth flow', 'export pipeline') use `code_search`; for exact-identifier occurrences use `references`. Returns up to `limit` (default 50) symbol summaries. (CLI: `asd search` with filters.)"
    )]
    async fn code_query(&self, params: Parameters<CodeQueryParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;

        let index = AsgIndexStore::from_engine(&engine);
        let kind_filter = p.kind.as_deref().map(|k| k.to_lowercase());
        let name_filter = p.name_contains.as_deref();
        let lang_filter = p.language.as_deref();
        let limit = p.limit.max(1) as usize;

        // One bulk id-map read, then filter in memory. (Was: one
        // get_symbol_by_qname per indexed qname — minutes at 10k
        // symbols on a cold FTS cache, holding the engine mutex.)
        let mut symbols: Vec<Symbol> = index
            .build_id_map(&engine)
            .into_values()
            .filter(|sym| {
                if let Some(needle) = name_filter
                    && !sym.qname.contains(needle)
                {
                    return false;
                }
                if let Some(lang) = lang_filter
                    && sym.language != lang
                {
                    return false;
                }
                if let Some(ref k) = kind_filter
                    && kind_str(&sym.kind) != k.as_str()
                {
                    return false;
                }
                true
            })
            .collect();

        symbols.sort_by(|a, b| a.qname.cmp(&b.qname));
        symbols.truncate(limit);
        // Plan E t-007: brief = compact per-symbol projection.
        if brief::brief_from_env() {
            let projected: Vec<_> = symbols.iter().map(brief::brief_symbol).collect();
            return serde_json::to_string(&projected).unwrap_or_else(|_| "[]".to_string());
        }
        serde_json::to_string(&symbols).unwrap_or_else(|_| "[]".to_string())
    }

    #[tool(
        description = "Ranked concept search over indexed symbols (FTS5/BM25). CALL THIS WHEN discovering entry points for a feature or concept ('playhead over clips', 'auth flow'). For structured name/kind filters use `code_query`; for exact identifier matches use `references`. Supports inline exclusion syntax ('drift playhead -sample'). (CLI: `asd search`.)"
    )]
    async fn code_search(&self, params: Parameters<CodeSearchParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let (tokens, mut exclusions) = parse_query(&p.query);
        if let Some(ref excl) = p.exclude {
            for term in excl
                .split(',')
                .map(|t| t.trim().to_lowercase())
                .filter(|t| !t.is_empty())
            {
                exclusions.push(term);
            }
        }

        if tokens.is_empty() {
            return "[]".to_string();
        }

        let limit = p.limit.max(1) as usize;
        let mut paths_filter: Vec<String> = Vec::new();
        if let Some(ref scope) = p.scope {
            paths_filter.extend(resolve_scope(scope, &db_path));
        }
        if let Some(ref paths) = p.paths {
            paths_filter.extend(
                paths
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty()),
            );
        }
        let filters = FtsFilters {
            kind: p.kind.as_deref().map(|k| k.to_lowercase()),
            language: p.language.as_deref().map(|l| l.to_lowercase()),
            include_tests: p.include_tests,
            tests_only: p.tests_only,
            exclude_terms: exclusions.clone(),
            paths_filter,
            exclude_paths: Vec::new(),
            exclude_languages: Vec::new(),
        };

        // --- FTS path ---
        let fts_result = SearchFtsDb::open(&db_path)
            .ok()
            .filter(|fts| fts.has_data())
            .and_then(|fts| fts.search(&p.query, &filters, limit * 4).ok());

        if let Some(hits) = fts_result {
            let ledger_store = AsgLedgerStore::from_engine(&engine);
            let mut scored: Vec<(f64, _)> = hits
                .into_iter()
                .map(|hit| {
                    let boost = hybrid_boost(&hit, &tokens);
                    let entries = ledger_store
                        .list_entries(&ref_name, &hit.symbol_id)
                        .unwrap_or_default();
                    let text = entries
                        .iter()
                        .map(|e| e.summary.to_lowercase())
                        .collect::<Vec<_>>()
                        .join(" ");
                    let ledger_boost = if text.is_empty() {
                        0.0
                    } else {
                        tokens.iter().filter(|t| text.contains(t.as_str())).count() as f64
                    };
                    (hit.bm25_score + boost + ledger_boost, hit)
                })
                .collect();
            scored.sort_by(|a, b| {
                b.0.partial_cmp(&a.0)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then_with(|| a.1.qname.cmp(&b.1.qname))
            });
            if !exclusions.is_empty() {
                scored.retain(|(_, hit)| {
                    let qn = hit.qname.to_lowercase();
                    let fl = hit.file.to_lowercase();
                    let doc = hit.doc.as_deref().unwrap_or("").to_lowercase();
                    let sig = hit.signature.as_deref().unwrap_or("").to_lowercase();
                    !exclusions.iter().any(|e| {
                        qn.contains(e.as_str())
                            || fl.contains(e.as_str())
                            || doc.contains(e.as_str())
                            || sig.contains(e.as_str())
                    })
                });
            }
            scored.truncate(limit);

            let recency = gather_recency(200, 14.0);
            let index_store = AsgIndexStore::from_engine(&engine);
            let raw_scores: Vec<f64> = scored.iter().map(|(s, _)| *s).collect();
            let confidences = confidence_scores(&raw_scores);
            let mut layers_present: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            let results: Vec<serde_json::Value> = scored
                .iter()
                .zip(confidences.iter())
                .map(|((score, hit), conf)| {
                    let tier = hit.tier;
                    let layer = classify_layer_sym(&hit.file, &hit.qname, tier, &layer_overrides);
                    layers_present.insert(layer.to_string());
                    let summary = extract_summary(hit.doc.as_deref(), hit.signature.as_deref());
                    let rec = recency.get(&hit.file);
                    let is_hot = rec.map(|r| r.hot).unwrap_or(false);
                    let entries = ledger_store
                        .list_entries(&ref_name, &hit.symbol_id)
                        .unwrap_or_default();
                    let has_ledger = !entries.is_empty();
                    let match_reasons = index_store
                        .get_symbol_by_qname(&ref_name, &hit.qname)
                        .ok()
                        .flatten()
                        .map(|sym| explain_match(&sym, &tokens, &entries, is_hot))
                        .unwrap_or_default();
                    let bucket = result_bucket(&hit.file, &match_reasons, has_ledger, is_hot);
                    serde_json::json!({
                        "score": score,
                        "confidence": conf,
                        "bucket": bucket,
                        "qname": hit.qname,
                        "kind": hit.kind,
                        "language": hit.language,
                        "file": hit.file,
                        "line": hit.line,
                        "tier": tier,
                        "layer": layer,
                        "summary": summary,
                        "signature": hit.signature,
                        "doc": hit.doc,
                        "last_touched_days": rec.and_then(|r| r.last_touched_days),
                        "hot": is_hot,
                        "match_reasons": match_reasons,
                    })
                })
                .collect();
            let layers_ref: std::collections::HashSet<&str> =
                layers_present.iter().map(|s| s.as_str()).collect();
            let ambiguous_terms = detect_ambiguous_tokens(&tokens, engine.fts.as_ref(), &filters);
            let possible_misses = detect_possible_misses(&p.query, &layers_ref, results.len());
            // Document hits from the broad corpus (markdown, config, manifests, etc.)
            let doc_hits: Vec<serde_json::Value> = SearchDocsDb::open(&db_path)
                .ok()
                .filter(|db| !db.is_empty())
                .and_then(|db| db.search(&tokens, limit, None).ok())
                .unwrap_or_default()
                .into_iter()
                .map(|h| {
                    serde_json::json!({
                        "source": "document",
                        "score": h.bm25_score,
                        "kind": h.kind,
                        "path": h.path,
                        "line": h.span_start,
                        "title": h.title,
                        "preview": h.preview,
                        "owner_symbol_id": h.owner_symbol_id,
                    })
                })
                .collect();
            let stale = stale_warning(&db_path, 3600);
            // Plan D t-007: brief mode projects each FTS hit down to
            // {qname, file:line, signature, doc, score} and drops the
            // ambiguous_terms / possible_misses / confidence / document_hits
            // arrays that don't add per-hit information.
            if brief::brief_from_env() {
                let out = serde_json::json!({
                    "query": p.query,
                    "results": brief::brief_search_results(&results),
                    "stale": stale,
                    "query_id": brief::query_id("code_search", &[&p.query]),
                });
                return serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string());
            }
            let out = serde_json::json!({
                "query": p.query,
                "ambiguous_terms": ambiguous_terms,
                "possible_misses": possible_misses,
                "results": results,
                "document_hits": doc_hits,
                "stale": stale,
                "confidence": {
                    "strong": "concept and cross-layer queries that span multiple terms (e.g. 'master volume strategy', 'export pipeline')",
                    "weak": "exact-identifier lookups and 'all references to X' — use `references` for those; broad single-word queries may surface unrelated files",
                },
            });
            return serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string());
        }

        // --- Fallback: in-memory O(N) scoring ---
        // Shared core implementation: one by-qname tree read + one
        // ledger walk (was a per-qname symbol fetch + per-symbol
        // ledger read — minutes at 10k symbols on a cold FTS cache).
        let mut scored: Vec<(u32, agentstatedeveloper_core::Symbol)> =
            agentstatedeveloper_core::in_memory_scored_symbols(
                &engine,
                &tokens,
                filters.kind.as_deref(),
                filters.language.as_deref(),
            );
        scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.qname.cmp(&b.1.qname)));
        scored.truncate(limit);
        let recency = gather_recency(200, 14.0);
        let results: Vec<serde_json::Value> = scored
            .iter()
            .map(|(score, sym)| {
                let tier = symbol_tier(&sym.file);
                let layer = classify_layer_sym(&sym.file, &sym.qname, tier, &layer_overrides);
                let summary = extract_summary(sym.doc.as_deref(), sym.signature.as_deref());
                let rec = recency.get(&sym.file);
                serde_json::json!({
                    "score": score,
                    "qname": sym.qname,
                    "kind": format!("{:?}", sym.kind).to_lowercase(),
                    "language": sym.language,
                    "file": sym.file,
                    "line": sym.start.line,
                    "tier": tier,
                    "layer": layer,
                    "summary": summary,
                    "signature": sym.signature,
                    "doc": sym.doc,
                    "last_touched_days": rec.and_then(|r| r.last_touched_days),
                    "hot": rec.map(|r| r.hot).unwrap_or(false),
                })
            })
            .collect();
        serde_json::to_string(&results).unwrap_or_else(|_| "[]".to_string())
    }

    #[tool(
        description = "List named scope aliases from `.asd/scopes.toml`. Use this first when broad searches return noise — narrow with `--scope <name>` or `--paths <glob>` on search, prepare_change, investigate, impact, checklist, since. (CLI: `asd scopes list`.)"
    )]
    async fn scopes_list(&self) -> String {
        let engine = self.engine.lock().await;
        let db_path = self.db_path();
        drop(engine);
        let aliases = load_scope_aliases(&db_path);
        let scopes_file = db_path
            .parent()
            .unwrap_or(std::path::Path::new("."))
            .join("scopes.toml")
            .display()
            .to_string();
        let hint = if aliases.is_empty() {
            "no scopes defined; create .asd/scopes.toml with entries like `audio-engine = [\"Packages/AudioEngine/**\"]`, or pass `--paths <glob>` directly to any scoped command"
        } else {
            "pass `--scope <name>` to search/prepare_change/investigate/impact/checklist/since"
        };
        serde_json::to_string(&serde_json::json!({
            "scopes": aliases,
            "count": aliases.len(),
            "scopes_file": scopes_file,
            "usage_hint": hint,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "List ledger entries bucketed by the six Plan B conclusion classes (decisions, classifications, mappings, hazards, recipes, followups). Optional `class` filters to one bucket; optional `symbol` filters to one qname. Use to audit what conclusions exist before exporting to .asd/conclusions/*.jsonl. (CLI: `asd conclusions list`.)"
    )]
    async fn conclusions_list(&self, params: Parameters<ConclusionsListParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let ledger = AsgLedgerStore::from_engine(&engine);

        // Parse optional class filter.
        let target_class: Option<ConclusionClass> = p.class.as_deref().and_then(|s| match s {
            "decisions" => Some(ConclusionClass::Decisions),
            "classifications" => Some(ConclusionClass::Classifications),
            "mappings" => Some(ConclusionClass::Mappings),
            "hazards" => Some(ConclusionClass::Hazards),
            "recipes" => Some(ConclusionClass::Recipes),
            "followups" => Some(ConclusionClass::FollowUps),
            _ => None,
        });
        if p.class.is_some() && target_class.is_none() {
            return err_json(&format!(
                "unknown conclusion class: {}. valid: decisions, classifications, mappings, hazards, recipes, followups",
                p.class.as_deref().unwrap_or("")
            ));
        }

        // Resolve target symbols → (qname, live entries) pairs.
        // Workspace-wide: one bulk walk (Plan T scale finding) instead
        // of per-qname symbol + ledger reads.
        let symbol_entries: Vec<(String, Vec<LedgerEntry>)> =
            if let Some(qname) = p.symbol.as_deref() {
                match index.get_symbol_by_qname(&ref_name, qname) {
                    Ok(Some(sym)) => vec![(
                        sym.qname,
                        ledger
                            .list_entries(&ref_name, &sym.symbol_id)
                            .unwrap_or_default(),
                    )],
                    _ => Vec::new(),
                }
            } else {
                agentstatedeveloper_core::thinking::all_symbol_entries(&engine)
            };

        use std::collections::BTreeMap;
        let mut buckets: BTreeMap<&'static str, Vec<serde_json::Value>> = BTreeMap::new();
        for class in ConclusionClass::all() {
            if target_class.is_none() || target_class == Some(*class) {
                buckets.insert(class.filename_stem(), Vec::new());
            }
        }

        for (qname, entries) in &symbol_entries {
            for entry in entries.iter().cloned() {
                let class = entry.kind.conclusion_class();
                if let Some(filter) = target_class {
                    if class != filter {
                        continue;
                    }
                }
                if let Some(bucket) = buckets.get_mut(class.filename_stem()) {
                    bucket.push(serde_json::json!({
                        "entry_id": entry.entry_id,
                        "kind": entry.kind.as_str(),
                        "qname": qname,
                        "symbol_id": entry.symbol_id,
                        "summary": entry.summary,
                        "role": entry.role,
                        "command": entry.command,
                        "tags": entry.tags,
                        "created_at": entry.created_at,
                    }));
                }
            }
        }

        let total: usize = buckets.values().map(|v| v.len()).sum();
        let full = serde_json::json!({
            "class": target_class.map(|c| c.filename_stem()),
            "symbol": p.symbol,
            "total": total,
            "buckets": buckets,
        });
        // Plan F t-006: brief mode drops symbol_id + null role/command/tags.
        let out = if brief::brief_from_env() {
            brief::brief_conclusions_list(&full)
        } else {
            full
        };
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Write all ledger conclusions to compact JSONL files (one per class) under `.asd/conclusions/`. Byte-stable when no new entries — safe to run from a pre-commit hook. Returns per-class entry + byte counts. (CLI: `asd conclusions export`.)"
    )]
    async fn conclusions_export(&self, params: Parameters<ConclusionsExportParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;

        let out_dir: std::path::PathBuf =
            p.out.map(std::path::PathBuf::from).unwrap_or_else(|| {
                db_path
                    .parent()
                    .unwrap_or(std::path::Path::new("."))
                    .join(".asd")
                    .join("conclusions")
            });

        match conclusions_export::export_all(&engine, &out_dir) {
            Ok(counts) => {
                let total_entries: usize = counts.iter().map(|(_, n, _)| n).sum();
                let total_bytes: u64 = counts.iter().map(|(_, _, b)| b).sum();
                serde_json::to_string(&serde_json::json!({
                    "out_dir": out_dir.display().to_string(),
                    "files": counts.iter().map(|(stem, n, b)| serde_json::json!({
                        "class": stem,
                        "file": format!("{stem}.jsonl"),
                        "entries": n,
                        "bytes": b,
                    })).collect::<Vec<_>>(),
                    "total_entries": total_entries,
                    "total_bytes": total_bytes,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => err_json(&format!("conclusions export failed: {e}")),
        }
    }

    #[tool(
        description = "Read `.asd/conclusions/*.jsonl` back into the local ledger. Idempotent (entries keyed by entry_id). Run after `git pull` or on a fresh clone to populate ASG with the committed conclusions. (CLI: `asd conclusions import`.)"
    )]
    async fn conclusions_import(&self, params: Parameters<ConclusionsImportParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;

        let in_dir: std::path::PathBuf =
            p.in_dir.map(std::path::PathBuf::from).unwrap_or_else(|| {
                db_path
                    .parent()
                    .unwrap_or(std::path::Path::new("."))
                    .join(".asd")
                    .join("conclusions")
            });

        match conclusions_export::import_all(&engine, &in_dir, "asd-mcp") {
            Ok(results) => {
                let total_read: usize = results.iter().map(|r| r.read).sum();
                let total_imported: usize = results.iter().map(|r| r.imported).sum();
                let total_up_to_date: usize = results.iter().map(|r| r.skipped_up_to_date).sum();
                let total_unknown: usize = results.iter().map(|r| r.skipped_unknown_qname).sum();
                let total_parse: usize = results.iter().map(|r| r.skipped_parse_error).sum();
                serde_json::to_string(&serde_json::json!({
                    "in_dir": in_dir.display().to_string(),
                    "files": results.iter().map(|r| serde_json::json!({
                        "class": r.class,
                        "file": r.file,
                        "read": r.read,
                        "imported": r.imported,
                        "skipped_up_to_date": r.skipped_up_to_date,
                        "skipped_unknown_qname": r.skipped_unknown_qname,
                        "skipped_parse_error": r.skipped_parse_error,
                    })).collect::<Vec<_>>(),
                    "total_read": total_read,
                    "total_imported": total_imported,
                    "total_skipped_up_to_date": total_up_to_date,
                    "total_skipped_unknown_qname": total_unknown,
                    "total_skipped_parse_error": total_parse,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => err_json(&format!("conclusions import failed: {e}")),
        }
    }

    #[tool(
        description = "Classify test-tier symbols matching a query into migration actions — Delete / Gate / Run / KeepAsCovered / Review — from their role-tagged ledger entries. CALL THIS WHEN you have a batch of stale/uncertain tests and want a structured action plan instead of a raw symbol list. For stale test FILES that may need moving, use `recipe_migrate_stale_tests`. Params: `query`, `limit` (default 50). (CLI: `asd recipe classify-test-migration`.)"
    )]
    async fn recipe_classify_test_migration(
        &self,
        params: Parameters<RecipeClassifyTestMigrationParams>,
    ) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;
        let index = AsgIndexStore::from_engine(&engine);

        // Resolve candidate test-tier symbols via FTS.
        let fts = SearchFtsDb::open(&db_path).ok();
        let candidate_qnames: Vec<String> = if let Some(fts) = fts {
            let filters = FtsFilters {
                kind: None,
                language: None,
                include_tests: true,
                tests_only: true,
                exclude_terms: vec![],
                paths_filter: vec![],
                exclude_paths: vec![],
                exclude_languages: vec![],
            };
            fts.search(&p.query, &filters, p.limit as usize)
                .unwrap_or_default()
                .into_iter()
                .map(|h| h.qname)
                .collect()
        } else {
            Vec::new()
        };

        let recipe = recipes::classify_test_migration(&engine, &index, &candidate_qnames, &p.query);
        serde_json::to_string(&recipe).unwrap_or_else(|_| "{}".to_string())
    }

    // -- Plan G t-003: agent-thinking handlers -----------------------------

    #[tool(
        description = "Record a Hypothesis about a symbol — a hunch with a `confidence` in [0.0, 1.0]. CALL THIS WHEN you form a theory you're not yet sure of ('this cache is probably the drift source'); marks below 0.3 are hidden from prepare_change/context_for prior-thinking by default. Idempotent per (qname, summary). (CLI: `asd think speculate`.)"
    )]
    async fn think_speculate(&self, params: Parameters<ThinkSpeculateParams>) -> String {
        let p = params.0;
        if !(0.0..=1.0).contains(&p.confidence) {
            return err_json(&format!(
                "confidence must be in [0.0, 1.0]; got {}",
                p.confidence
            ));
        }
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let sym = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let ledger = AsgLedgerStore::from_engine(&engine);
        let mut entry = LedgerEntry::new(
            &sym.symbol_id,
            LedgerKind::Hypothesis,
            &p.summary,
            Author {
                kind: AuthorKind::Agent,
                id: "asd-mcp".into(),
            },
        );
        entry.entry_id = think_det_id("hypothesis", &p.qname, &p.summary);
        entry.confidence = Some(p.confidence);
        entry.body = p.body;
        think_push_provenance_tags(&self.db_path(), &mut entry.tags);
        match ledger.append_entry(&ref_name, &entry, "asd-mcp") {
            Ok(()) => serde_json::to_string(&serde_json::json!({
                "ok": true, "kind": "hypothesis", "qname": p.qname,
                "confidence": p.confidence, "entry_id": entry.entry_id,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Record a MentalModel — a multi-symbol structural understanding spanning several qnames (anchored on the FIRST symbol in `symbols`; body carries the full list). CALL THIS WHEN you've worked out how a set of symbols fit together and want the next agent to inherit that map. Idempotent by (name, summary). (CLI: `asd think model`.)"
    )]
    async fn think_model(&self, params: Parameters<ThinkModelParams>) -> String {
        let p = params.0;
        let symbols: Vec<String> = p
            .symbols
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        if symbols.is_empty() {
            return err_json("symbols must list at least one qname (comma-separated)");
        }
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let sym = match index.get_symbol_by_qname(&ref_name, &symbols[0]) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", symbols[0])),
            Err(e) => return err_json(&e.to_string()),
        };
        let ledger = AsgLedgerStore::from_engine(&engine);
        let body = serde_json::json!({ "symbols": &symbols, "name": &p.name }).to_string();
        let mut entry = LedgerEntry::new(
            &sym.symbol_id,
            LedgerKind::MentalModel,
            format!("{}: {}", p.name, p.summary),
            Author {
                kind: AuthorKind::Agent,
                id: "asd-mcp".into(),
            },
        );
        entry.entry_id = think_det_id("model", &p.name, &p.summary);
        entry.body = Some(body);
        think_push_provenance_tags(&self.db_path(), &mut entry.tags);
        match ledger.append_entry(&ref_name, &entry, "asd-mcp") {
            Ok(()) => serde_json::to_string(&serde_json::json!({
                "ok": true, "kind": "mental_model", "name": p.name,
                "symbols": symbols, "entry_id": entry.entry_id,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Record a FailedAttempt — what you tried and why it didn't work. CALL THIS WHEN an approach fails, so the next session doesn't re-tread it. Idempotent by (qname, tried). (CLI: `asd think failed`.)"
    )]
    async fn think_failed(&self, params: Parameters<ThinkFailedParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let sym = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let ledger = AsgLedgerStore::from_engine(&engine);
        let body = serde_json::json!({ "tried": &p.tried, "because": &p.because }).to_string();
        let mut entry = LedgerEntry::new(
            &sym.symbol_id,
            LedgerKind::FailedAttempt,
            format!("failed: {} — because {}", p.tried, p.because),
            Author {
                kind: AuthorKind::Agent,
                id: "asd-mcp".into(),
            },
        );
        entry.entry_id = think_det_id("failed", &p.qname, &p.tried);
        entry.body = Some(body);
        think_push_provenance_tags(&self.db_path(), &mut entry.tags);
        match ledger.append_entry(&ref_name, &entry, "asd-mcp") {
            Ok(()) => serde_json::to_string(&serde_json::json!({
                "ok": true, "kind": "failed_attempt", "qname": p.qname,
                "entry_id": entry.entry_id,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Record an OpenQuestion — a known unknown blocking confident action. CALL THIS WHEN you hit something you can't resolve now; be generous, every recorded question is one the next session won't have to re-ask. Idempotent by (qname, question). (CLI: `asd think question`.)"
    )]
    async fn think_question(&self, params: Parameters<ThinkQuestionParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let sym = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let ledger = AsgLedgerStore::from_engine(&engine);
        let mut entry = LedgerEntry::new(
            &sym.symbol_id,
            LedgerKind::OpenQuestion,
            &p.question,
            Author {
                kind: AuthorKind::Agent,
                id: "asd-mcp".into(),
            },
        );
        entry.entry_id = think_det_id("question", &p.qname, &p.question);
        think_push_provenance_tags(&self.db_path(), &mut entry.tags);
        match ledger.append_entry(&ref_name, &entry, "asd-mcp") {
            Ok(()) => serde_json::to_string(&serde_json::json!({
                "ok": true, "kind": "open_question", "qname": p.qname,
                "entry_id": entry.entry_id,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "List captured thinking entries (Hypothesis / MentalModel / FailedAttempt / OpenQuestion). CALL THIS WHEN resuming work on an area to see what prior sessions concluded or got stuck on. Optional `kind` filter (hypothesis | mental_model | failed_attempt | open_question) and `symbol` filter. (CLI: `asd think list`.)"
    )]
    async fn think_list(&self, params: Parameters<ThinkListParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let ledger = AsgLedgerStore::from_engine(&engine);

        let kind_filter: Option<LedgerKind> = p.kind.as_deref().and_then(|s| match s {
            "hypothesis" => Some(LedgerKind::Hypothesis),
            "mental_model" => Some(LedgerKind::MentalModel),
            "failed_attempt" => Some(LedgerKind::FailedAttempt),
            "open_question" => Some(LedgerKind::OpenQuestion),
            _ => None,
        });
        if p.kind.is_some() && kind_filter.is_none() {
            return err_json(
                "unknown kind; valid: hypothesis, mental_model, failed_attempt, open_question",
            );
        }

        // (qname, live entries) pairs to scan. Workspace-wide: one bulk
        // walk (Plan T scale finding) instead of per-qname symbol +
        // ledger reads.
        let symbol_entries: Vec<(String, Vec<LedgerEntry>)> =
            if let Some(qname) = p.symbol.as_deref() {
                match index.get_symbol_by_qname(&ref_name, qname) {
                    Ok(Some(s)) => vec![(
                        s.qname,
                        ledger
                            .list_entries(&ref_name, &s.symbol_id)
                            .unwrap_or_default(),
                    )],
                    _ => return err_json(&format!("symbol not found: {qname}")),
                }
            } else {
                agentstatedeveloper_core::thinking::all_symbol_entries(&engine)
            };

        let mut entries = Vec::new();
        for (qname, les) in &symbol_entries {
            for entry in les.iter().cloned() {
                if entry.kind.conclusion_class() != ConclusionClass::Thinking {
                    continue;
                }
                if let Some(filter) = kind_filter {
                    if entry.kind != filter {
                        continue;
                    }
                }
                entries.push(serde_json::json!({
                    "entry_id": entry.entry_id,
                    "kind": entry.kind.as_str(),
                    "qname": qname,
                    "summary": entry.summary,
                    "confidence": entry.confidence,
                    "body": entry.body,
                    "tags": entry.tags,
                    "created_at": entry.created_at,
                }));
            }
        }

        serde_json::to_string(&serde_json::json!({
            "total": entries.len(),
            "kind_filter": p.kind,
            "symbol_filter": p.symbol,
            "entries": entries,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Build a migration plan for stale test files. Same output shape as `recipe_classify_test_migration` but adds a Move action when a Mapping ledger entry carries a `move_to` path; otherwise falls back to the classify decision tree. CALL THIS WHEN reorganizing test files after a rename/move. Params: `query`, `limit`. (CLI: `asd recipe migrate-stale-tests`.)"
    )]
    async fn recipe_migrate_stale_tests(
        &self,
        params: Parameters<RecipeClassifyTestMigrationParams>,
    ) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;
        let index = AsgIndexStore::from_engine(&engine);

        let fts = SearchFtsDb::open(&db_path).ok();
        let candidate_qnames: Vec<String> = if let Some(fts) = fts {
            let filters = FtsFilters {
                kind: None,
                language: None,
                include_tests: true,
                tests_only: true,
                exclude_terms: vec![],
                paths_filter: vec![],
                exclude_paths: vec![],
                exclude_languages: vec![],
            };
            fts.search(&p.query, &filters, p.limit as usize)
                .unwrap_or_default()
                .into_iter()
                .map(|h| h.qname)
                .collect()
        } else {
            Vec::new()
        };

        let recipe = recipes::migrate_stale_tests(&engine, &index, &candidate_qnames, &p.query);
        serde_json::to_string(&recipe).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Exact-symbol references with rg parity. Returns the canonical definition(s) from the ASD index plus every literal text occurrence in the worktree via `rg --fixed-strings --word-regexp`. Use this when you want complete, predictable matches for a concrete identifier (no tokenization, no BM25). Requires `rg` on PATH. (CLI: `asd references`.)"
    )]
    async fn references(&self, params: Parameters<ReferencesParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);

        // Definition lookup — qname-exact if `.` present, else basename-suffix match.
        let definitions: Vec<Symbol> = if p.name.contains('.') {
            match index.get_symbol_by_qname(&ref_name, &p.name) {
                Ok(Some(s)) => vec![s],
                Ok(None) => Vec::new(),
                Err(e) => return err_json(&e.to_string()),
            }
        } else {
            let prefix = format!("{}/index/by-qname", ASD_PATH_PREFIX);
            let qnames: Vec<String> = match engine.repo.get_tree(&ref_name, &prefix) {
                Ok(serde_json::Value::Object(m)) => m.keys().cloned().collect(),
                _ => Vec::new(),
            };
            let needle_dot = format!(".{}", p.name);
            let mut out = Vec::new();
            for qn in qnames {
                if qn == p.name || qn.ends_with(&needle_dot) {
                    if let Ok(Some(s)) = index.get_symbol_by_qname(&ref_name, &qn) {
                        out.push(s);
                    }
                }
            }
            out.sort_by(|a, b| a.qname.cmp(&b.qname));
            out
        };

        // Drop engine lock before shelling out — rg can take a moment on large trees.
        drop(engine);

        let root = p
            .path
            .clone()
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
        let globs: Vec<String> = p
            .globs
            .as_deref()
            .map(|s| {
                s.split(',')
                    .map(|t| t.trim().to_string())
                    .filter(|t| !t.is_empty())
                    .collect()
            })
            .unwrap_or_default();
        let limit = p.limit as usize;

        let (occurrences, scan_status) = match rg_scan(&root, &p.name, &globs, limit) {
            Ok(occ) => (occ, "ok".to_string()),
            Err(e) => (Vec::new(), format!("error: {e}")),
        };

        let stale = stale_warning(&self.db_path(), 3600);
        // Plan D t-007: brief mode drops the confidence + scan metadata
        // and projects definitions through brief_symbol so each is the
        // compact 4-field shape.
        if brief::brief_from_env() {
            let brief_defs: Vec<serde_json::Value> =
                definitions.iter().map(brief::brief_symbol).collect();
            let payload = serde_json::json!({
                "name": p.name,
                "definitions": brief_defs,
                "occurrences": occurrences,
                "occurrence_count": occurrences.len(),
                "stale": stale,
                "query_id": brief::query_id("references", &[&p.name]),
            });
            return serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string());
        }
        let payload = serde_json::json!({
            "name": p.name,
            "search_root": root.display().to_string(),
            "definitions": definitions,
            "occurrences": occurrences,
            "occurrence_count": occurrences.len(),
            "limit": p.limit,
            "scan": { "tool": "rg", "status": scan_status, "flags": ["--fixed-strings", "--word-regexp"] },
            "stale": stale,
            "confidence": {
                "strong": "exact-literal references for concrete identifiers (MasterBusParams, KSPatch.userFacingPresets); matches rg by construction",
                "weak": "conceptual or cross-layer queries (e.g. 'master volume strategy') — use `code_search` or `investigate` for those",
            },
        });
        serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Feature archaeology in one pass: search for entry points, then expand each with call chains, effects, invariants, and hazards. CALL THIS WHEN you need to UNDERSTAND how a feature works before touching it. Differs from siblings: `code_search` only returns a ranked symbol list (no expansion); `prepare_change` is the same expansion PLUS impact + a pre-edit checklist and is the right first call when you intend to EDIT. Supports `intent` (bugfix/feature/refactor/…), `scope`/`paths` narrowing, and inline exclusion syntax."
    )]
    async fn investigate(&self, params: Parameters<InvestigateParams>) -> String {
        let p = params.0;
        let intent = p.intent.as_deref().and_then(parse_intent).unwrap_or("");
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let (tokens, mut exclusions) = parse_query(&p.query);
        if let Some(ref excl) = p.exclude {
            for term in excl
                .split(',')
                .map(|t| t.trim().to_lowercase())
                .filter(|t| !t.is_empty())
            {
                exclusions.push(term);
            }
        }

        if tokens.is_empty() {
            return serde_json::json!({ "query": p.query, "entry_points": [] }).to_string();
        }

        let depth = p.depth.max(1) as usize;
        let mut paths_filter: Vec<String> = Vec::new();
        if let Some(ref scope) = p.scope {
            paths_filter.extend(resolve_scope(scope, &db_path));
        }
        if let Some(ref paths) = p.paths {
            paths_filter.extend(
                paths
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty()),
            );
        }
        let filters = FtsFilters {
            kind: p.kind.as_deref().map(|k| k.to_lowercase()),
            language: p.language.as_deref().map(|l| l.to_lowercase()),
            include_tests: p.include_tests,
            tests_only: false,
            exclude_terms: exclusions,
            paths_filter,
            exclude_paths: Vec::new(),
            exclude_languages: Vec::new(),
        };

        let index = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);

        let mut top_qnames = find_candidates(
            &engine,
            &p.query,
            &tokens,
            &filters,
            &ledger_store,
            &index,
            depth,
        );

        // Apply durable feedback adjustments.
        {
            use agentstatedeveloper_core::{FeedbackStore, apply_feedback_adjustments};
            let fb_store = AsgFeedbackStore::from_engine(&engine);
            let fb = fb_store.flat_verdicts(&ref_name).unwrap_or_default();
            apply_feedback_adjustments(&engine, &index, &p.query, &mut top_qnames, &fb);
        }

        // Build id_map for call graph resolution — one bulk read (the
        // per-qname loop this replaces was minutes at 10k symbols on a
        // cold FTS cache, holding the engine mutex).
        let id_map = index.build_id_map(&engine);

        let recency = gather_recency(200, 14.0);

        let resolve_ids = |ids: Vec<String>| -> Vec<serde_json::Value> {
            ids.iter().map(|id| {
                if let Some(s) = id_map.get(id) {
                    serde_json::json!({ "qname": s.qname, "file": s.file, "line": s.start.line })
                } else {
                    serde_json::json!({ "symbol_id": id })
                }
            }).collect()
        };

        let mut entry_points: Vec<serde_json::Value> = Vec::new();
        for (score, qname) in &top_qnames {
            let sym = match index.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(s)) => s,
                _ => continue,
            };
            let callee_ids = index
                .get_callees(&ref_name, &sym.symbol_id)
                .unwrap_or_default();
            let caller_ids = index
                .get_callers(&ref_name, &sym.symbol_id)
                .unwrap_or_default();
            let effects = effect_store
                .get_effects(&ref_name, &sym.symbol_id)
                .unwrap_or(None);
            let ledger = ledger_store
                .list_entries(&ref_name, &sym.symbol_id)
                .unwrap_or_default();

            let mut invariants: Vec<serde_json::Value> = Vec::new();
            let mut hazards: Vec<serde_json::Value> = Vec::new();
            let mut ownership: Vec<serde_json::Value> = Vec::new();
            let mut validation_scenarios: Vec<serde_json::Value> = Vec::new();
            let mut known_bugs: Vec<serde_json::Value> = Vec::new();
            let mut concepts: Vec<serde_json::Value> = Vec::new();
            let mut other_ledger: Vec<serde_json::Value> = Vec::new();
            for entry in &ledger {
                let v = serde_json::to_value(entry).unwrap_or_default();
                match entry.kind {
                    LedgerKind::Invariant => invariants.push(v),
                    LedgerKind::Hazard => hazards.push(v),
                    LedgerKind::Ownership => ownership.push(v),
                    LedgerKind::ValidationScenario => validation_scenarios.push(v),
                    LedgerKind::KnownBug => known_bugs.push(v),
                    LedgerKind::Concept => concepts.push(v),
                    _ => other_ledger.push(v),
                }
            }

            let tier = symbol_tier(&sym.file);
            let layer = classify_layer_sym(&sym.file, &sym.qname, tier, &layer_overrides);
            let summary = extract_summary(sym.doc.as_deref(), sym.signature.as_deref());
            let rec = recency.get(&sym.file);
            entry_points.push(serde_json::json!({
                "score": score,
                "layer": layer,
                "summary": summary,
                "last_touched_days": rec.and_then(|r| r.last_touched_days),
                "hot": rec.map(|r| r.hot).unwrap_or(false),
                "qname": sym.qname,
                "kind": format!("{:?}", sym.kind).to_lowercase(),
                "language": sym.language,
                "file": sym.file,
                "line": sym.start.line,
                "signature": sym.signature,
                "invariants": invariants,
                "hazards": hazards,
                "known_bugs": known_bugs,
                "concepts": concepts,
                "ownership": ownership,
                "validation_scenarios": validation_scenarios,
                "callers": resolve_ids(caller_ids),
                "callees": resolve_ids(callee_ids),
                "effects": effects,
                "notes": other_ledger,
            }));
        }

        // Aggregate invariants/hazards across all entry points.
        let mut all_invariants: Vec<serde_json::Value> = Vec::new();
        let mut all_hazards: Vec<serde_json::Value> = Vec::new();
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        for ep in &entry_points {
            let qname = ep.get("qname").and_then(|v| v.as_str()).unwrap_or("");
            if let Some(invs) = ep.get("invariants").and_then(|v| v.as_array()) {
                for inv in invs {
                    let key = inv
                        .get("summary")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    if !key.is_empty() && seen.insert(key) {
                        let mut v = inv.clone();
                        if let Some(obj) = v.as_object_mut() {
                            obj.insert(
                                "source_qname".to_string(),
                                serde_json::Value::String(qname.to_string()),
                            );
                        }
                        all_invariants.push(v);
                    }
                }
            }
            if let Some(hzs) = ep.get("hazards").and_then(|v| v.as_array()) {
                for hz in hzs {
                    let mut v = hz.clone();
                    if let Some(obj) = v.as_object_mut() {
                        obj.insert(
                            "source_qname".to_string(),
                            serde_json::Value::String(qname.to_string()),
                        );
                    }
                    all_hazards.push(v);
                }
            }
        }

        // Group by layer (intent-aware ordering).
        let layer_order = intent_layer_order(intent);
        let mut by_layer = serde_json::Map::new();
        for lk in layer_order {
            let members: Vec<&serde_json::Value> = entry_points
                .iter()
                .filter(|ep| ep.get("layer").and_then(|v| v.as_str()) == Some(*lk))
                .collect();
            if !members.is_empty() {
                by_layer.insert(
                    lk.to_string(),
                    serde_json::Value::Array(members.into_iter().cloned().collect()),
                );
            }
        }

        let focus = intent_focus(intent);
        let layers_present: std::collections::HashSet<&str> = entry_points
            .iter()
            .filter_map(|ep| ep.get("layer").and_then(serde_json::Value::as_str))
            .collect();
        let ambiguous_terms = detect_ambiguous_tokens(&tokens, engine.fts.as_ref(), &filters);
        let possible_misses = detect_possible_misses(&p.query, &layers_present, entry_points.len());
        // Token economy (1.0.80): drop `query` input echo. Other
        // fields use `intent`/`focus` from input but those are
        // resolved-and-canonicalized derivatives — keep them.
        let full = serde_json::json!({
            "intent": if intent.is_empty() { serde_json::Value::Null } else { serde_json::json!(intent) },
            "focus": if focus.is_empty() { serde_json::Value::Null } else { serde_json::json!(focus) },
            "tokens": tokens,
            "ambiguous_terms": ambiguous_terms,
            "possible_misses": possible_misses,
            "invariants": all_invariants,
            "hazards": all_hazards,
            "by_layer": by_layer,
        });
        // Plan F t-006: brief flattens by_layer to a compact entry_points list.
        let out = if brief::brief_from_env() {
            brief::brief_investigate(&full)
        } else {
            full
        };
        let out = agentstatedeveloper_core::drop_empty_top_level(out);
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Read a symbol by qname. Returns { symbol, effects, ledger } — its signature, effects, and ledger decisions. CALL THIS WHEN you need one symbol's definition, effects, and ledger. For DEEP context on one or more symbols (callers/callees, covering tests, ownership discovery, token-budgeted) use `context_for` instead. (CLI: `asd read`.)"
    )]
    async fn code_read(&self, params: Parameters<CodeReadParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };

        let effects_store = AsgEffectStore::from_engine(&engine);
        let effects = match effects_store.get_effects(&ref_name, &symbol.symbol_id) {
            Ok(e) => e,
            Err(e) => return err_json(&e.to_string()),
        };

        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let ledger = match ledger_store.list_entries(&ref_name, &symbol.symbol_id) {
            Ok(e) => e,
            Err(e) => return err_json(&e.to_string()),
        };

        // Plan D t-007: honor ASD_FORMAT=brief at the per-call site.
        if brief::brief_from_env() {
            let effects_json = effects.as_ref().and_then(|e| serde_json::to_value(e).ok());
            let mut out = brief::brief_read(
                &symbol,
                &[], // code_read doesn't compute callers/callees inline
                &[],
                effects_json.as_ref(),
                ledger.len(),
            );
            if let serde_json::Value::Object(ref mut m) = out {
                m.insert(
                    "query_id".into(),
                    serde_json::Value::String(brief::query_id("code_read", &[&p.qname])),
                );
            }
            return serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string());
        }

        let payload = serde_json::json!({
            "symbol": symbol,
            "effects": effects,
            "ledger": ledger,
        });
        serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Return the declared + transitively-inherited side effects for a symbol (I/O, network, filesystem, logging, mutation, etc.), resolved via qname. CALL THIS WHEN you need to know what a function touches before editing or before declaring your own effects. To check declared effects against what the source actually does use `verify_effects`; to change them use `effect_declare`. Requires `qname`. (MCP-only — no CLI verb.)"
    )]
    async fn effects(&self, params: Parameters<EffectsOfParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };

        let effects_store = AsgEffectStore::from_engine(&engine);
        match effects_store.get_effects(&ref_name, &symbol.symbol_id) {
            Ok(Some(decl)) => serde_json::to_string(&decl).unwrap_or_else(|_| "null".to_string()),
            Ok(None) => "null".to_string(),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "List symbols that call the given symbol (inbound call edges, intra-module)."
    )]
    async fn callers(&self, params: Parameters<CallersOfParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let target = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let ids = match index.get_callers(&ref_name, &target.symbol_id) {
            Ok(v) => v,
            Err(e) => return err_json(&e.to_string()),
        };
        let syms = match resolve_symbols_by_ids(&engine, &ids) {
            Ok(v) => v,
            Err(e) => return err_json(&e.to_string()),
        };
        // Plan E t-007: brief = compact per-symbol projection.
        if brief::brief_from_env() {
            let projected: Vec<_> = syms.iter().map(brief::brief_symbol).collect();
            return serde_json::to_string(&projected).unwrap_or_else(|_| "[]".to_string());
        }
        serde_json::to_string(&syms).unwrap_or_else(|_| "[]".to_string())
    }

    #[tool(
        description = "List symbols called by the given symbol (outbound call edges, intra-module)."
    )]
    async fn callees(&self, params: Parameters<CalleesOfParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let target = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let ids = match index.get_callees(&ref_name, &target.symbol_id) {
            Ok(v) => v,
            Err(e) => return err_json(&e.to_string()),
        };
        let syms = match resolve_symbols_by_ids(&engine, &ids) {
            Ok(v) => v,
            Err(e) => return err_json(&e.to_string()),
        };
        // Plan E t-007: brief = compact per-symbol projection.
        if brief::brief_from_env() {
            let projected: Vec<_> = syms.iter().map(brief::brief_symbol).collect();
            return serde_json::to_string(&projected).unwrap_or_else(|_| "[]".to_string());
        }
        serde_json::to_string(&syms).unwrap_or_else(|_| "[]".to_string())
    }

    #[tool(
        description = "List ledger entries for a symbol, newest first. By default, entries superseded by later entries are omitted; set include_superseded=true to include them."
    )]
    async fn ledger_get(&self, params: Parameters<LedgerGetParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };

        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let entries = match ledger_store.list_entries(&ref_name, &symbol.symbol_id) {
            Ok(e) => e,
            Err(e) => return err_json(&e.to_string()),
        };

        let filtered: Vec<&LedgerEntry> = if p.include_superseded {
            entries.iter().collect()
        } else {
            // Collect all superseded ids, then exclude entries whose id appears in any supersedes list.
            let mut superseded: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            for e in &entries {
                for sid in &e.supersedes {
                    superseded.insert(sid.clone());
                }
            }
            entries
                .iter()
                .filter(|e| !superseded.contains(&e.entry_id))
                .collect()
        };

        serde_json::to_string(&filtered).unwrap_or_else(|_| "[]".to_string())
    }

    #[tool(
        description = "Search ledger entries across ALL symbols by optional filters: `kind`, `tag`, `author_id`. CALL THIS WHEN you want conclusions/decisions/hazards matching a criterion without knowing which symbol they hang on. To read one symbol's ledger use `ledger_get`. Returns up to `limit` (default 50). (MCP-only — CLI reads go through `asd list` / `asd read`.)"
    )]
    async fn ledger_find(&self, params: Parameters<LedgerFindParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let prefix = format!("{}/ledger", ASD_PATH_PREFIX);
        let limit = p.limit.max(1) as usize;

        let kind_filter = match p.kind.as_deref() {
            Some(s) => match parse_ledger_kind(s) {
                Ok(k) => Some(k),
                Err(e) => return err_json(&e),
            },
            None => None,
        };

        let tree = match engine.repo.get_tree(&ref_name, &prefix) {
            Ok(v) => v,
            Err(_) => return "[]".to_string(),
        };

        let mut matches: Vec<LedgerEntry> = Vec::new();
        if let serde_json::Value::Object(by_symbol) = tree {
            for (_sym_id, per_symbol) in by_symbol {
                let entries_map = match per_symbol {
                    serde_json::Value::Object(m) => m,
                    _ => continue,
                };
                for (_entry_id, v) in entries_map {
                    if let Ok(entry) = serde_json::from_value::<LedgerEntry>(v) {
                        if let Some(k) = kind_filter
                            && entry.kind != k
                        {
                            continue;
                        }
                        if let Some(ref t) = p.tag
                            && !entry.tags.iter().any(|x| x == t)
                        {
                            continue;
                        }
                        if let Some(ref a) = p.author_id
                            && &entry.author.id != a
                        {
                            continue;
                        }
                        matches.push(entry);
                    }
                }
            }
        }

        matches.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        matches.truncate(limit);
        serde_json::to_string(&matches).unwrap_or_else(|_| "[]".to_string())
    }

    // -- Write tools --

    #[tool(
        description = "Append a ledger entry to a symbol (resolved via qname). Routes through the configured policy gate — may deny, allow, or flag the entry as awaiting-approval. Returns { entry_id, matched_policy, status }."
    )]
    async fn ledger_append(&self, params: Parameters<LedgerAppendParams>) -> String {
        let p = params.0;
        let kind = match parse_ledger_kind(&p.kind) {
            Ok(k) => k,
            Err(e) => return err_json(&e),
        };
        let author_kind = match parse_author_kind(&p.author_kind) {
            Ok(k) => k,
            Err(e) => return err_json(&e),
        };
        let author_kind_label = match author_kind {
            AuthorKind::Agent => "agent",
            AuthorKind::Human => "human",
        };

        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_APPEND,
                    &p.author_id,
                    author_kind_label,
                    "error",
                )
                .with_reason(format!("symbol not found: {}", p.qname))
                .with_payload(serde_json::json!({
                    "qname": &p.qname,
                    "kind": kind.as_str(),
                }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&format!("symbol not found: {}", p.qname));
            }
            Err(e) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_APPEND,
                    &p.author_id,
                    author_kind_label,
                    "error",
                )
                .with_reason(e.to_string())
                .with_payload(serde_json::json!({
                    "qname": &p.qname,
                    "kind": kind.as_str(),
                }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&e.to_string());
            }
        };

        // Evaluate policy before doing any write.
        let action = actions::ledger_append_action(kind.as_str());
        let situation = Situation {
            description: format!("ledger.append for {}", p.qname),
            qualifiers: serde_json::json!({
                "qname": &p.qname,
                "kind": kind.as_str(),
                "symbol_id": &symbol.symbol_id,
                "file": &symbol.file,
                "language": &symbol.language,
            }),
        };
        let decision = match engine.policy.evaluate(&situation, &action, &p.author_id) {
            Ok(d) => d,
            Err(e) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_APPEND,
                    &p.author_id,
                    author_kind_label,
                    "error",
                )
                .with_secondary(&symbol.symbol_id)
                .with_reason(format!("policy evaluation failed: {}", e))
                .with_payload(serde_json::json!({
                    "qname": &p.qname,
                    "kind": kind.as_str(),
                }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&format!("policy evaluation failed: {}", e));
            }
        };

        if let Decision::Deny {
            matched_policy,
            reason,
        } = &decision
        {
            let event = AuditEvent::new(
                event_types::LEDGER_APPEND,
                &p.author_id,
                author_kind_label,
                "denied",
            )
            .with_secondary(&symbol.symbol_id)
            .with_matched_policy(Some(matched_policy.clone()))
            .with_reason(reason.clone())
            .with_payload(serde_json::json!({
                "qname": &p.qname,
                "kind": kind.as_str(),
            }));
            emit_audit(engine.audit.as_ref(), event);
            return err_json(&format!(
                "policy denied: {} (matched {})",
                reason, matched_policy
            ));
        }

        let author = Author {
            kind: author_kind,
            id: p.author_id.clone(),
        };
        let mut entry = LedgerEntry::new(symbol.symbol_id.clone(), kind, p.summary, author);
        entry.body = p.body;
        if let Some(tags) = p.tags {
            entry.tags = tags;
        }
        entry.matched_policy = decision.matched_policy();
        // Plan C t-002: warn on unknown role (stderr — visible to the
        // MCP host's logs). Unknown tags are still stored; CLI/MCP just
        // signal the typo.
        if let Some(ref r) = p.role {
            if agentstatedeveloper_core::RoleTag::from_str(r).is_none() {
                let valid: Vec<&str> = agentstatedeveloper_core::RoleTag::all()
                    .iter()
                    .map(|t| t.as_str())
                    .collect();
                eprintln!(
                    "asd-mcp: warning: role={:?} is not a canonical RoleTag. Valid: {}",
                    r,
                    valid.join(", ")
                );
            }
        }
        entry.role = p.role;
        entry.command = p.command;

        // RequireApproval: tag the entry so downstream reviewers see it.
        if let Decision::RequireApproval {
            approvers, reason, ..
        } = &decision
        {
            entry.tags.push("awaiting-approval".to_string());
            for a in approvers {
                entry.tags.push(format!("approver:{}", a));
            }
            if let Some(r) = reason {
                if entry.body.is_none() {
                    entry.body = Some(format!("Approval reason: {}", r));
                }
            }
        }

        let ledger_store = AsgLedgerStore::from_engine(&engine);
        if let Err(e) = ledger_store.append_entry(&ref_name, &entry, &p.author_id) {
            let event = AuditEvent::new(
                event_types::LEDGER_APPEND,
                &p.author_id,
                author_kind_label,
                "error",
            )
            .with_subject(&entry.entry_id)
            .with_secondary(&symbol.symbol_id)
            .with_matched_policy(entry.matched_policy.clone())
            .with_reason(e.to_string())
            .with_payload(serde_json::json!({
                "qname": &p.qname,
                "kind": kind.as_str(),
            }));
            emit_audit(engine.audit.as_ref(), event);
            return err_json(&e.to_string());
        }

        let status = match &decision {
            Decision::Allow { .. } => "allowed",
            Decision::RequireApproval { .. } => "awaiting-approval",
            Decision::Deny { .. } => "denied",
            Decision::NoPolicyMatch => "no-policy-match",
        };

        let event = AuditEvent::new(
            event_types::LEDGER_APPEND,
            &p.author_id,
            author_kind_label,
            status,
        )
        .with_subject(&entry.entry_id)
        .with_secondary(&entry.symbol_id)
        .with_matched_policy(entry.matched_policy.clone())
        .with_payload(serde_json::json!({
            "qname": &p.qname,
            "kind": kind.as_str(),
            "tags": &entry.tags,
        }));
        emit_audit(engine.audit.as_ref(), event);

        serde_json::to_string(&serde_json::json!({
            "entry_id": entry.entry_id,
            "symbol_id": symbol.symbol_id,
            "matched_policy": entry.matched_policy,
            "status": status,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Approve a ledger entry currently tagged `awaiting-approval`. Flips tags to `approved` + records `approved-by:<approver>` and `approved-at:<timestamp>`. Scans ledger by entry_id — no qname needed. Enforces that the approver kind/id matches one of the original entry's `approver:*` tags."
    )]
    async fn ledger_approve(&self, params: Parameters<LedgerApproveParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let situation = Situation {
            description: format!("ledger.approve {}", p.entry_id),
            qualifiers: serde_json::json!({ "entry_id": &p.entry_id }),
        };
        if let Ok(Decision::Deny {
            matched_policy,
            reason,
        }) = engine
            .policy
            .evaluate(&situation, actions::LEDGER_APPROVE, &p.approver)
        {
            return err_json(&format!(
                "policy denied: {} (matched {})",
                reason, matched_policy
            ));
        }
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        match ledger_store.approve_entry(
            &ref_name,
            &p.entry_id,
            &p.approver,
            &p.approver_kind,
            p.message.as_deref(),
            "asd-mcp",
        ) {
            Ok(outcome) => {
                let status = if outcome.already_approved {
                    "already-approved"
                } else {
                    "approved"
                };
                let event = AuditEvent::new(
                    event_types::LEDGER_APPROVE,
                    &p.approver,
                    &p.approver_kind,
                    status,
                )
                .with_subject(&outcome.entry.entry_id)
                .with_secondary(&outcome.entry.symbol_id)
                .with_matched_policy(outcome.entry.matched_policy.clone())
                .with_payload(serde_json::json!({ "tags": outcome.entry.tags }));
                emit_audit(engine.audit.as_ref(), event);

                serde_json::to_string(&serde_json::json!({
                    "status": status,
                    "entry": outcome.entry,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_APPROVE,
                    &p.approver,
                    &p.approver_kind,
                    "error",
                )
                .with_subject(&p.entry_id)
                .with_reason(e.to_string());
                emit_audit(engine.audit.as_ref(), event);
                err_json(&e.to_string())
            }
        }
    }

    #[tool(
        description = "Reject an awaiting-approval ledger entry. Flips tags to `rejected` + records `rejected-by:<reviewer>` and `rejected-at:<timestamp>`. `reason` is required and appended to the entry body. Same approver-match rule as `ledger_approve`."
    )]
    async fn ledger_reject(&self, params: Parameters<LedgerRejectParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let situation = Situation {
            description: format!("ledger.reject {}", p.entry_id),
            qualifiers: serde_json::json!({ "entry_id": &p.entry_id }),
        };
        if let Ok(Decision::Deny {
            matched_policy,
            reason,
        }) = engine
            .policy
            .evaluate(&situation, actions::LEDGER_REJECT, &p.reviewer)
        {
            return err_json(&format!(
                "policy denied: {} (matched {})",
                reason, matched_policy
            ));
        }
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        match ledger_store.reject_entry(
            &ref_name,
            &p.entry_id,
            &p.reviewer,
            &p.reviewer_kind,
            &p.reason,
            "asd-mcp",
        ) {
            Ok(outcome) => {
                let status = if outcome.already_resolved {
                    "already-rejected"
                } else {
                    "rejected"
                };
                let event = AuditEvent::new(
                    event_types::LEDGER_REJECT,
                    &p.reviewer,
                    &p.reviewer_kind,
                    status,
                )
                .with_subject(&outcome.entry.entry_id)
                .with_secondary(&outcome.entry.symbol_id)
                .with_matched_policy(outcome.entry.matched_policy.clone())
                .with_reason(&p.reason)
                .with_payload(serde_json::json!({ "tags": outcome.entry.tags }));
                emit_audit(engine.audit.as_ref(), event);

                serde_json::to_string(&serde_json::json!({
                    "status": status,
                    "entry": outcome.entry,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_REJECT,
                    &p.reviewer,
                    &p.reviewer_kind,
                    "error",
                )
                .with_subject(&p.entry_id)
                .with_reason(e.to_string());
                emit_audit(engine.audit.as_ref(), event);
                err_json(&e.to_string())
            }
        }
    }

    #[tool(
        description = "Withdraw an awaiting-approval entry. Must be called by the original author (author_id matching the entry's author.id). Flips `awaiting-approval` → `withdrawn`."
    )]
    async fn ledger_withdraw(&self, params: Parameters<LedgerWithdrawParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let situation = Situation {
            description: format!("ledger.withdraw {}", p.entry_id),
            qualifiers: serde_json::json!({ "entry_id": &p.entry_id }),
        };
        if let Ok(Decision::Deny {
            matched_policy,
            reason,
        }) = engine
            .policy
            .evaluate(&situation, actions::LEDGER_WITHDRAW, &p.author_id)
        {
            return err_json(&format!(
                "policy denied: {} (matched {})",
                reason, matched_policy
            ));
        }
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        match ledger_store.withdraw_entry(&ref_name, &p.entry_id, &p.author_id, "asd-mcp") {
            Ok(outcome) => {
                let status = if outcome.already_resolved {
                    "already-withdrawn"
                } else {
                    "withdrawn"
                };
                let event =
                    AuditEvent::new(event_types::LEDGER_WITHDRAW, &p.author_id, "agent", status)
                        .with_subject(&outcome.entry.entry_id)
                        .with_secondary(&outcome.entry.symbol_id)
                        .with_payload(serde_json::json!({ "tags": outcome.entry.tags }));
                emit_audit(engine.audit.as_ref(), event);

                serde_json::to_string(&serde_json::json!({
                    "status": status,
                    "entry": outcome.entry,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => {
                let event =
                    AuditEvent::new(event_types::LEDGER_WITHDRAW, &p.author_id, "agent", "error")
                        .with_subject(&p.entry_id)
                        .with_reason(e.to_string());
                emit_audit(engine.audit.as_ref(), event);
                err_json(&e.to_string())
            }
        }
    }

    #[tool(
        description = "Append a new ledger entry that supersedes one or more existing entries for the given symbol. Non-superseded entries remain; superseded ones are filtered out of default `ledger_get` results."
    )]
    async fn ledger_supersede(&self, params: Parameters<LedgerSupersedeParams>) -> String {
        let p = params.0;
        let kind = match parse_ledger_kind(&p.kind) {
            Ok(k) => k,
            Err(e) => return err_json(&e),
        };
        let author_kind = match parse_author_kind(&p.author_kind) {
            Ok(k) => k,
            Err(e) => return err_json(&e),
        };
        let author_kind_label = match author_kind {
            AuthorKind::Agent => "agent",
            AuthorKind::Human => "human",
        };

        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_SUPERSEDE,
                    &p.author_id,
                    author_kind_label,
                    "error",
                )
                .with_reason(format!("symbol not found: {}", p.qname))
                .with_payload(serde_json::json!({
                    "qname": &p.qname,
                    "supersedes": &p.supersedes,
                }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&format!("symbol not found: {}", p.qname));
            }
            Err(e) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_SUPERSEDE,
                    &p.author_id,
                    author_kind_label,
                    "error",
                )
                .with_reason(e.to_string())
                .with_payload(serde_json::json!({ "qname": &p.qname }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&e.to_string());
            }
        };

        let situation = Situation {
            description: format!("ledger.supersede for {}", p.qname),
            qualifiers: serde_json::json!({
                "qname": &p.qname,
                "symbol_id": &symbol.symbol_id,
                "file": &symbol.file,
                "language": &symbol.language,
            }),
        };
        if let Ok(Decision::Deny {
            matched_policy,
            reason,
        }) = engine
            .policy
            .evaluate(&situation, actions::LEDGER_SUPERSEDE, &p.author_id)
        {
            return err_json(&format!(
                "policy denied: {} (matched {})",
                reason, matched_policy
            ));
        }

        let author = Author {
            kind: author_kind,
            id: p.author_id.clone(),
        };
        let mut entry = LedgerEntry::new(&symbol.symbol_id, kind, p.summary, author);
        entry.body = p.body;
        entry.supersedes = p.supersedes.clone();
        entry.tags.push("supersedes".to_string());

        let ledger_store = AsgLedgerStore::from_engine(&engine);
        match ledger_store.append_entry(&ref_name, &entry, "asd-mcp") {
            Ok(()) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_SUPERSEDE,
                    &p.author_id,
                    author_kind_label,
                    "success",
                )
                .with_subject(&entry.entry_id)
                .with_secondary(&entry.symbol_id)
                .with_payload(serde_json::json!({
                    "supersedes": entry.supersedes,
                    "qname": &p.qname,
                }));
                emit_audit(engine.audit.as_ref(), event);

                serde_json::to_string(&serde_json::json!({
                    "status": "superseded",
                    "entry_id": entry.entry_id,
                    "symbol_id": entry.symbol_id,
                    "supersedes": entry.supersedes,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => {
                let event = AuditEvent::new(
                    event_types::LEDGER_SUPERSEDE,
                    &p.author_id,
                    author_kind_label,
                    "error",
                )
                .with_secondary(&symbol.symbol_id)
                .with_reason(e.to_string())
                .with_payload(serde_json::json!({
                    "supersedes": &p.supersedes,
                    "qname": &p.qname,
                }));
                emit_audit(engine.audit.as_ref(), event);
                err_json(&e.to_string())
            }
        }
    }

    #[tool(
        description = "Overwrite the `declared` effects list for a symbol. Routes through the configured policy gate. Uses `asd.effect.declare.broadens` as the action when the new list introduces effect categories not already present; otherwise `asd.effect.declare`. Returns the updated EffectDecl plus a `status` string."
    )]
    async fn effect_declare(&self, params: Parameters<EffectDeclareParams>) -> String {
        let p = params.0;

        // Deserialize each declared element into an Effect.
        let mut declared: Vec<Effect> = Vec::with_capacity(p.declared.len());
        for (i, v) in p.declared.into_iter().enumerate() {
            match serde_json::from_value::<Effect>(v) {
                // `adapter` marks an effect a re-index inferred and may
                // refresh; a declared one must not carry it (an effect copied
                // from `asd effects` output would), or the next index replaces
                // the declaration with its own inference.
                Ok(e) => declared.push(Effect { adapter: None, ..e }),
                Err(e) => return err_json(&format!("declared[{}]: {}", i, e)),
            }
        }

        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => {
                let event =
                    AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", "error")
                        .with_reason(format!("symbol not found: {}", p.qname))
                        .with_payload(serde_json::json!({ "qname": &p.qname }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&format!("symbol not found: {}", p.qname));
            }
            Err(e) => {
                let event =
                    AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", "error")
                        .with_reason(e.to_string())
                        .with_payload(serde_json::json!({ "qname": &p.qname }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&e.to_string());
            }
        };

        let effects_store = AsgEffectStore::from_engine(&engine);
        let existing = match effects_store.get_effects(&ref_name, &symbol.symbol_id) {
            Ok(e) => e,
            Err(e) => {
                let event =
                    AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", "error")
                        .with_subject(&symbol.symbol_id)
                        .with_reason(e.to_string())
                        .with_payload(serde_json::json!({ "qname": &p.qname }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&e.to_string());
            }
        };

        // Broadening check: if any new effect category is not already present
        // in the existing declared list, this call is broadening.
        let existing_set: std::collections::HashSet<EffectCategory> = existing
            .as_ref()
            .map(|d| d.declared.iter().map(|e| e.effect.clone()).collect())
            .unwrap_or_default();
        let new_categories: Vec<String> = declared
            .iter()
            .map(|e| e.effect.as_str().to_string())
            .collect();
        let broadens = declared.iter().any(|e| !existing_set.contains(&e.effect));
        let action = if broadens {
            actions::EFFECT_DECLARE_BROADENS
        } else {
            actions::EFFECT_DECLARE
        };

        let situation = Situation {
            description: format!("effect.declare for {}", p.qname),
            qualifiers: serde_json::json!({
                "qname": &p.qname,
                "declared": new_categories,
                "broadens": broadens,
                "symbol_id": &symbol.symbol_id,
                "file": &symbol.file,
                "language": &symbol.language,
            }),
        };
        let decision = match engine.policy.evaluate(&situation, action, &p.author_id) {
            Ok(d) => d,
            Err(e) => {
                let event =
                    AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", "error")
                        .with_subject(&symbol.symbol_id)
                        .with_reason(format!("policy evaluation failed: {}", e))
                        .with_payload(serde_json::json!({
                            "qname": &p.qname,
                            "declared": &new_categories,
                            "broadens": broadens,
                            "action": action,
                        }));
                emit_audit(engine.audit.as_ref(), event);
                return err_json(&format!("policy evaluation failed: {}", e));
            }
        };

        if let Decision::Deny {
            matched_policy,
            reason,
        } = &decision
        {
            let event =
                AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", "denied")
                    .with_subject(&symbol.symbol_id)
                    .with_matched_policy(Some(matched_policy.clone()))
                    .with_reason(reason.clone())
                    .with_payload(serde_json::json!({
                        "qname": &p.qname,
                        "declared": &new_categories,
                        "broadens": broadens,
                        "action": action,
                    }));
            emit_audit(engine.audit.as_ref(), event);
            return err_json(&format!(
                "policy denied: {} (matched {})",
                reason, matched_policy
            ));
        }

        let matched_policy = decision.matched_policy();

        let updated = EffectDecl {
            symbol_id: symbol.symbol_id.clone(),
            declared,
            transitive: existing
                .as_ref()
                .map(|d| d.transitive.clone())
                .unwrap_or_default(),
            verification: existing.as_ref().and_then(|d| d.verification.clone()),
            confidence: existing.as_ref().and_then(|d| d.confidence),
            runtime: existing.as_ref().and_then(|d| d.runtime.clone()),
            matched_policy: matched_policy.clone(),
        };

        if let Err(e) =
            effects_store.put_effects(&ref_name, &symbol.symbol_id, &updated, &p.author_id)
        {
            let event =
                AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", "error")
                    .with_subject(&symbol.symbol_id)
                    .with_matched_policy(matched_policy.clone())
                    .with_reason(e.to_string())
                    .with_payload(serde_json::json!({
                        "qname": &p.qname,
                        "declared": &new_categories,
                        "broadens": broadens,
                        "action": action,
                    }));
            emit_audit(engine.audit.as_ref(), event);
            return err_json(&e.to_string());
        }

        let status = match &decision {
            Decision::Allow { .. } => "allowed",
            Decision::RequireApproval { .. } => "awaiting-approval",
            Decision::Deny { .. } => "denied",
            Decision::NoPolicyMatch => "no-policy-match",
        };

        let event = AuditEvent::new(event_types::EFFECT_DECLARE, &p.author_id, "agent", status)
            .with_subject(&symbol.symbol_id)
            .with_matched_policy(matched_policy.clone())
            .with_payload(serde_json::json!({
                "qname": &p.qname,
                "declared": &new_categories,
                "broadens": broadens,
                "action": action,
            }));
        emit_audit(engine.audit.as_ref(), event);

        serde_json::to_string(&serde_json::json!({
            "effect_decl": updated,
            "matched_policy": matched_policy,
            "status": status,
            "action": action,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Return execution trace records stored for a symbol (written by `asd trace`). Returns newest-first, up to `limit` (default 20)."
    )]
    async fn traces(&self, params: Parameters<TracesOfParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index = AsgIndexStore::from_engine(&engine);
        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let prefix = format!("{}/traces/{}", paths::ASD_ROOT, symbol.symbol_id);
        let limit = p.limit.unwrap_or(20).min(200);
        let leaf_paths = match engine.repo.list_paths(&ref_name, &prefix, None) {
            Ok(v) => v,
            Err(_) => Vec::new(),
        };
        let mut traces: Vec<serde_json::Value> = Vec::new();
        for path in leaf_paths.iter().take(limit * 4) {
            if let Ok(v) = engine.repo.get_json(&ref_name, path) {
                if traces.len() < limit {
                    traces.push(v);
                }
            }
        }
        serde_json::to_string(&serde_json::json!({
            "symbol_id": symbol.symbol_id,
            "qname": p.qname,
            "count": traces.len(),
            "traces": traces,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Re-parse a source file or directory and refresh the ASD symbol index, effects, and call graph. Accepts absolute or relative paths. Equivalent to running `asd index <path>` from the CLI. After indexing, call the `sync` tool (or the pre-commit hook runs `asd sync --prune` automatically) to flush the updated state into the .asd/v1/ sidecar so it travels with the next git commit."
    )]
    async fn reindex(&self, params: Parameters<ReindexParams>) -> String {
        let p = params.0;
        let root = std::path::PathBuf::from(&p.path);
        if !root.exists() {
            return err_json(&format!("path does not exist: {}", p.path));
        }
        let adapters = default_adapters();
        let engine = self.engine.lock().await;
        match agentstatedeveloper_core::run_index(
            &engine.repo,
            &engine.ref_name,
            &root,
            "asd-mcp",
            &adapters,
            Some(engine.audit.as_ref()),
            None,
            None,
            Some(&self.db_path()),
        ) {
            Ok(s) => serde_json::json!({
                "path": p.path,
                "files": s.files,
                "skipped": s.skipped,
                "symbols": s.symbols,
                "edges": s.edges,
                "intra_module_edges": s.intra_module_edges,
                "cross_module_edges": s.cross_module_edges,
                "transitive_updates": s.transitive_updates,
                "orphaned_tagged": s.orphaned_tagged,
                "orphaned_untagged": s.orphaned_untagged,
                "stale_pruned": s.stale_pruned,
                "stale_rebound": s.stale_rebound,
                "ledger_entries_rebound": s.ledger_entries_rebound,
                "stale_kept": s.stale_kept,
                "orphaned_effects_pruned": s.orphaned_effects_pruned,
                "code_entries_pruned": s.code_entries_pruned,
            })
            .to_string(),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Flush live ASG state (symbols, effects, ledger, rebinds) into the `.asd/v1/` sidecar so it travels with the next `git commit`. CALL THIS after `reindex` (or edits) so committed state stays current — the reindex tool tells you to. `prune` also drops orphaned sidecar files for symbols that no longer exist. `dir` defaults to the active db's directory. (CLI: `asd sync [--prune]`.)"
    )]
    async fn sync(&self, params: Parameters<SyncParams>) -> String {
        let p = params.0;
        let dir = match p.dir {
            Some(d) => std::path::PathBuf::from(d),
            None => std::path::PathBuf::from(&self.db_path())
                .parent()
                .map(|d| d.to_path_buf())
                .unwrap_or_else(|| std::path::PathBuf::from(".")),
        };
        let engine = self.engine.lock().await;
        match agentstatedeveloper_core::sync_to_dir(&engine.repo, &engine.ref_name, &dir) {
            Ok(mut summary) => {
                if p.prune {
                    summary.pruned = agentstatedeveloper_core::prune_sidecar(
                        &engine.repo,
                        &engine.ref_name,
                        &dir,
                    )
                    .unwrap_or(0);
                }
                // Cache vs store vs sidecar: an entry the store lost is
                // absent from the sidecar too, so say so rather than report
                // a clean export. `asd repair --fix` restores it.
                let ledger = agentstatedeveloper_core::ledger_counts(
                    &engine.repo,
                    &engine.ref_name,
                    engine.fts.as_ref(),
                    Some(&dir),
                )
                .ok();
                let ledger_warning = ledger.as_ref().and_then(|l| l.warning());
                serde_json::json!({
                    "symbols_written": summary.symbols_written,
                    "effects_written": summary.effects_written,
                    "ledger_entries_written": summary.ledger_entries_written,
                    "rebinds_synced": summary.rebinds_synced,
                    "pruned": summary.pruned,
                    "moved_entries_removed": summary.moved_entries_removed,
                    "schema_version": summary.schema_version,
                    "ledger": ledger,
                    "ledger_warning": ledger_warning,
                })
                .to_string()
            }
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Summarize raw test-runner output into a compact, failures-only report: { runner, passed, failed, failures[] }. Cargo and pytest are parsed precisely; other runners via a generic scan. CALL THIS WHEN you've run a test suite and want just the failures (with names + detail) instead of scrolling thousands of lines of passing output. Pass the raw output as `output`. (CLI: `cargo test 2>&1 | asd test-summary`.)"
    )]
    async fn test_summary(&self, params: Parameters<TestSummaryParams>) -> String {
        let s = agentstatedeveloper_core::test_summary::summarize(&params.0.output);
        serde_json::json!({
            "runner": s.runner,
            "passed": s.passed,
            "failed": s.failed,
            "failures": s.failures.iter().map(|f| serde_json::json!({
                "name": f.name,
                "detail": f.detail,
            })).collect::<Vec<_>>(),
        })
        .to_string()
    }

    #[tool(
        description = "Initial-read project map for a cold start: package boundaries and test-file roles (fast-test vs diagnostic-test), and — unless `dry_run` — writes them as Ownership ledger entries so the NEXT session inherits the mental model without re-deriving it. CALL THIS ONCE when first orienting on an indexed repo. Idempotent (re-running overwrites its own tags). Unlike `architecture` (read-only overview), map PERSISTS role/ownership tags. (CLI: `asd map`.)"
    )]
    async fn map(&self, params: Parameters<MapParams>) -> String {
        let engine = self.engine.lock().await;
        let db_path = self.db_path();
        let db_parent = std::path::Path::new(&db_path).parent();
        match agentstatedeveloper_core::map::run_map(
            &engine,
            "asd-mcp",
            db_parent,
            params.0.dry_run,
        ) {
            Ok(payload) => payload.to_string(),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Record that a symbol was renamed or moved. Writes a rebind record so the old symbol_id maps to the new one, then re-parents all ledger entries from the old symbol_id to the new one. Use this whenever an agent or human renames a function, class, or method so its ledger history follows the rename."
    )]
    async fn ledger_rebind(&self, params: Parameters<LedgerRebindParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = &engine.ref_name;

        // Policy gate — evaluate before any writes
        let situation = Situation::new("rebind symbol")
            .with_qualifier("from_symbol_id", &p.from_symbol_id)
            .with_qualifier("to_qname", &p.to_qname);
        match engine
            .policy
            .evaluate(&situation, actions::LEDGER_REBIND, &p.agent_id)
        {
            Ok(Decision::Deny {
                matched_policy,
                reason,
            }) => {
                return serde_json::json!({
                    "policy_denied": true,
                    "matched_policy": matched_policy,
                    "reason": reason,
                })
                .to_string();
            }
            Ok(_) => {}
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        }

        // Resolve new qname → Symbol via index
        let index_store = AsgIndexStore::from_engine(&engine);
        let new_symbol = match index_store.get_symbol_by_qname(ref_name, &p.to_qname) {
            Ok(Some(s)) => s,
            Ok(None) => {
                return serde_json::json!({
                    "error": format!("symbol not found for qname '{}'", p.to_qname)
                })
                .to_string();
            }
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        };

        // An id with nothing filed under it is most likely a typo.
        match AsgLedgerStore::from_engine(&engine)
            .list_entries_with_superseded(ref_name, &p.from_symbol_id)
        {
            Ok(entries) if entries.is_empty() => {
                return serde_json::json!({
                    "error": format!("no ledger entries are filed under {}", p.from_symbol_id)
                })
                .to_string();
            }
            Ok(_) => {}
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        }

        let outcome = match agentstatedeveloper_core::rebind_ledger(
            &engine.repo,
            engine.fts.as_ref(),
            ref_name,
            &[(p.from_symbol_id.clone(), new_symbol)],
            &p.agent_id,
        ) {
            Ok(mut outcomes) => outcomes.remove(0),
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        };

        let audit_event =
            AuditEvent::new(event_types::LEDGER_REBIND, &p.agent_id, "agent", "allow")
                .with_subject(outcome.from_symbol_id.clone())
                .with_secondary(outcome.to_symbol_id.clone())
                .with_payload(serde_json::json!({
                    "from_symbol_id": outcome.from_symbol_id,
                    "to_symbol_id": outcome.to_symbol_id,
                    "to_qname": outcome.to_qname,
                    "entries_reparented": outcome.entries_moved,
                }));
        emit_audit(engine.audit.as_ref(), audit_event);

        serde_json::json!({
            "from_symbol_id": outcome.from_symbol_id,
            "to_symbol_id": outcome.to_symbol_id,
            "to_qname": outcome.to_qname,
            "entries_reparented": outcome.entries_moved,
        })
        .to_string()
    }

    #[tool(
        description = "Read back audit events from the configured JSONL log. Supports filtering by event_type substring, exact actor_id, exact outcome, and a `since` cursor. Returns `configured: false` when ASD_AUDIT_LOG was not set at server startup."
    )]
    async fn audit_tail(&self, params: Parameters<AuditTailParams>) -> String {
        let p = params.0;
        let Some(path) = self.audit_log_path.as_ref() else {
            return serde_json::to_string(&serde_json::json!({
                "configured": false,
                "count": 0,
                "events": [],
            }))
            .unwrap_or_else(|_| "{}".to_string());
        };
        let events = match agentstatedeveloper_core::read_jsonl(path) {
            Ok(v) => v,
            Err(e) => return err_json(&format!("read audit log: {}", e)),
        };

        let start_idx = match p.since {
            Some(ref id) => events
                .iter()
                .position(|e| &e.event_id == id)
                .map(|i| i + 1)
                .unwrap_or(0),
            None => 0,
        };

        let limit = p.limit.unwrap_or(200).min(1000) as usize;
        let filtered: Vec<&agentstatedeveloper_core::AuditEvent> = events[start_idx..]
            .iter()
            .filter(|e| {
                if let Some(ref t) = p.event_type {
                    if !e.event_type.contains(t) {
                        return false;
                    }
                }
                if let Some(ref a) = p.actor {
                    if &e.actor_id != a {
                        return false;
                    }
                }
                if let Some(ref o) = p.outcome {
                    if &e.outcome != o {
                        return false;
                    }
                }
                true
            })
            .take(limit)
            .collect();

        serde_json::to_string(&serde_json::json!({
            "configured": true,
            "path": path.display().to_string(),
            "count": filtered.len(),
            "events": filtered,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Verify the hash-chain integrity of the configured audit log. Commercial feature (Enterprise tier) — requires asd-pro."
    )]
    async fn audit_verify(&self) -> String {
        serde_json::to_string(&serde_json::json!({
            "configured": self.audit_log_path.is_some(),
            "verified": false,
            "error": "audit verify is a commercial feature (Enterprise tier) — install asd-pro",
            "upgrade_url": "https://agentstatedeveloper.dev/pricing",
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    // -- Scratch tools -------------------------------------------------------

    #[tool(
        description = "Write a new draft scratch entry. Scratch entries are local-only working notes scoped to a symbol/workflow/session. No policy gate — write freely. Returns { scratch_id, status }.\n\nSet planning=true to write pre-implementation design notes: the 'planning' tag is added automatically, and the symbol name does not need to exist in the index yet (useful for naming planned modules or interfaces before any code is written)."
    )]
    async fn scratch_write(&self, params: Parameters<ScratchWriteParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgScratchStore { repo: &engine.repo };

        let is_planning = p.planning.unwrap_or(false);

        let mut entry = ScratchEntry::new(&p.content, "asd-mcp");
        entry.workflow = p.workflow;
        entry.tags = p.tags.unwrap_or_default();

        if is_planning && !entry.tags.contains(&"planning".to_string()) {
            entry.tags.push("planning".to_string());
        }

        if let Some(ttl_h) = p.ttl_hours {
            entry.expires_at = Some(chrono::Utc::now() + chrono::Duration::hours(ttl_h));
        }

        // Resolve symbol to symbol_id. In planning mode, an unresolved qname
        // is stored as the workflow name (prefixed) rather than an error.
        if let Some(ref qname) = p.symbol {
            let index = AsgIndexStore::from_engine(&engine);
            match index.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(sym)) => {
                    entry.symbol_id = Some(sym.symbol_id);
                }
                Ok(None) if is_planning => {
                    // Symbol doesn't exist yet — store the intended qname as
                    // the workflow so it's filterable and visible in scratch_list.
                    if entry.workflow.is_none() {
                        entry.workflow = Some(format!("planned:{qname}"));
                    }
                }
                Ok(None) => return err_json(&format!("symbol not found: {qname}")),
                Err(e) => return err_json(&e.to_string()),
            }
        }

        match store.write_entry(&ref_name, &entry, "asd-mcp") {
            Ok(stored) => serde_json::to_string(&serde_json::json!({
                "scratch_id": stored.scratch_id,
                "status": "draft",
                "planning": is_planning,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "List scratch entries. Default: draft status, non-expired. Use status=null to see all. Returns { entries: [...], count }."
    )]
    async fn scratch_list(&self, params: Parameters<ScratchListParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgScratchStore { repo: &engine.repo };

        let status = match p.status.as_deref() {
            Some("promoted") => Some(ScratchStatus::Promoted),
            Some("discarded") => Some(ScratchStatus::Discarded),
            Some("draft") | None => Some(ScratchStatus::Draft),
            Some(other) => return err_json(&format!("unknown status: {other}")),
        };

        let mut filter = ScratchFilter {
            workflow: p.workflow,
            session: p.session,
            status,
            exclude_expired: true,
            symbol_id: None,
        };

        if let Some(ref qname) = p.symbol {
            let index = AsgIndexStore::from_engine(&engine);
            match index.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(sym)) => {
                    filter.symbol_id = Some(sym.symbol_id);
                }
                Ok(None) => return err_json(&format!("symbol not found: {qname}")),
                Err(e) => return err_json(&e.to_string()),
            }
        }

        match store.list_entries(&ref_name, &filter) {
            Ok(mut entries) => {
                entries.truncate(p.limit.max(1) as usize);
                let count = entries.len();
                serde_json::to_string(&serde_json::json!({
                    "entries": entries,
                    "count": count,
                }))
                .unwrap_or_else(|_| "{}".to_string())
            }
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Read a single scratch entry by scratch_id. Returns the full ScratchEntry JSON."
    )]
    async fn scratch_read(&self, params: Parameters<ScratchReadParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgScratchStore { repo: &engine.repo };
        match store.read_entry(&ref_name, &p.scratch_id) {
            Ok(entry) => serde_json::to_string(&entry).unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Replace the content of an existing draft scratch entry. Returns the updated ScratchEntry."
    )]
    async fn scratch_update(&self, params: Parameters<ScratchUpdateParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgScratchStore { repo: &engine.repo };
        match store.update_entry(&ref_name, &p.scratch_id, &p.content, "asd-mcp") {
            Ok(entry) => serde_json::to_string(&entry).unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Mark a scratch entry as discarded (soft-delete). Use scratch_clean to permanently purge discarded entries. Returns { ok: true }."
    )]
    async fn scratch_discard(&self, params: Parameters<ScratchDiscardParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgScratchStore { repo: &engine.repo };
        match store.discard_entry(&ref_name, &p.scratch_id, "asd-mcp") {
            Ok(()) => r#"{"ok":true}"#.to_string(),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Promote a draft scratch entry to a durable ledger entry. Requires `kind` and a symbol (via `qname` or the entry's existing symbol_id). Goes through policy + audit. Returns { scratch_id, promoted_to, entry_id }."
    )]
    async fn scratch_promote(&self, params: Parameters<ScratchPromoteParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let scratch_store = AsgScratchStore { repo: &engine.repo };
        let ledger_store = AsgLedgerStore::from_engine(&engine);

        // 1. Read scratch entry.
        let entry = match scratch_store.read_entry(&ref_name, &p.scratch_id) {
            Ok(e) => e,
            Err(e) => return err_json(&e.to_string()),
        };

        // 2. Resolve symbol_id.
        let symbol_id = if let Some(ref qname) = p.qname {
            let index = AsgIndexStore::from_engine(&engine);
            match index.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(sym)) => sym.symbol_id,
                Ok(None) => return err_json(&format!("symbol not found: {qname}")),
                Err(e) => return err_json(&e.to_string()),
            }
        } else if let Some(ref sid) = entry.symbol_id {
            sid.clone()
        } else {
            return err_json("no symbol attached to scratch entry and qname was not provided");
        };

        // 3. Parse ledger kind.
        let kind = match parse_ledger_kind(&p.kind) {
            Ok(k) => k,
            Err(e) => return err_json(&e),
        };

        // 4. Build summary.
        let summary = p.summary.unwrap_or_else(|| {
            entry
                .content
                .lines()
                .find(|l| !l.trim().is_empty())
                .unwrap_or(&entry.content)
                .chars()
                .take(140)
                .collect()
        });

        // 5. Create LedgerEntry.
        let author = Author {
            kind: AuthorKind::Agent,
            id: "asd-mcp".to_string(),
        };
        let mut ledger_entry = LedgerEntry::new(&symbol_id, kind, &summary, author);
        ledger_entry.body = Some(entry.content.clone());

        if let Err(e) = ledger_store.append_entry(&ref_name, &ledger_entry, "asd-mcp") {
            return err_json(&e.to_string());
        }

        // 6. Mark scratch promoted.
        match scratch_store.mark_promoted(
            &ref_name,
            &entry.scratch_id,
            &ledger_entry.entry_id,
            "asd-mcp",
        ) {
            Ok(promoted) => serde_json::to_string(&serde_json::json!({
                "scratch_id": promoted.scratch_id,
                "promoted_to": ledger_entry.entry_id,
                "entry_id": ledger_entry.entry_id,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Permanently delete scratch entries matching the filter. Returns { deleted: N }. Use dry_run=true to preview without deleting."
    )]
    async fn scratch_clean(&self, params: Parameters<ScratchCleanParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgScratchStore { repo: &engine.repo };

        let statuses: Vec<ScratchStatus> = p
            .statuses
            .split(',')
            .filter_map(|t| match t.trim() {
                "draft" => Some(ScratchStatus::Draft),
                "promoted" => Some(ScratchStatus::Promoted),
                "discarded" => Some(ScratchStatus::Discarded),
                _ => None,
            })
            .collect();

        let filter = CleanFilter {
            older_than: Some(chrono::Duration::hours(p.older_than_hours as i64)),
            statuses,
        };

        match store.clean_entries(&ref_name, &filter, p.dry_run) {
            Ok(count) => serde_json::to_string(
                &serde_json::json!({ "deleted": count, "dry_run": p.dry_run }),
            )
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "One-call agent-ready context package for a planned change. Composes investigate + impact + checklist: design_invariants, known_hazards, entry_points by layer, likely_edit_files (with recency), affected_tests, effects_summary, and recently_touched git history. Use this as the first call before any non-trivial code change."
    )]
    async fn prepare_change(&self, params: Parameters<PrepareChangeParams>) -> String {
        let p = params.0;
        let intent = p.intent.as_deref().and_then(parse_intent).unwrap_or("");
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let (mut tokens, mut exclusions) = parse_query(&p.description);
        if let Some(ref excl) = p.exclude {
            for term in excl
                .split(',')
                .map(|t| t.trim().to_lowercase())
                .filter(|t| !t.is_empty())
            {
                exclusions.push(term);
            }
        }
        if let Some(ref ctx_text) = p.task_context {
            let (ctx_tokens, _) = parse_query(ctx_text);
            for t in ctx_tokens {
                if !tokens.contains(&t) {
                    tokens.push(t);
                }
            }
        }

        if tokens.is_empty() {
            return serde_json::json!({ "description": p.description, "entry_points": {} })
                .to_string();
        }

        let depth = p.depth.max(1) as usize;
        let test_depth = p.test_depth.max(1) as usize;
        let git_depth = p.git_depth.max(1) as usize;
        let mut paths_filter: Vec<String> = Vec::new();
        if let Some(ref scope) = p.scope {
            paths_filter.extend(resolve_scope(scope, &db_path));
        }
        if let Some(ref paths) = p.paths {
            paths_filter.extend(
                paths
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty()),
            );
        }
        let filters = FtsFilters {
            kind: p.kind.as_deref().map(|k| k.to_lowercase()),
            language: p.language.as_deref().map(|l| l.to_lowercase()),
            include_tests: p.include_tests,
            tests_only: false,
            exclude_terms: exclusions,
            paths_filter,
            exclude_paths: Vec::new(),
            exclude_languages: Vec::new(),
        };

        let index = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);

        // One bulk id-map read (the per-qname loop this replaces was
        // minutes at 10k symbols on a cold FTS cache, holding the
        // engine mutex). Matches the CLI twin (prepare_change.rs).
        let id_map = index.build_id_map(&engine);

        let mut candidates = find_candidates(
            &engine,
            &p.description,
            &tokens,
            &filters,
            &ledger_store,
            &index,
            depth,
        );

        // Apply durable feedback adjustments.
        {
            use agentstatedeveloper_core::{FeedbackStore, apply_feedback_adjustments};
            let fb_store = AsgFeedbackStore::from_engine(&engine);
            let fb = fb_store.flat_verdicts(&ref_name).unwrap_or_default();
            apply_feedback_adjustments(&engine, &index, &p.description, &mut candidates, &fb);
        }

        let recency = gather_recency(200, 14.0);
        let layer_order = intent_layer_order(intent);

        // Plan M t-004 (1.0.98): scoring walk lifted to
        // agentstatedeveloper_core::prepare_change. Single source of
        // truth shared with the CLI handler. MCP entry_points now
        // include confidence/bucket/match_reasons (previously
        // CLI-only) and likely_edit_files carries conflict_detail —
        // additive enrichments, no field removals.
        let agg = agentstatedeveloper_core::aggregate_candidate_data(
            &engine,
            &index,
            &ledger_store,
            &effect_store,
            &candidates,
            &tokens,
            &recency,
            &layer_overrides,
        );
        let agentstatedeveloper_core::CandidateAggregates {
            mut by_layer,
            mut design_invariants,
            known_hazards,
            validation_scenarios_ledger,
            effects_summary,
            mut file_scores,
            top_sym_id,
            mut seen_inv,
        } = agg;
        let propagated = agentstatedeveloper_core::propagate_caller_invariants(
            &engine,
            &index,
            &ledger_store,
            &db_path,
            &candidates,
            &mut seen_inv,
        );
        design_invariants.extend(propagated);

        // Reorder by_layer.
        let mut ordered: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
        for lk in layer_order {
            if let Some(v) = by_layer.remove(*lk) {
                ordered.insert(lk.to_string(), v);
            }
        }

        let dirty_files_pc = git_dirty_files();
        let likely_edit_files =
            agentstatedeveloper_core::finalize_file_scores(&mut file_scores, &dirty_files_pc, true);

        // Affected tests via BFS from top entry point.
        let mut affected_tests: Vec<serde_json::Value> = Vec::new();
        if let Some(start_id) = top_sym_id {
            let mut visited: HashSet<String> = HashSet::new();
            let mut queue: VecDeque<(String, usize)> = VecDeque::new();
            let mut seen_tnames: HashSet<String> = HashSet::new();
            visited.insert(start_id.clone());
            queue.push_back((start_id, 0));
            while let Some((sid, depth)) = queue.pop_front() {
                if depth >= test_depth {
                    continue;
                }
                let callers = index.get_callers(&ref_name, &sid).unwrap_or_default();
                for cid in callers {
                    if visited.contains(&cid) {
                        continue;
                    }
                    visited.insert(cid.clone());
                    if let Some(s) = id_map.get(&cid) {
                        if symbol_tier(&s.file) == 2 && seen_tnames.insert(s.qname.clone()) {
                            let qname_words: Vec<String> = s
                                .qname
                                .split(|c: char| !c.is_alphabetic())
                                .filter(|t: &&str| t.len() > 2)
                                .map(|t| t.to_lowercase())
                                .collect();
                            let doc_words: Vec<String> = s
                                .doc
                                .as_deref()
                                .unwrap_or("")
                                .split(|c: char| !c.is_alphabetic())
                                .filter(|t: &&str| t.len() > 2)
                                .map(|t| t.to_lowercase())
                                .collect();
                            let test_tokens: Vec<&str> = qname_words
                                .iter()
                                .chain(doc_words.iter())
                                .map(|s| s.as_str())
                                .collect();
                            let covers: Vec<&str> = design_invariants
                                .iter()
                                .filter_map(|inv| {
                                    inv.get("summary").and_then(serde_json::Value::as_str)
                                })
                                .filter(|sum| {
                                    let sl = sum.to_lowercase();
                                    test_tokens.iter().any(|t| sl.contains(*t))
                                })
                                .collect();
                            affected_tests.push(serde_json::json!({
                                "qname": s.qname, "file": s.file, "line": s.start.line,
                                "covers_invariants": covers,
                            }));
                        }
                        if depth + 1 < test_depth {
                            queue.push_back((cid, depth + 1));
                        }
                    }
                }
            }
        }

        // Recent git touches on top 3 files.
        let top_files: Vec<(String, usize)> = file_scores
            .iter()
            .take(3)
            .map(|(_, f, _, _, _, _, _)| (f.clone(), 0))
            .collect();
        let recently_touched = mcp_git_recent_touches(&top_files, git_depth);

        let test_gap = affected_tests.is_empty();
        let proposed_test_path = test_gap
            .then(|| {
                file_scores
                    .first()
                    .map(|(_, f, _, _, _, _, _)| propose_test_path(f))
            })
            .flatten();
        // Plan J t-007: language-aware test stub body — same trigger
        // as proposed_test_path. file_scores tuple = (score, file,
        // layer, days, hot, qname, why); element 5 is the symbol qname
        // used to derive the test name (snake_case for py/rs/rb/ts,
        // PascalCase for go/java/cs/kt/swift).
        let proposed_test_stub: Option<String> = if test_gap {
            file_scores.first().map(|(_, file, _, _, _, qname, _)| {
                agentstatedeveloper_core::propose_test_stub(file, qname)
            })
        } else {
            None
        };
        // 1.0.86: emit refs for invariant-derived hints (dedupes
        // against design_invariants[].summary); keep effects + cold-
        // start as inline hints (genuinely new content).
        let suggested_test_coverage: Vec<serde_json::Value> = if test_gap {
            let mut out: Vec<serde_json::Value> = Vec::new();
            let mut seen: HashSet<String> = HashSet::new();
            for inv in &design_invariants {
                if let Some(eid) = inv.get("entry_id").and_then(serde_json::Value::as_str) {
                    if seen.insert(format!("ref:{eid}")) {
                        out.push(serde_json::json!({ "ref": eid }));
                    }
                }
            }
            for eff in &effects_summary {
                if let Some(cat) = eff.get("category").and_then(serde_json::Value::as_str) {
                    let hint = format!("verify {} after change", cat.to_lowercase());
                    if seen.insert(format!("hint:{hint}")) {
                        out.push(serde_json::json!({ "hint": hint }));
                    }
                }
            }
            if design_invariants.is_empty() {
                if let Some((_, qname)) = candidates.first() {
                    if let Ok(Some(sym)) = index.get_symbol_by_qname(&ref_name, qname) {
                        for h in derive_cold_hints(
                            &sym.qname,
                            sym.signature.as_deref(),
                            sym.doc.as_deref(),
                        ) {
                            if seen.insert(format!("hint:{h}")) {
                                out.push(serde_json::json!({ "hint": h }));
                            }
                        }
                    }
                }
            }
            out
        } else {
            vec![]
        };

        const CONSTRAINT_WORDS: &[&str] = &[
            "must",
            "never",
            "shall",
            "always",
            "only",
            "cannot",
            "no ",
            "not ",
            "require",
            "ensure",
            "prevent",
            "guarantee",
            "invariant",
            "forbidden",
        ];
        // 1.0.86: emit refs against design_invariants[].entry_id
        // instead of duplicating summary text.
        let scenario_tests: Vec<serde_json::Value> = design_invariants
            .iter()
            .filter_map(|inv| {
                let summary = inv.get("summary").and_then(serde_json::Value::as_str)?;
                let entry_id = inv.get("entry_id").and_then(serde_json::Value::as_str)?;
                let sl = summary.to_lowercase();
                if CONSTRAINT_WORDS.iter().any(|w| sl.contains(w)) {
                    Some(serde_json::json!({ "ref": entry_id }))
                } else {
                    None
                }
            })
            .collect();

        // T1: safe-change recipe.  T4: manually_validate includes ValidationScenario entries.
        let recipe_inspect: Vec<serde_json::Value> = file_scores.iter()
            .map(|(score, file, layer, days, hot, top_symbol, why)| serde_json::json!({
                "file": file, "layer": layer, "score": score, "last_touched_days": days, "hot": hot,
                "top_symbol": top_symbol, "why": why,
            }))
            .collect();
        // 1.0.86: invariants emit refs; hazards stay inline (no
        // dedupe target in this response).
        let recipe_preserve: Vec<serde_json::Value> = design_invariants
            .iter()
            .filter_map(|inv| {
                inv.get("entry_id")
                    .and_then(serde_json::Value::as_str)
                    .map(|eid| serde_json::json!({ "ref": eid, "kind": "invariant" }))
            })
            .chain(known_hazards.iter().map(|h| {
                serde_json::json!({
                    "constraint": h["summary"],
                    "source": h["source"],
                    "kind": "hazard",
                })
            }))
            .collect();
        let recipe_edit: Vec<serde_json::Value> = likely_edit_files
            .iter()
            .filter(|f| f["file_role"].as_str() == Some("impl"))
            .cloned()
            .chain(
                likely_edit_files
                    .iter()
                    .filter(|f| f["file_role"].as_str() != Some("impl"))
                    .cloned(),
            )
            .collect();
        let recipe_run: Vec<serde_json::Value> = affected_tests.iter()
            .map(|t| serde_json::json!({ "qname": t["qname"], "file": t["file"], "covers_invariants": t["covers_invariants"] }))
            .collect();
        let mut recipe_manually_validate: Vec<serde_json::Value> =
            validation_scenarios_ledger.clone();
        for s in &scenario_tests {
            recipe_manually_validate.push(serde_json::json!({ "scenario": s, "source": "invariant", "kind": "constraint_check" }));
        }
        for eff in &effects_summary {
            let desc = format!(
                "verify {} side-effect still correct after change",
                eff["category"].as_str().unwrap_or("").to_lowercase()
            );
            recipe_manually_validate.push(serde_json::json!({ "scenario": desc, "source": eff["source"], "kind": "effect_check" }));
        }
        // Plan J t-002: when no affected tests exist, prepend a
        // missing_test item to the recipe so an agent reading only
        // the recipe sees the gap (without having to cross-reference
        // top-level `test_gap` field).
        if test_gap {
            let suggestion = proposed_test_path
                .as_deref()
                .unwrap_or("(no proposed path; see proposed_test_path)");
            recipe_manually_validate.push(serde_json::json!({
                "scenario": format!(
                    "No test currently exercises this change set. Add a test \
                     covering the planned edit; suggested target: {suggestion}"
                ),
                "source": "test_gap",
                "kind": "missing_test",
            }));
        }
        // AcmeFlow refinement #1 (1.0.84): recursively drop
        // empty sub-fields. Matches CLI prepare_change handling.
        let safe_change_recipe =
            agentstatedeveloper_core::drop_empty_recursive(serde_json::json!({
                "inspect": recipe_inspect,
                "preserve": recipe_preserve,
                "edit": recipe_edit,
                "run": recipe_run,
                "manually_validate": recipe_manually_validate,
            }));

        let focus = intent_focus(intent);
        let layers_present_pc: std::collections::HashSet<&str> = file_scores
            .iter()
            .map(|(_, _, layer, _, _, _, _)| layer.as_str())
            .collect();
        let ambiguous_terms = detect_ambiguous_tokens(&tokens, engine.fts.as_ref(), &filters);
        let possible_misses =
            detect_possible_misses(&p.description, &layers_present_pc, file_scores.len());
        // Plan G t-006: surface captured thinking on the symbols that
        // matter for this query. Pull top_symbol off each likely_edit_files
        // entry; gather_prior_thinking walks the ledger and projects to the
        // compact `prior_thinking` shape (or Value::Null if nothing to surface).
        let thinking_qnames: Vec<String> = likely_edit_files
            .iter()
            .filter_map(|f| {
                f.get("top_symbol")
                    .and_then(serde_json::Value::as_str)
                    .map(String::from)
            })
            .collect();
        // AcmeFlow refinement (2026-06-04): gather now returns
        // PriorThinking { entries, summary }. `thinking_summary` always
        // emits (load-bearing signal: tells agents whether thinking
        // exists but was filtered, vs. doesn't exist at all).
        let pt = thinking::gather_prior_thinking(
            &engine,
            &thinking_qnames,
            thinking::DEFAULT_CONFIDENCE_FLOOR,
        );
        let prior_thinking = pt.entries;
        let thinking_summary = pt.summary;

        let full = serde_json::json!({
            "description": p.description,
            "task_context": p.task_context,
            "intent": if intent.is_empty() { serde_json::Value::Null } else { serde_json::json!(intent) },
            "focus": if focus.is_empty() { serde_json::Value::Null } else { serde_json::json!(focus) },
            "ambiguous_terms": ambiguous_terms,
            "possible_misses": possible_misses,
            "safe_change_recipe": safe_change_recipe,
            "design_invariants": design_invariants,
            "known_hazards": known_hazards,
            "validation_scenarios": validation_scenarios_ledger,
            "entry_points": { "by_layer": ordered },
            "likely_edit_files": likely_edit_files,
            "affected_tests": affected_tests,
            "test_gap": test_gap,
            "proposed_test_path": proposed_test_path,
            "proposed_test_stub": proposed_test_stub,
            "suggested_test_coverage": suggested_test_coverage,
            "scenario_tests": scenario_tests,
            "effects_summary": effects_summary,
            "recently_touched": recently_touched,
            "prior_thinking": prior_thinking,
            "thinking_summary": thinking_summary,
            // AcmeFlow refinement (1.0.77): 24h soft threshold for
            // prepare-change (matches a typical dev day; index built
            // this morning is fine all afternoon). When age exceeds the
            // threshold but the query DID resolve, downstream UIs can
            // demote via `stale_severity == "soft"`. Loud severity
            // ("critical") fires on empty/broken FTS regardless of age.
            "stale": agentstatedeveloper_core::stale_warning_classified(
                &db_path,
                agentstatedeveloper_core::SOFT_STALE_THRESHOLD_SECS,
            )
                .as_ref()
                .map(|w| serde_json::Value::String(w.message.clone()))
                .unwrap_or(serde_json::Value::Null),
            "stale_severity": agentstatedeveloper_core::stale_warning_classified(
                &db_path,
                agentstatedeveloper_core::SOFT_STALE_THRESHOLD_SECS,
            )
                .as_ref()
                .map(|w| serde_json::to_value(w.severity).unwrap_or(serde_json::Value::Null))
                .unwrap_or(serde_json::Value::Null),
            "confidence": {
                "strong": "orientation across layers (app/engine/UI/persistence) for a feature-level change description",
                "weak": "narrow bug-fix work — verify each suggested file with `references` or `read` before editing; broad descriptions can surface unrelated files",
            },
        });
        // Plan F t-006: brief drops by_layer / recently_touched / scenario_tests
        // / suggested_test_coverage / effects_summary and trims likely_edit_files
        // to {file, why, top_symbol, layer}.
        let mut out = if brief::brief_from_env() {
            brief::brief_prepare_change(&full)
        } else {
            full
        };
        // Token economy (1.0.79): drop input echoes (the MCP client
        // just sent these) and dedupe stale string vs severity. Then
        // strip top-level null/[]/{} via drop_empty_top_level.
        if let Some(obj) = out.as_object_mut() {
            obj.remove("description");
            obj.remove("task_context");
            obj.remove("stale");
        }
        let out = agentstatedeveloper_core::drop_empty_top_level(out);
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Pre-edit checklist for a query: files to inspect, invariants to preserve, tests to run, known hazards, effects to verify (structured JSON). CALL THIS WHEN you want just the action list for a change described in words. For the fuller package (this checklist + entry points + likely edit files + blast radius) use `prepare_change`; if you already know the exact symbol you're changing, use `impact`. Takes a free-text `query` (not a qname)."
    )]
    async fn checklist(&self, params: Parameters<ChecklistParams>) -> String {
        let p = params.0;
        let intent = p.intent.as_deref().and_then(parse_intent).unwrap_or("");
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let (tokens, mut exclusions) = parse_query(&p.query);
        if let Some(ref excl) = p.exclude {
            for term in excl
                .split(',')
                .map(|t| t.trim().to_lowercase())
                .filter(|t| !t.is_empty())
            {
                exclusions.push(term);
            }
        }

        if tokens.is_empty() {
            return serde_json::json!({ "query": p.query, "files_to_inspect": [] }).to_string();
        }

        let depth = p.depth.max(1) as usize;
        let test_depth = p.test_depth.max(1) as usize;
        let mut paths_filter: Vec<String> = Vec::new();
        if let Some(ref scope) = p.scope {
            paths_filter.extend(resolve_scope(scope, &db_path));
        }
        if let Some(ref paths) = p.paths {
            paths_filter.extend(
                paths
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty()),
            );
        }
        let filters = FtsFilters {
            kind: p.kind.as_deref().map(|k| k.to_lowercase()),
            language: p.language.as_deref().map(|l| l.to_lowercase()),
            include_tests: p.include_tests,
            tests_only: false,
            exclude_terms: exclusions,
            paths_filter,
            exclude_paths: Vec::new(),
            exclude_languages: Vec::new(),
        };

        let index = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);

        // Build id_map for test BFS — one bulk read (same Plan T scale
        // fix as prepare_change/investigate).
        let id_map = index.build_id_map(&engine);

        let mut candidates = find_candidates(
            &engine,
            &p.query,
            &tokens,
            &filters,
            &ledger_store,
            &index,
            depth,
        );

        // Apply durable feedback adjustments.
        {
            use agentstatedeveloper_core::{FeedbackStore, apply_feedback_adjustments};
            let fb_store = AsgFeedbackStore::from_engine(&engine);
            let fb = fb_store.flat_verdicts(&ref_name).unwrap_or_default();
            apply_feedback_adjustments(&engine, &index, &p.query, &mut candidates, &fb);
        }

        let mut files_to_inspect: Vec<serde_json::Value> = Vec::new();
        let mut seen_files: HashSet<String> = HashSet::new();
        let mut invariants: Vec<serde_json::Value> = Vec::new();
        let mut hazards: Vec<serde_json::Value> = Vec::new();
        let mut effects_list: Vec<serde_json::Value> = Vec::new();
        let mut test_rows: Vec<serde_json::Value> = Vec::new();
        let mut seen_inv: HashSet<String> = HashSet::new();
        let mut seen_tests: HashSet<String> = HashSet::new();

        for (_score, qname) in &candidates {
            let sym = match index.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(s)) => s,
                _ => continue,
            };
            let tier = symbol_tier(&sym.file);
            let layer = classify_layer_sym(&sym.file, &sym.qname, tier, &layer_overrides);

            if seen_files.insert(sym.file.clone()) {
                files_to_inspect.push(serde_json::json!({
                    "file": sym.file, "qname": sym.qname, "layer": layer, "line": sym.start.line,
                }));
            }

            let entries = ledger_store
                .list_entries(&ref_name, &sym.symbol_id)
                .unwrap_or_default();
            for entry in &entries {
                match entry.kind {
                    LedgerKind::Invariant => {
                        if seen_inv.insert(entry.summary.clone()) {
                            invariants.push(serde_json::json!({
                                "summary": entry.summary, "source": sym.qname, "body": entry.body,
                            }));
                        }
                    }
                    LedgerKind::Hazard | LedgerKind::KnownBug => {
                        hazards.push(serde_json::json!({
                            "summary": entry.summary, "source": sym.qname,
                            "kind": entry.kind.as_str(), "body": entry.body,
                        }));
                    }
                    LedgerKind::ValidationScenario => {
                        if seen_inv.insert(entry.summary.clone()) {
                            invariants.push(serde_json::json!({
                                "summary": entry.summary, "source": sym.qname,
                                "kind": "validation_scenario", "body": entry.body,
                            }));
                        }
                    }
                    _ => {}
                }
            }

            if let Ok(Some(decl)) = effect_store.get_effects(&ref_name, &sym.symbol_id) {
                for eff in &decl.declared {
                    effects_list.push(serde_json::json!({
                        "category": format!("{:?}", eff.effect), "source": sym.qname,
                    }));
                }
            }

            // BFS for test callers.
            let mut visited: HashSet<String> = HashSet::new();
            let mut queue: VecDeque<(String, usize)> = VecDeque::new();
            visited.insert(sym.symbol_id.clone());
            queue.push_back((sym.symbol_id.clone(), 0));
            while let Some((sid, depth)) = queue.pop_front() {
                if depth >= test_depth {
                    continue;
                }
                let callers = index.get_callers(&ref_name, &sid).unwrap_or_default();
                for cid in callers {
                    if visited.contains(&cid) {
                        continue;
                    }
                    visited.insert(cid.clone());
                    if let Some(s) = id_map.get(&cid) {
                        if symbol_tier(&s.file) == 2 && seen_tests.insert(s.qname.clone()) {
                            test_rows.push(serde_json::json!({
                                "qname": s.qname, "file": s.file, "line": s.start.line,
                            }));
                        }
                        if depth + 1 < test_depth {
                            queue.push_back((cid, depth + 1));
                        }
                    }
                }
            }
        }

        let test_gap = test_rows.is_empty();
        let proposed_test_path = test_gap
            .then(|| {
                files_to_inspect
                    .first()
                    .and_then(|v| v.get("file").and_then(serde_json::Value::as_str))
                    .map(propose_test_path)
            })
            .flatten();
        let suggested_test_coverage: Vec<String> = if test_gap {
            let mut hints: Vec<String> = invariants
                .iter()
                .filter_map(|inv| inv.get("summary").and_then(serde_json::Value::as_str))
                .map(|s| s.to_string())
                .collect();
            for eff in &effects_list {
                if let Some(cat) = eff.get("category").and_then(serde_json::Value::as_str) {
                    let hint = format!("verify {} after change", cat.to_lowercase());
                    if !hints.contains(&hint) {
                        hints.push(hint);
                    }
                }
            }
            if invariants.is_empty() {
                if let Some((_, qname)) = candidates.first() {
                    if let Ok(Some(sym)) = index.get_symbol_by_qname(&ref_name, qname) {
                        for h in derive_cold_hints(
                            &sym.qname,
                            sym.signature.as_deref(),
                            sym.doc.as_deref(),
                        ) {
                            if !hints.contains(&h) {
                                hints.push(h);
                            }
                        }
                    }
                }
            }
            hints
        } else {
            vec![]
        };

        const CONSTRAINT_WORDS_CL: &[&str] = &[
            "must",
            "never",
            "shall",
            "always",
            "only",
            "cannot",
            "no ",
            "not ",
            "require",
            "ensure",
            "prevent",
            "guarantee",
            "invariant",
            "forbidden",
        ];
        let scenario_tests: Vec<&str> = invariants
            .iter()
            .filter_map(|inv| inv.get("summary").and_then(serde_json::Value::as_str))
            .filter(|s| {
                let sl = s.to_lowercase();
                CONSTRAINT_WORDS_CL.iter().any(|w| sl.contains(w))
            })
            .collect();

        // T-004: task-close proof suggestions.
        let task_close_suggestions: Vec<serde_json::Value> = {
            let mut suggestions = Vec::new();
            for inv in invariants.iter().take(4) {
                let source = inv
                    .get("source")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                let summary = inv
                    .get("summary")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                if !source.is_empty() && !summary.is_empty() {
                    suggestions.push(serde_json::json!({
                        "action": "ledger_append", "kind": "proof", "symbol": source,
                        "suggested_summary": format!("verified that {} holds after change", summary),
                    }));
                }
            }
            for h in hazards.iter().take(2) {
                let source = h
                    .get("source")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                let summary = h
                    .get("summary")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                if !source.is_empty() && !summary.is_empty() {
                    suggestions.push(serde_json::json!({
                        "action": "ledger_append", "kind": "validation_scenario", "symbol": source,
                        "suggested_summary": format!("validate that hazard '{}' was not triggered", summary),
                    }));
                }
            }
            for eff in effects_list.iter().take(2) {
                let source = eff
                    .get("source")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                let cat = eff
                    .get("category")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                if !source.is_empty() && !cat.is_empty() {
                    suggestions.push(serde_json::json!({
                        "action": "ledger_append", "kind": "proof", "symbol": source,
                        "suggested_summary": format!("verified {} side-effect is correct after change", cat.to_lowercase()),
                    }));
                }
            }
            suggestions
        };

        let focus = intent_focus(intent);
        let layers_present_cl: std::collections::HashSet<&str> = files_to_inspect
            .iter()
            .filter_map(|f| f.get("layer").and_then(serde_json::Value::as_str))
            .collect();
        let ambiguous_terms_cl = detect_ambiguous_tokens(&tokens, engine.fts.as_ref(), &filters);
        let possible_misses_cl =
            detect_possible_misses(&p.query, &layers_present_cl, files_to_inspect.len());
        serde_json::to_string(&serde_json::json!({
            "query": p.query,
            "intent": if intent.is_empty() { serde_json::Value::Null } else { serde_json::json!(intent) },
            "focus": if focus.is_empty() { serde_json::Value::Null } else { serde_json::json!(focus) },
            "ambiguous_terms": ambiguous_terms_cl,
            "possible_misses": possible_misses_cl,
            "files_to_inspect": files_to_inspect,
            "invariants_to_preserve": invariants,
            "tests_to_run": test_rows,
            "test_gap": test_gap,
            "proposed_test_path": proposed_test_path,
            "suggested_test_coverage": suggested_test_coverage,
            "scenario_tests": scenario_tests,
            "known_hazards": hazards,
            "effects_to_verify": effects_list,
            "task_close_suggestions": task_close_suggestions,
        })).unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Blast-radius analysis for ONE known symbol before editing it: transitive callers (to `depth`), aggregated effects, invariants/hazards from all callers, affected tests, recent git touches. CALL THIS WHEN you already have the exact `qname` you intend to change. If you only have a description of the change (no symbol name), use `checklist` or `prepare_change`; for a diff/PR use `since`. Requires `qname`."
    )]
    async fn impact(&self, params: Parameters<ImpactParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);

        let symbol = match index.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };

        let tier = symbol_tier(&symbol.file);
        let layer = classify_layer_sym(&symbol.file, &symbol.qname, tier, &layer_overrides);

        // Build id_map for call graph resolution — one bulk read (the
        // per-qname loop this replaces was minutes at 10k symbols on a
        // cold FTS cache, holding the engine mutex).
        let id_map = index.build_id_map(&engine);

        // BFS transitive callers.
        let max_depth = p.depth.max(1) as usize;
        let mut visited: HashSet<String> = HashSet::new();
        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
        visited.insert(symbol.symbol_id.clone());
        queue.push_back((symbol.symbol_id.clone(), 0));

        let mut caller_rows: Vec<serde_json::Value> = Vec::new();
        let mut affected_test_rows: Vec<serde_json::Value> = Vec::new();
        let mut touched_files: Vec<(String, usize)> = vec![(symbol.file.clone(), 0)];

        while let Some((sym_id, depth)) = queue.pop_front() {
            if depth >= max_depth {
                continue;
            }
            let neighbors = index.get_callers(&ref_name, &sym_id).unwrap_or_default();
            for nbr_id in neighbors {
                if visited.contains(&nbr_id) {
                    continue;
                }
                visited.insert(nbr_id.clone());
                if let Some(s) = id_map.get(&nbr_id) {
                    let t = symbol_tier(&s.file);
                    let l = classify_layer_sym(&s.file, &s.qname, t, &layer_overrides);
                    let row = serde_json::json!({
                        "qname": s.qname,
                        "file": s.file,
                        "line": s.start.line,
                        "depth": depth + 1,
                        "layer": l,
                    });
                    if t == 2 {
                        affected_test_rows.push(row);
                    } else {
                        caller_rows.push(row);
                    }
                    if !touched_files.iter().any(|(f, _)| f == &s.file) {
                        touched_files.push((s.file.clone(), depth + 1));
                    }
                    if depth + 1 < max_depth {
                        queue.push_back((nbr_id, depth + 1));
                    }
                }
            }
        }

        // Collect invariants/hazards/validation_scenarios/known_bugs
        // from target + all callers. Plan J t-013 extends the prior
        // (invariants + hazards only) shape to surface
        // ValidationScenario and KnownBug — same blast-radius
        // pattern, same `source_symbol_id` annotation. Invariants are
        // deduped by summary; the other kinds aren't (callers want
        // every instance for impact reasoning).
        // Pre-existing bug surfaced by Plan J t-013 tests: `visited`
        // already contains the target symbol, so chain(once(target),
        // visited) walked the target's ledger twice. Dedupe at source.
        let mut seen_ids: HashSet<String> = HashSet::new();
        let all_sym_ids: Vec<String> = std::iter::once(symbol.symbol_id.clone())
            .chain(visited.iter().cloned())
            .filter(|id| seen_ids.insert(id.clone()))
            .collect();
        let mut all_invariants: Vec<serde_json::Value> = Vec::new();
        let mut all_hazards: Vec<serde_json::Value> = Vec::new();
        let mut all_validation_scenarios: Vec<serde_json::Value> = Vec::new();
        let mut all_known_bugs: Vec<serde_json::Value> = Vec::new();
        let mut seen_inv: HashSet<String> = HashSet::new();
        for sym_id in &all_sym_ids {
            let entries = ledger_store
                .list_entries(&ref_name, sym_id)
                .unwrap_or_default();
            for entry in entries {
                let key = entry.summary.clone();
                match entry.kind {
                    LedgerKind::Invariant => {
                        if seen_inv.insert(key) {
                            let mut v = serde_json::to_value(&entry).unwrap_or_default();
                            if let Some(obj) = v.as_object_mut() {
                                obj.insert(
                                    "source_symbol_id".to_string(),
                                    serde_json::json!(sym_id),
                                );
                            }
                            all_invariants.push(v);
                        }
                    }
                    LedgerKind::Hazard => {
                        let mut v = serde_json::to_value(&entry).unwrap_or_default();
                        if let Some(obj) = v.as_object_mut() {
                            obj.insert("source_symbol_id".to_string(), serde_json::json!(sym_id));
                        }
                        all_hazards.push(v);
                    }
                    LedgerKind::ValidationScenario => {
                        let mut v = serde_json::to_value(&entry).unwrap_or_default();
                        if let Some(obj) = v.as_object_mut() {
                            obj.insert("source_symbol_id".to_string(), serde_json::json!(sym_id));
                        }
                        all_validation_scenarios.push(v);
                    }
                    LedgerKind::KnownBug => {
                        let mut v = serde_json::to_value(&entry).unwrap_or_default();
                        if let Some(obj) = v.as_object_mut() {
                            obj.insert("source_symbol_id".to_string(), serde_json::json!(sym_id));
                        }
                        all_known_bugs.push(v);
                    }
                    _ => {}
                }
            }
        }

        // Effects for the target symbol.
        let effects = effect_store
            .get_effects(&ref_name, &symbol.symbol_id)
            .unwrap_or(None);

        // Recent git touches.
        let git_depth = p.git_depth.max(1) as usize;
        let recently_touched = mcp_git_recent_touches(&touched_files, git_depth);

        let mut sym_val = serde_json::to_value(&symbol).unwrap_or_default();
        if let Some(obj) = sym_val.as_object_mut() {
            obj.remove("body");
        }

        serde_json::to_string(&serde_json::json!({
            "symbol": sym_val,
            "layer": layer,
            "caller_count": caller_rows.len(),
            "test_count": affected_test_rows.len(),
            "invariants": all_invariants,
            "hazards": all_hazards,
            "validation_scenarios": all_validation_scenarios,
            "known_bugs": all_known_bugs,
            "effects": effects,
            "callers": caller_rows,
            "affected_tests": affected_test_rows,
            "recently_touched": recently_touched,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    /// Symbols in files changed since a commit + combined blast radius.
    /// PR-review workflow: pass the base SHA to get full impact without knowing any symbol names.
    #[tool(
        description = "Symbols in files changed since a commit and their combined blast radius. Pass the base SHA of a branch/PR to discover all symbols touched by the diff, their transitive callers, affected tests, invariants, hazards, and effects — without needing to know any symbol names upfront."
    )]
    async fn since(&self, params: Parameters<SinceParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let index = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);

        // Build id_map — one bulk read (same Plan T scale fix as
        // prepare_change/investigate).
        let id_map = index.build_id_map(&engine);

        // Get changed files.
        let changed_files: Vec<String> = {
            let out = Proc::new("git")
                .args(["diff", "--name-only", &format!("{}..HEAD", p.sha)])
                .output();
            match out {
                Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .filter(|l| !l.is_empty())
                    .map(|l| l.to_string())
                    .collect(),
                _ => vec![],
            }
        };

        if changed_files.is_empty() {
            return serde_json::to_string(&serde_json::json!({
                "sha": p.sha, "changed_files": [], "touched_symbols": {},
                "callers": [], "affected_tests": [], "invariants": [], "hazards": [], "effects": [],
            }))
            .unwrap_or_else(|_| "{}".to_string());
        }

        let changed_set: HashSet<&str> = changed_files.iter().map(String::as_str).collect();

        // Seeds: all symbols in changed files.
        let seed_ids: Vec<String> = id_map
            .values()
            .filter(|s| changed_set.contains(s.file.as_str()))
            .map(|s| s.symbol_id.clone())
            .collect();

        // Group touched symbols by layer.
        let mut by_layer: std::collections::HashMap<String, Vec<serde_json::Value>> =
            std::collections::HashMap::new();
        for sid in &seed_ids {
            if let Some(s) = id_map.get(sid) {
                let tier = symbol_tier(&s.file);
                let layer = classify_layer_sym(&s.file, &s.qname, tier, &layer_overrides);
                by_layer
                    .entry(layer.to_string())
                    .or_default()
                    .push(serde_json::json!({
                        "qname": s.qname, "file": s.file, "line": s.start.line, "layer": layer,
                    }));
            }
        }

        // BFS blast radius.
        let max_depth = p.depth.max(1) as usize;
        let mut visited: HashSet<String> = seed_ids.iter().cloned().collect();
        let mut queue: VecDeque<(String, usize)> =
            seed_ids.iter().map(|id| (id.clone(), 0)).collect();
        let mut caller_rows: Vec<serde_json::Value> = Vec::new();
        let mut affected_test_rows: Vec<serde_json::Value> = Vec::new();
        let mut touched_files: Vec<(String, usize)> =
            changed_files.iter().map(|f| (f.clone(), 0)).collect();
        let mut seen_files: HashSet<String> = changed_files.iter().cloned().collect();

        while let Some((sym_id, depth)) = queue.pop_front() {
            if depth >= max_depth {
                continue;
            }
            let neighbors = index.get_callers(&ref_name, &sym_id).unwrap_or_default();
            for nbr_id in neighbors {
                if visited.contains(&nbr_id) {
                    continue;
                }
                visited.insert(nbr_id.clone());
                if let Some(s) = id_map.get(&nbr_id) {
                    let t = symbol_tier(&s.file);
                    let l = classify_layer_sym(&s.file, &s.qname, t, &layer_overrides);
                    let row = serde_json::json!({
                        "qname": s.qname, "file": s.file, "line": s.start.line,
                        "depth": depth + 1, "layer": l,
                    });
                    if t == 2 {
                        affected_test_rows.push(row);
                    } else {
                        caller_rows.push(row);
                    }
                    if seen_files.insert(s.file.clone()) {
                        touched_files.push((s.file.clone(), depth + 1));
                    }
                    if depth + 1 < max_depth {
                        queue.push_back((nbr_id, depth + 1));
                    }
                }
            }
        }

        // Aggregate invariants/hazards/effects from seeds.
        let mut all_invariants: Vec<serde_json::Value> = Vec::new();
        let mut all_hazards: Vec<serde_json::Value> = Vec::new();
        let mut all_effects: Vec<serde_json::Value> = Vec::new();
        let mut seen_inv: HashSet<String> = HashSet::new();
        for sym_id in &seed_ids {
            let entries = ledger_store
                .list_entries(&ref_name, sym_id)
                .unwrap_or_default();
            let sym_qname = id_map.get(sym_id).map(|s| s.qname.as_str()).unwrap_or("");
            for entry in entries {
                let key = entry.summary.clone();
                match entry.kind {
                    LedgerKind::Invariant => {
                        if seen_inv.insert(key) {
                            all_invariants.push(serde_json::json!({ "summary": entry.summary, "source": sym_qname }));
                        }
                    }
                    LedgerKind::Hazard => {
                        all_hazards.push(
                            serde_json::json!({ "summary": entry.summary, "source": sym_qname }),
                        );
                    }
                    _ => {}
                }
            }
            if let Ok(Some(decl)) = effect_store.get_effects(&ref_name, sym_id) {
                let qn = id_map
                    .get(sym_id)
                    .map(|s| s.qname.clone())
                    .unwrap_or_default();
                for eff in &decl.declared {
                    all_effects.push(serde_json::json!({ "category": format!("{:?}", eff.effect), "source": qn }));
                }
            }
        }

        let git_depth = p.git_depth.max(1) as usize;
        let recently_touched =
            mcp_git_recent_touches(&touched_files[..touched_files.len().min(5)], git_depth);

        serde_json::to_string(&serde_json::json!({
            "sha": p.sha,
            "changed_files": changed_files,
            "touched_symbols": by_layer,
            "caller_count": caller_rows.len(),
            "test_count": affected_test_rows.len(),
            "callers": caller_rows,
            "affected_tests": affected_test_rows,
            "invariants": all_invariants,
            "hazards": all_hazards,
            "effects": all_effects,
            "recently_touched": recently_touched,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Record an invariant that must hold at a symbol. Shortcut for `ledger_append` with kind=invariant. Invariants appear in investigate, checklist, and prepare_change outputs — record them here so future agents see them."
    )]
    async fn invariant_add(&self, params: Parameters<InvariantAddParams>) -> String {
        let p = params.0;
        let Ok(engine) = Engine::open_sqlite(&self.db_path()) else {
            return err_json("failed to open database");
        };
        let index_store = AsgIndexStore::from_engine(&engine);
        let Ok(Some(symbol)) = index_store.get_symbol_by_qname(&engine.ref_name, &p.qname) else {
            return err_json(&format!("symbol not found: {}", p.qname));
        };
        let author = Author {
            kind: AuthorKind::Agent,
            id: p.author_id.clone(),
        };
        let entry = LedgerEntry::new(
            &symbol.symbol_id,
            LedgerKind::Invariant,
            p.summary.clone(),
            author,
        );
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        match ledger_store.append_entry(&engine.ref_name, &entry, "asd-mcp") {
            Ok(_) => serde_json::to_string(&serde_json::json!({
                "status": "added",
                "entry_id": entry.entry_id,
                "symbol_id": entry.symbol_id,
                "qname": p.qname,
                "summary": p.summary,
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "List invariants recorded against symbols. Pass qname to filter to one symbol; omit to list all invariants in the index."
    )]
    async fn invariant_list(&self, params: Parameters<InvariantListParams>) -> String {
        let p = params.0;
        let Ok(engine) = Engine::open_sqlite(&self.db_path()) else {
            return err_json("failed to open database");
        };
        let ledger_store = AsgLedgerStore::from_engine(&engine);

        let rows: Vec<serde_json::Value> = if let Some(qname) = p.qname {
            let index_store = AsgIndexStore::from_engine(&engine);
            match index_store.get_symbol_by_qname(&engine.ref_name, &qname) {
                Ok(Some(symbol)) => ledger_store
                    .list_entries(&engine.ref_name, &symbol.symbol_id)
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|e| e.kind == LedgerKind::Invariant)
                    .map(|e| {
                        serde_json::json!({
                            "entry_id": e.entry_id,
                            "qname": qname,
                            "summary": e.summary,
                            "created_at": e.created_at,
                            "tags": e.tags,
                        })
                    })
                    .collect(),
                _ => return err_json(&format!("symbol not found: {}", qname)),
            }
        } else {
            let ref_name = &engine.ref_name;
            let tree = match engine.repo.get_tree(ref_name, "/asd/v1/ledger") {
                Ok(v) => v,
                _ => {
                    return serde_json::to_string(&serde_json::json!({ "invariants": [] }))
                        .unwrap_or_else(|_| "{}".to_string());
                }
            };
            // One bulk id-map read (same Plan T scale fix as
            // prepare_change/investigate).
            let index_store_all = AsgIndexStore::from_engine(&engine);
            let id_map = index_store_all.build_id_map(&engine);
            let mut rows: Vec<serde_json::Value> = Vec::new();
            if let Some(sym_map) = tree.as_object() {
                for per_symbol in sym_map.values() {
                    if let Some(entry_map) = per_symbol.as_object() {
                        for entry_val in entry_map.values() {
                            if let Ok(e) = serde_json::from_value::<LedgerEntry>(entry_val.clone())
                            {
                                if e.kind == LedgerKind::Invariant {
                                    let qname = id_map
                                        .get(&e.symbol_id)
                                        .map(|s| s.qname.as_str())
                                        .unwrap_or("");
                                    rows.push(serde_json::json!({
                                        "entry_id": e.entry_id,
                                        "qname": qname,
                                        "summary": e.summary,
                                        "created_at": e.created_at,
                                        "tags": e.tags,
                                    }));
                                }
                            }
                        }
                    }
                }
            }
            rows.sort_by(|a, b| {
                a.get("qname")
                    .and_then(serde_json::Value::as_str)
                    .cmp(&b.get("qname").and_then(serde_json::Value::as_str))
            });
            rows
        };

        serde_json::to_string(&serde_json::json!({ "invariants": rows }))
            .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Record a verdict on a search result. Verdicts: useful (good match), noisy (irrelevant), missing (should have appeared), wrong_layer (architectural misclassification), already_covered (this symbol's behavior is covered by another — Plan C t-005, also surface a Mapping ledger entry), diagnostic_only (this symbol is a diagnostic/instrumentation test — Plan C t-005, also surface a Classification entry with role=diagnostic-test). Persisted and applied as score adjustments in future searches."
    )]
    async fn feedback_mark(&self, params: Parameters<FeedbackMarkParams>) -> String {
        let p = params.0;
        // Plan C t-005: delegate to FeedbackVerdict::from_str so the
        // taxonomy stays single-sourced in core.
        let verdict = match FeedbackVerdict::from_str(&p.verdict) {
            Some(v) => v,
            None => {
                return err_json(&format!(
                    "unknown verdict {:?}; valid: useful, noisy, missing, wrong_layer, already_covered, diagnostic_only",
                    p.verdict
                ));
            }
        };
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index_store = AsgIndexStore::from_engine(&engine);
        let symbol = match index_store.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let entry_id = format!("fb_{}", uuid::Uuid::new_v4().simple());
        let now = chrono::Utc::now();
        let expires_at = p.ttl_days.map(|days| now + chrono::Duration::days(days));
        let entry = FeedbackEntry {
            entry_id: entry_id.clone(),
            symbol_id: symbol.symbol_id.clone(),
            symbol_qname: p.qname.clone(),
            query: p.query.to_lowercase().trim().to_string(),
            verdict,
            note: p.note.clone(),
            author: p.author_id.clone(),
            created_at: now,
            file_scope: None,
            expires_at,
            // A freshly recorded verdict is never withdrawn.
            withdrawn_at: None,
            withdrawn_by: None,
            withdrawn_reason: None,
        };
        let feedback_store = AsgFeedbackStore::from_engine(&engine);
        if let Err(e) = feedback_store.record(&ref_name, &entry, &p.author_id) {
            return err_json(&e.to_string());
        }

        // Plan E t-009: auto-write paired ledger entries so the
        // verdict's intent is durable, not just a per-query verdict.
        let mut paired_kind: Option<&'static str> = None;
        let author_struct = Author {
            kind: AuthorKind::Agent,
            id: p.author_id.clone(),
        };
        let ledger_store = AsgLedgerStore::from_engine(&engine);

        if matches!(verdict, FeedbackVerdict::AlreadyCovered) {
            let cover = match p.covered_by.as_deref() {
                Some(c) if !c.is_empty() => c,
                _ => return err_json("covered_by is required when verdict=already_covered"),
            };
            let body = serde_json::json!({
                "from_qname": &p.qname,
                "to_qname": cover,
                "source": "feedback-pair",
            })
            .to_string();
            let mut led = LedgerEntry::new(
                &symbol.symbol_id,
                LedgerKind::Mapping,
                format!("covered by {cover}"),
                author_struct.clone(),
            );
            led.body = Some(body);
            led.tags.push("plan-e:t-009".into());
            if let Err(e) = ledger_store.append_entry(&ref_name, &led, &p.author_id) {
                return err_json(&e.to_string());
            }
            paired_kind = Some("mapping");
        } else if matches!(verdict, FeedbackVerdict::DiagnosticOnly) {
            let mut led = LedgerEntry::new(
                &symbol.symbol_id,
                LedgerKind::Ownership,
                format!("diagnostic-only: {}", p.query),
                author_struct.clone(),
            );
            led.role = Some("diagnostic-test".to_string());
            led.tags.push("plan-e:t-009".into());
            if let Err(e) = ledger_store.append_entry(&ref_name, &led, &p.author_id) {
                return err_json(&e.to_string());
            }
            paired_kind = Some("classification");
        }

        serde_json::to_string(&serde_json::json!({
            "ok": true,
            "entry_id": entry_id,
            "verdict": p.verdict,
            "qname": p.qname,
            "paired_ledger": paired_kind,
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    #[tool(
        description = "Designate a symbol as the canonical source-of-truth for a domain concept. Writes an Ownership ledger entry (3x ranking boost) so future searches for that concept reliably surface this symbol. Use when you know which function/struct truly owns a concept."
    )]
    async fn feedback_promote(&self, params: Parameters<FeedbackPromoteParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index_store = AsgIndexStore::from_engine(&engine);
        let symbol = match index_store.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };
        let author_kind = if p.author_id.contains("human") {
            AuthorKind::Human
        } else {
            AuthorKind::Agent
        };
        let mut entry = LedgerEntry::new(
            &symbol.symbol_id,
            LedgerKind::Ownership,
            &p.concept,
            Author {
                kind: author_kind,
                id: p.author_id.clone(),
            },
        );
        entry.tags = vec!["promote-as-truth".to_string()];
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        match ledger_store.append_entry(&ref_name, &entry, &p.author_id) {
            Ok(()) => serde_json::to_string(&serde_json::json!({
                "ok": true,
                "entry_id": entry.entry_id,
                "qname": p.qname,
                "concept": p.concept,
                "kind": "ownership",
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "Retract a recorded verdict so it stops influencing search ranking. Use when a verdict was WRONG. For one that was right but is no longer relevant, use its ttl/expiry instead. The entry stays listed, marked withdrawn."
    )]
    async fn feedback_withdraw(&self, params: Parameters<FeedbackWithdrawParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let store = AsgFeedbackStore::from_engine(&engine);
        let by = p.by.as_deref().unwrap_or("asd-mcp");
        match store.withdraw(&ref_name, &p.entry_id, by, p.reason.as_deref()) {
            Ok(Some(e)) => serde_json::to_string(&serde_json::json!({
                "withdrawn": true,
                "entry_id": e.entry_id,
                "symbol_qname": e.symbol_qname,
                "query": e.query,
                "verdict": format!("{:?}", e.verdict),
                "withdrawn_at": e.withdrawn_at,
                "withdrawn_by": e.withdrawn_by,
                "withdrawn_reason": e.withdrawn_reason,
                "note": "no longer influences ranking; still listed so it explains past rankings",
            }))
            .unwrap_or_else(|_| "{}".to_string()),
            Ok(None) => err_json(&format!("no feedback entry {}", p.entry_id)),
            Err(e) => err_json(&e.to_string()),
        }
    }

    #[tool(
        description = "List recorded feedback verdicts. Pass qname to filter to one symbol; omit to list all. Use this to audit search quality signals or review past verdicts."
    )]
    async fn feedback_list(&self, params: Parameters<FeedbackListParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let feedback_store = AsgFeedbackStore::from_engine(&engine);
        let entries: Vec<serde_json::Value> = if let Some(ref qname) = p.qname {
            let index_store = AsgIndexStore::from_engine(&engine);
            match index_store.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(sym)) => feedback_store
                    .list_for_symbol(&ref_name, &sym.symbol_id)
                    .unwrap_or_default()
                    .into_iter()
                    .map(|e| serde_json::to_value(&e).unwrap_or_default())
                    .collect(),
                Ok(None) => return err_json(&format!("symbol not found: {}", qname)),
                Err(e) => return err_json(&e.to_string()),
            }
        } else {
            feedback_store
                .list_all(&ref_name)
                .unwrap_or_default()
                .into_iter()
                .map(|e| serde_json::to_value(&e).unwrap_or_default())
                .collect()
        };
        serde_json::to_string(&serde_json::json!({ "feedback": entries }))
            .unwrap_or_else(|_| "{}".to_string())
    }

    // -----------------------------------------------------------------------
    // Tool 1: search — Full agent-quality ranked search
    // -----------------------------------------------------------------------

    #[tool(
        description = "Full ranked symbol search with confidence, uncertainty model, feedback adjustments, and agent-quality output. Prefer this over code_search for agent workflows."
    )]
    async fn search(&self, params: Parameters<SearchParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let layer_overrides = load_layer_overrides(&db_path);
        let intent = p.intent.as_deref().and_then(parse_intent).unwrap_or("");
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let dq_state_str: String = {
            let trust = compute_trust_score(&db_path);
            trust.data_quality.state.clone()
        };

        let all_feedback: Vec<agentstatedeveloper_core::FeedbackEntry> = {
            let fb_store = AsgFeedbackStore::from_engine(&engine);
            // Plan J t-014: expired entries don't influence ranking;
            // storage is preserved so users can audit via feedback_list.
            fb_store
                .list_all(&ref_name)
                .unwrap_or_default()
                .into_iter()
                .filter(|e| !e.is_expired())
                .collect()
        };

        let (tokens, mut inline_exclusions) = parse_query(&p.query);
        if let Some(ref excl) = p.exclude {
            for term in excl
                .split(',')
                .map(|t| t.trim().to_lowercase())
                .filter(|t| !t.is_empty())
            {
                inline_exclusions.push(term);
            }
        }

        if tokens.is_empty() {
            return serde_json::json!({"query": p.query, "results": [], "document_hits": []})
                .to_string();
        }

        let limit = p.limit.max(1) as usize;
        let mut paths_filter: Vec<String> = Vec::new();
        if let Some(ref scope) = p.scope {
            paths_filter.extend(resolve_scope(scope, &db_path));
        }
        if let Some(ref paths_str) = p.paths {
            paths_filter.extend(
                paths_str
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty()),
            );
        }
        let filters = FtsFilters {
            kind: p.kind.as_deref().map(|k| k.to_lowercase()),
            language: p.language.as_deref().map(|l| l.to_lowercase()),
            include_tests: p.include_tests,
            tests_only: false,
            exclude_terms: inline_exclusions.clone(),
            paths_filter: paths_filter.clone(),
            exclude_paths: vec![],
            exclude_languages: vec![],
        };

        let doc_hits: Vec<serde_json::Value> = if !p.symbols_only {
            SearchDocsDb::open(&db_path)
                .ok()
                .filter(|db| !db.is_empty())
                .and_then(|db| db.search(&tokens, limit, None).ok())
                .unwrap_or_default()
                .into_iter()
                .map(|h| {
                    serde_json::json!({
                        "source": "document",
                        "score": h.bm25_score,
                        "kind": h.kind,
                        "path": h.path,
                        "line": h.span_start,
                        "title": h.title,
                        "preview": h.preview,
                        "owner_symbol_id": h.owner_symbol_id,
                    })
                })
                .collect()
        } else {
            vec![]
        };

        let fts_result = engine
            .fts
            .as_ref()
            .filter(|fts| fts.has_data())
            .and_then(|fts| fts.search(&p.query, &filters, limit * 2).ok());

        if let Some(hits) = fts_result {
            let ledger_store = AsgLedgerStore::from_engine(&engine);
            let effect_store = AsgEffectStore::from_engine(&engine);
            let index_store = AsgIndexStore::from_engine(&engine);

            let mut has_ledger_ids: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            const GENERIC_BOOST_SKIP: &[&str] = &[
                "state",
                "update",
                "position",
                "value",
                "cursor",
                "progress",
                "indicator",
                "status",
                "mode",
                "flag",
                "current",
                "local",
                "playhead",
                "tick",
                "item",
                "data",
                "info",
                "manager",
            ];
            let mut scored: Vec<(f64, _)> = {
                let mut tmp = Vec::with_capacity(hits.len());
                for hit in hits {
                    let hybrid = hybrid_boost(&hit, &tokens);
                    let ledger_boost = if hit.ledger_text.is_empty() {
                        0.0
                    } else {
                        tokens
                            .iter()
                            .filter(|t| hit.ledger_text.contains(t.as_str()))
                            .count() as f64
                    };
                    let haystack =
                        format!("{} {}", hit.qname.to_lowercase(), hit.file.to_lowercase());
                    let domain_overlap = tokens
                        .iter()
                        .filter(|t| !GENERIC_BOOST_SKIP.contains(&t.as_str()))
                        .filter(|t| haystack.contains(t.as_str()))
                        .count();
                    let has_ownership = hit.has_ownership();
                    let has_invariant = hit.has_invariant();
                    if hit.has_ledger() {
                        has_ledger_ids.insert(hit.symbol_id.clone());
                    }
                    let is_state_holder =
                        matches!(hit.kind.as_str(), "class" | "struct" | "type" | "enum")
                            && !has_ownership
                            && !has_invariant
                            && !tokens.iter().any(|t| {
                                matches!(
                                    t.as_str(),
                                    "state"
                                        | "model"
                                        | "type"
                                        | "class"
                                        | "struct"
                                        | "enum"
                                        | "schema"
                                )
                            });
                    let state_penalty = if is_state_holder { -0.8 } else { 0.0 };
                    let sot_boost = if has_ownership && domain_overlap >= 2 {
                        5.0
                    } else if has_ownership && domain_overlap >= 1 {
                        3.5
                    } else if has_ownership {
                        2.0
                    } else if has_invariant && domain_overlap >= 1 {
                        1.5
                    } else {
                        0.0
                    };
                    let total = hit.bm25_score + hybrid + ledger_boost + sot_boost + state_penalty;
                    tmp.push((total, hit));
                }
                tmp
            };

            // Apply feedback adjustments
            let mut feedback_metrics = agentstatedeveloper_core::FeedbackMetrics::default();
            {
                if !all_feedback.is_empty() {
                    // Plan J t-016: tuple gained created_at for age-decay.
                    let fb_tuples: Vec<_> = all_feedback
                        .iter()
                        .filter(|e| e.file_scope.is_none())
                        .map(|e| {
                            (
                                e.symbol_id.clone(),
                                e.query.clone(),
                                e.verdict,
                                e.created_at,
                            )
                        })
                        .collect();
                    let fs_tuples: Vec<_> = all_feedback
                        .iter()
                        .filter_map(|e| {
                            e.file_scope
                                .as_ref()
                                .map(|g| (g.clone(), e.verdict, e.query.clone(), e.created_at))
                        })
                        .collect();
                    let mut adj: Vec<(f64, String)> =
                        scored.iter().map(|(s, h)| (*s, h.qname.clone())).collect();
                    feedback_metrics = apply_feedback_adjustments(
                        &engine,
                        &index_store,
                        &p.query,
                        &mut adj,
                        &fb_tuples,
                    );
                    apply_file_scope_feedback(
                        &engine,
                        &index_store,
                        &p.query,
                        &mut adj,
                        &fs_tuples,
                    );
                    let adj_map: std::collections::HashMap<String, f64> =
                        adj.into_iter().map(|(s, q)| (q, s)).collect();
                    scored.retain(|(_, h)| adj_map.contains_key(&h.qname));
                    for (score, h) in scored.iter_mut() {
                        if let Some(&new_s) = adj_map.get(&h.qname) {
                            *score = new_s;
                        }
                    }
                }
            }

            scored.sort_by(|a, b| {
                b.0.partial_cmp(&a.0)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then_with(|| a.1.qname.cmp(&b.1.qname))
            });
            scored.truncate(limit);

            let recency = gather_recency(200, 14.0);
            let raw_scores: Vec<f64> = scored.iter().map(|(s, _)| *s).collect();
            let confidences = confidence_scores(&raw_scores);
            let ambiguous_terms = detect_ambiguous_tokens(&tokens, engine.fts.as_ref(), &filters);

            let all_result_qnames: Vec<String> =
                scored.iter().map(|(_, h)| h.qname.clone()).collect();
            let all_feedback_impacts = explain_feedback_impacts(
                &engine,
                &index_store,
                &p.query,
                &all_result_qnames,
                &all_feedback,
            );

            let mut layers_present: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            let mut ledger_cache: std::collections::HashMap<String, Vec<LedgerEntry>> =
                std::collections::HashMap::new();
            let results: Vec<serde_json::Value> = scored.iter().zip(confidences.iter()).map(|((score, hit), conf)| {
                let rec = recency.get(&hit.file);
                let is_hot = rec.map(|r| r.hot).unwrap_or(false);
                let tier = symbol_tier(&hit.file);
                let layer = classify_layer_sym(&hit.file, &hit.qname, tier, &layer_overrides);
                layers_present.insert(layer.to_string());
                if !ledger_cache.contains_key(&hit.symbol_id) {
                    if let Ok(entries) = ledger_store.list_entries(&ref_name, &hit.symbol_id) {
                        ledger_cache.insert(hit.symbol_id.clone(), entries);
                    }
                }
                let ledger_entries = ledger_cache.get(&hit.symbol_id).cloned().unwrap_or_default();
                let has_ledger = has_ledger_ids.contains(&hit.symbol_id) || !ledger_entries.is_empty();
                let match_reasons = if let Ok(Some(sym)) = index_store.get_symbol_by_qname(&ref_name, &hit.qname) {
                    explain_match(&sym, &tokens, &ledger_entries, is_hot)
                } else { vec![] };
                let bucket = result_bucket(&hit.file, &match_reasons, has_ledger, is_hot);
                let conf_reason = confidence_reason(&match_reasons, has_ledger, is_hot);
                let fb_status = {
                    let q = p.query.to_lowercase();
                    all_feedback.iter().find(|e| {
                        e.symbol_id == hit.symbol_id
                            && (e.query.is_empty() || q.contains(e.query.as_str()) || e.query.contains(q.as_str()))
                    }).map(|e| e.verdict.as_str().to_string())
                };
                let feedback_rule: Option<serde_json::Value> = all_feedback_impacts.get(&hit.qname).map(|imp| {
                    serde_json::json!({"verdict": imp.verdict, "matched_query": imp.matched_query, "author": imp.author})
                });
                let effect_detail = {
                    let decl = effect_store.get_effects(&ref_name, &hit.symbol_id).ok().flatten();
                    effect_detail_reason(decl.as_ref())
                };
                serde_json::json!({
                    "score": score, "confidence": conf, "bucket": bucket,
                    "confidence_reason": conf_reason,
                    "qname": hit.qname, "kind": hit.kind,
                    "file": hit.file, "line": hit.line, "layer": layer,
                    "summary": extract_summary(hit.doc.as_deref(), hit.signature.as_deref()),
                    "last_touched_days": rec.and_then(|r| r.last_touched_days),
                    "hot": is_hot,
                    "match_reasons": match_reasons,
                    "feedback_status": fb_status,
                    "feedback_rule": feedback_rule,
                    "effect_detail": effect_detail,
                })
            }).collect();

            let scope_narrowed =
                !filters.paths_filter.is_empty() || !filters.exclude_terms.is_empty();
            let layers_ref: std::collections::HashSet<&str> =
                layers_present.iter().map(|s| s.as_str()).collect();
            let possible_misses = if scope_narrowed {
                vec![]
            } else {
                detect_possible_misses(&p.query, &layers_ref, results.len())
            };
            let confidence_warnings = detect_confidence_warnings(
                &tokens,
                results.len(),
                &ambiguous_terms,
                engine.fts.as_ref(),
            );
            let query_suggestions = if scope_narrowed {
                vec![]
            } else {
                suggest_better_queries(&tokens, &p.query)
            };
            let top_qnames: Vec<String> = results
                .iter()
                .take(5)
                .filter_map(|r| r["qname"].as_str().map(|s| s.to_string()))
                .collect();
            let scoped_suggestions = if scope_narrowed || ambiguous_terms.is_empty() {
                vec![]
            } else {
                suggest_scoped_queries(&tokens, &ambiguous_terms, &top_qnames)
            };
            let uncertainty = compute_uncertainty(
                &tokens,
                &ambiguous_terms,
                &possible_misses,
                results.len(),
                &scoped_suggestions,
                engine.fts.as_ref(),
                Some(dq_state_str.as_str()),
            );
            let feedback_state = build_feedback_state_from_entries(
                &all_feedback,
                &p.query,
                feedback_metrics.entries_applied,
            );
            let raw = serde_json::json!({
                "query": p.query,
                "intent": if intent.is_empty() { serde_json::Value::Null } else { serde_json::json!(intent) },
                "uncertainty": uncertainty.to_json(),
                "ambiguous_terms": ambiguous_terms,
                "possible_misses": possible_misses,
                "confidence_warnings": confidence_warnings,
                "query_suggestions": query_suggestions,
                "scoped_suggestions": scoped_suggestions,
                "scope_narrowed": scope_narrowed,
                "feedback_state": feedback_state.to_json(),
                "results": results,
                "document_hits": doc_hits,
            });
            let max_list = (p.agent_budget as usize / 500).max(3).min(20);
            let trimmed = trim_for_agent(&raw, max_list);
            let json_str = serde_json::to_string(&trimmed).unwrap_or_default();
            let token_est = estimate_tokens(&json_str);
            let mut out = trimmed.clone();
            if let Some(obj) = out.as_object_mut() {
                obj.insert("token_estimate".into(), serde_json::json!(token_est));
            }
            return serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string());
        }

        // Fallback: in-memory scoring
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let prefix = format!("{}/index/by-qname", ASD_PATH_PREFIX);
        let qnames: Vec<String> = match engine.repo.get_tree(&ref_name, &prefix) {
            Ok(serde_json::Value::Object(map)) => map.keys().cloned().collect(),
            _ => return serde_json::json!({"query": p.query, "results": [], "document_hits": doc_hits}).to_string(),
        };
        let index = AsgIndexStore::from_engine(&engine);
        let mut scored: Vec<(u32, Symbol)> = Vec::new();
        for qname in &qnames {
            let sym = match index.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(s)) => s,
                _ => continue,
            };
            if let Some(ref k) = filters.kind {
                let sk = format!("{:?}", sym.kind).to_lowercase();
                if &sk != k {
                    continue;
                }
            }
            if let Some(ref lang) = filters.language {
                if &sym.language != lang {
                    continue;
                }
            }
            let qn = sym.qname.to_lowercase();
            let sig = sym.signature.as_deref().unwrap_or("").to_lowercase();
            let doc = sym.doc.as_deref().unwrap_or("").to_lowercase();
            let file = sym.file.to_lowercase();
            let ledger_text: String = ledger_store
                .list_entries(&ref_name, &sym.symbol_id)
                .unwrap_or_default()
                .iter()
                .map(|e| e.summary.to_lowercase())
                .collect::<Vec<_>>()
                .join(" ");
            let mut score: u32 = 0;
            for token in &tokens {
                if qn.contains(token.as_str()) {
                    score += 4;
                }
                if !sig.is_empty() && sig.contains(token.as_str()) {
                    score += 3;
                }
                if !doc.is_empty() && doc.contains(token.as_str()) {
                    score += 3;
                }
                if !ledger_text.is_empty() && ledger_text.contains(token.as_str()) {
                    score += 2;
                }
                if file.contains(token.as_str()) {
                    score += 1;
                }
            }
            if score > 0 {
                scored.push((score, sym));
            }
        }
        scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.qname.cmp(&b.1.qname)));
        scored.truncate(limit);
        let recency = gather_recency(200, 14.0);
        let results: Vec<serde_json::Value> = scored
            .iter()
            .map(|(score, sym)| {
                let tier = symbol_tier(&sym.file);
                let layer = classify_layer_sym(&sym.file, &sym.qname, tier, &layer_overrides);
                let rec = recency.get(&sym.file);
                serde_json::json!({
                    "score": score, "qname": sym.qname,
                    "kind": format!("{:?}", sym.kind).to_lowercase(),
                    "file": sym.file, "line": sym.start.line,
                    "tier": tier, "layer": layer,
                    "summary": extract_summary(sym.doc.as_deref(), sym.signature.as_deref()),
                    "last_touched_days": rec.and_then(|r| r.last_touched_days),
                    "hot": rec.map(|r| r.hot).unwrap_or(false),
                })
            })
            .collect();
        // Token economy (1.0.80): MCP is always agent-consumed.
        // Drop input echo (p.query) and any empty top-level fields.
        let raw = serde_json::json!({"results": results, "document_hits": doc_hits});
        let raw = agentstatedeveloper_core::drop_empty_top_level(raw);
        serde_json::to_string(&raw).unwrap_or_else(|_| "{}".to_string())
    }

    // -----------------------------------------------------------------------
    // Tool 2: context_for — Deep per-symbol context
    // -----------------------------------------------------------------------

    #[tool(
        description = "Assemble deep per-symbol context: signature, callers/callees, effects, all ledger entries (invariants, hazards, decisions), covering tests, and ownership discovery. Pass comma-separated qnames."
    )]
    async fn context_for(&self, params: Parameters<ContextForParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index_store = AsgIndexStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        let id_map = index_store.build_id_map(&engine);

        let qnames: Vec<&str> = p
            .qnames
            .split(',')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();
        let budget_chars = p.budget_tokens.map(|t| t as usize * 4);
        let include_body = p.include_body;

        // Plan M t-001 (1.0.91): per-symbol context assembly is now
        // a single core helper shared with the CLI `asd context-for`
        // command. ~150 lines of inline duplication removed.
        let mut symbols_out = Vec::new();
        for qname in &qnames {
            let symbol = match index_store.get_symbol_by_qname(&ref_name, qname) {
                Ok(Some(s)) => s,
                Ok(None) => {
                    symbols_out
                        .push(serde_json::json!({ "qname": qname, "error": "symbol not found" }));
                    continue;
                }
                Err(e) => {
                    symbols_out.push(serde_json::json!({ "qname": qname, "error": e.to_string() }));
                    continue;
                }
            };
            match agentstatedeveloper_core::assemble_symbol_context(
                &engine,
                &index_store,
                &effect_store,
                &ledger_store,
                &symbol,
                &id_map,
                include_body,
                engine.fts.as_ref(),
                None,
            ) {
                Ok(ctx) => symbols_out.push(ctx),
                Err(e) => {
                    symbols_out.push(serde_json::json!({ "qname": qname, "error": e.to_string() }))
                }
            }
        }

        // Plan G t-006: surface captured thinking across the requested qnames.
        // p.qnames is a comma-separated String per the existing API.
        let qnames_vec: Vec<String> = p
            .qnames
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        // AcmeFlow refinement: thinking_summary always emits, even
        // when prior_thinking is Null — load-bearing signal for agents
        // ("entries exist but filtered" vs "no entries on these symbols").
        let pt = thinking::gather_prior_thinking(
            &engine,
            &qnames_vec,
            thinking::DEFAULT_CONFIDENCE_FLOOR,
        );

        // Plan F t-006: brief projects each per-symbol context down to the
        // compact shape (symbol{qname,file,signature,doc} + capped callers/
        // callees + effects categories + ledger_count). The outer envelope
        // stays the same.
        let symbols_projected: Vec<serde_json::Value> = if brief::brief_from_env() {
            symbols_out.iter().map(brief::brief_context_for).collect()
        } else {
            symbols_out
        };

        // Token economy (1.0.80): drop input echo `query`. The MCP
        // client just sent `p.qnames`; echoing it costs ~50-200
        // chars depending on the qname list size.
        let mut out_map = serde_json::Map::new();
        out_map.insert("count".into(), serde_json::json!(symbols_projected.len()));
        out_map.insert("symbols".into(), serde_json::json!(symbols_projected));
        if !pt.entries.is_null() {
            out_map.insert("prior_thinking".into(), pt.entries);
        }
        out_map.insert(
            "thinking_summary".into(),
            serde_json::to_value(&pt.summary).unwrap_or(serde_json::Value::Null),
        );
        let out =
            agentstatedeveloper_core::drop_empty_top_level(serde_json::Value::Object(out_map));

        let mut output = serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string());
        if let Some(max_chars) = budget_chars {
            if output.len() > max_chars {
                let mut v = out.clone();
                if let Some(obj) = v.as_object_mut() {
                    obj.insert(
                        "_budget_warning".into(),
                        serde_json::json!(
                            "output exceeds budget; pass fewer qnames or increase budget_tokens"
                        ),
                    );
                }
                output = serde_json::to_string(&v).unwrap_or_else(|_| "{}".to_string());
            }
        }
        output
    }

    // -----------------------------------------------------------------------
    // Tool 3: task_close — Workflow task closure
    // -----------------------------------------------------------------------

    #[tool(
        description = "Close a task: write Proof (and optional ValidationScenario) ledger entries for affected symbols. Resolves symbols from git HEAD changed files when symbols is omitted."
    )]
    async fn task_close(&self, params: Parameters<TaskCloseParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index_store = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);

        let plan_id = p.plan.clone().unwrap_or_default();
        let task_id = p.task.clone().unwrap_or_default();

        let mut ctx_tags: Vec<String> = Vec::new();
        if !plan_id.is_empty() {
            ctx_tags.push(format!("ctx:plan:{}", plan_id));
        }
        if !task_id.is_empty() {
            ctx_tags.push(format!("ctx:task:{}", task_id));
        }

        // Resolve symbols
        let target_symbols: Vec<Symbol> = if let Some(ref sym_list) = p.symbols {
            sym_list
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .filter_map(|q| index_store.get_symbol_by_qname(&ref_name, q).ok().flatten())
                .collect()
        } else {
            let out = Proc::new("git")
                .args(["diff-tree", "--no-commit-id", "-r", "--name-only", "HEAD"])
                .output()
                .unwrap_or_else(|_| std::process::Output {
                    status: std::process::ExitStatus::default(),
                    stdout: vec![],
                    stderr: vec![],
                });
            let changed: Vec<String> = String::from_utf8_lossy(&out.stdout)
                .lines()
                .map(|l| l.trim().to_string())
                .filter(|l| !l.is_empty())
                .collect();
            let tree = engine
                .repo
                .get_tree(&ref_name, "/asd/v1/index/by-qname")
                .unwrap_or(serde_json::Value::Object(Default::default()));
            let mut syms: Vec<Symbol> = tree
                .as_object()
                .map(|m| {
                    m.values()
                        .filter_map(|v| serde_json::from_value::<Symbol>(v.clone()).ok())
                        .filter(|s| {
                            changed
                                .iter()
                                .any(|f| s.file.ends_with(f.as_str()) || s.file == *f)
                        })
                        .collect()
                })
                .unwrap_or_default();
            syms.truncate(20);
            syms
        };

        if target_symbols.is_empty() {
            return serde_json::to_string(&serde_json::json!({
                "written": [],
                "note": "no symbols resolved — pass symbols or ensure HEAD has changed files",
                "ctx": {"plan": plan_id, "task": task_id},
            }))
            .unwrap_or_else(|_| "{}".to_string());
        }

        let proof_base = p
            .proof
            .clone()
            .unwrap_or_else(|| "task completed".to_string());
        let proof_text = if let Some(ref ev) = p.evidence {
            format!("{} [evidence: {}]", proof_base, ev)
        } else {
            proof_base.clone()
        };

        let author = Author {
            kind: AuthorKind::Human,
            id: p.author.clone(),
        };
        let mut written: Vec<serde_json::Value> = Vec::new();
        let closed_at = chrono::Utc::now().to_rfc3339();

        for sym in &target_symbols {
            let mut proof_entry = LedgerEntry::new(
                &sym.symbol_id,
                LedgerKind::Proof,
                &proof_text,
                author.clone(),
            );
            proof_entry.tags.extend(ctx_tags.iter().cloned());
            if let Some(ref ev) = p.evidence {
                proof_entry.tags.push(format!("evidence:{}", ev));
            }
            match ledger_store.append_entry(&ref_name, &proof_entry, &p.author) {
                Ok(_) => written.push(serde_json::json!({"symbol": sym.qname, "kind": "proof", "summary": proof_text})),
                Err(e) => return err_json(&format!("ledger write failed for {}: {}", sym.qname, e)),
            }

            if p.validated {
                let validation_text = p
                    .validation_note
                    .clone()
                    .unwrap_or_else(|| format!("validated: {}", proof_base));
                let mut vs_entry = LedgerEntry::new(
                    &sym.symbol_id,
                    LedgerKind::ValidationScenario,
                    &validation_text,
                    author.clone(),
                );
                vs_entry.tags.extend(ctx_tags.iter().cloned());
                if let Ok(_) = ledger_store.append_entry(&ref_name, &vs_entry, &p.author) {
                    written.push(serde_json::json!({"symbol": sym.qname, "kind": "validation_scenario", "summary": validation_text}));
                }
            }
        }

        // Workflow integration
        let pre_existing: Vec<LedgerEntry> = target_symbols
            .iter()
            .flat_map(|sym| {
                ledger_store
                    .list_entries(&ref_name, &sym.symbol_id)
                    .unwrap_or_default()
            })
            .filter(|e| {
                !written
                    .iter()
                    .any(|w| w.get("summary").and_then(|s| s.as_str()) == Some(e.summary.as_str()))
            })
            .collect();

        let proof_was_explicit = p.proof.is_some();
        let eq = score_evidence_quality(
            &pre_existing,
            p.validated,
            p.evidence.as_deref(),
            proof_was_explicit,
            target_symbols.len(),
            written.len(),
        );
        let has_invariants = pre_existing.iter().any(|e| e.kind == LedgerKind::Invariant);
        let (wf_type, steps_detected, missing_steps) =
            detect_workflow(&pre_existing, &eq, has_invariants);
        let trust = compute_trust_score(&db_path);
        let db_state = trust.data_quality.state.clone();
        let db_state_note = match db_state.as_str() {
            "clean_room" => "fresh workspace — low evidence score is expected".to_string(),
            "unannotated" => "no prior annotations — low evidence score expected".to_string(),
            "degraded" => "warning: sparse ledger despite prior activity".to_string(),
            _ => String::new(),
        };

        let workflow_summary = WorkflowSummary {
            workflow_type: wf_type,
            steps_detected,
            missing_recommended_steps: missing_steps,
            evidence_quality: eq,
            task_id: task_id.clone(),
            plan_id: plan_id.clone(),
            closed_at: closed_at.clone(),
            symbols_annotated: target_symbols.len(),
            ledger_entries_written: written.len(),
            db_state,
            db_state_note,
        };
        append_workflow_session(&db_path, &workflow_summary);

        let out = serde_json::json!({
            "status": "closed",
            "closed_at": closed_at,
            "proof": proof_text,
            "validated": p.validated,
            "symbols_annotated": target_symbols.len(),
            "ledger_entries_written": written.len(),
            "ctx": {
                "plan": if plan_id.is_empty() { serde_json::Value::Null } else { serde_json::json!(plan_id) },
                "task": if task_id.is_empty() { serde_json::Value::Null } else { serde_json::json!(task_id) },
            },
            "workflow": workflow_summary.to_json(),
            "written": written,
        });
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    // -----------------------------------------------------------------------
    // Tool 4: verify_effects — Static effect verification
    // -----------------------------------------------------------------------

    #[tool(
        description = "Compare declared effects against what the static checker infers from source. Returns ok/mismatch/unverified and the list of mismatches."
    )]
    async fn verify_effects(&self, params: Parameters<VerifyEffectsParams>) -> String {
        let p = params.0;
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index_store = AsgIndexStore::from_engine(&engine);
        let effect_store = AsgEffectStore::from_engine(&engine);
        let adapters = default_adapters();

        let symbol = match index_store.get_symbol_by_qname(&ref_name, &p.qname) {
            Ok(Some(s)) => s,
            Ok(None) => return err_json(&format!("symbol not found: {}", p.qname)),
            Err(e) => return err_json(&e.to_string()),
        };

        let mut effect_decl = effect_store
            .get_effects(&ref_name, &symbol.symbol_id)
            .unwrap_or(None)
            .unwrap_or_else(|| EffectDecl {
                symbol_id: symbol.symbol_id.clone(),
                declared: Vec::new(),
                transitive: Vec::new(),
                verification: None,
                confidence: None,
                runtime: None,
                matched_policy: None,
            });

        let adapter = adapters
            .iter()
            .find(|a| a.language() == symbol.language.as_str());

        let (status, mismatches, inferred_strs) = if let Some(adapter) = adapter {
            match std::fs::read_to_string(&symbol.file) {
                Ok(source) => {
                    let stub = ParsedSymbol {
                        qname: symbol.qname.clone(),
                        kind: symbol.kind,
                        start_line: symbol.start.line,
                        start_col: symbol.start.col,
                        end_line: symbol.end.line,
                        end_col: symbol.end.col,
                        body: String::new(),
                        signature: symbol.signature.clone(),
                        doc: symbol.doc.clone(),
                    };
                    let inferred: Vec<EffectCategory> = adapter
                        .infer_effects(&source, &stub)
                        .into_iter()
                        .map(|e| e.effect)
                        .collect();
                    let declared_cats: Vec<EffectCategory> = effect_decl
                        .declared
                        .iter()
                        .map(|e| e.effect.clone())
                        .collect();
                    let mut mismatches: Vec<Mismatch> = Vec::new();
                    for cat in &declared_cats {
                        if !inferred.contains(cat) {
                            mismatches.push(Mismatch {
                                kind: "declared_not_inferred".to_string(),
                                effect: cat.clone(),
                                detected_in: Some(symbol.file.clone()),
                                note: Some("declared but not found by static checker".to_string()),
                            });
                        }
                    }
                    for cat in &inferred {
                        if !declared_cats.contains(cat) {
                            mismatches.push(Mismatch {
                                kind: "inferred_not_declared".to_string(),
                                effect: cat.clone(),
                                detected_in: Some(symbol.file.clone()),
                                note: Some(
                                    "found by static checker but not in declared effects"
                                        .to_string(),
                                ),
                            });
                        }
                    }
                    let status = if mismatches.is_empty() {
                        VerificationStatus::Ok
                    } else {
                        VerificationStatus::Mismatch
                    };
                    let inferred_strs: Vec<String> =
                        inferred.iter().map(|e| e.as_str().to_string()).collect();
                    (status, mismatches, inferred_strs)
                }
                Err(_) => (VerificationStatus::Unverified, Vec::new(), Vec::new()),
            }
        } else {
            (VerificationStatus::Unverified, Vec::new(), Vec::new())
        };

        if p.write {
            let verification = Verification {
                by: VerificationSource::StaticChecker,
                at: chrono::Utc::now(),
                status,
                mismatches: mismatches.clone(),
            };
            effect_decl.verification = Some(verification);
            if let Err(e) = effect_store.put_effects(
                &ref_name,
                &effect_decl.symbol_id,
                &effect_decl,
                "asd-mcp-verify",
            ) {
                return err_json(&format!("failed to write verification: {}", e));
            }
        }

        let out = serde_json::json!({
            "qname": symbol.qname,
            "symbol_id": symbol.symbol_id,
            "status": match status {
                VerificationStatus::Ok => "ok",
                VerificationStatus::Mismatch => "mismatch",
                VerificationStatus::Unverified => "unverified",
            },
            "declared": effect_decl.declared.iter().map(|e| e.effect.as_str()).collect::<Vec<_>>(),
            "inferred": inferred_strs,
            "mismatches": mismatches.iter().map(|m| serde_json::json!({
                "kind": m.kind, "effect": m.effect.as_str(), "note": m.note,
            })).collect::<Vec<_>>(),
            "written": p.write,
        });
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    // -----------------------------------------------------------------------
    // Tool 5: status — Workspace health
    // -----------------------------------------------------------------------

    #[tool(
        description = "Workspace index health: symbol count, index age, sidecar state, dirty source files, concept gaps, and the State Trust Score. CALL THIS WHEN deciding whether the index is fresh enough to trust, or to see which files changed since the last commit (`show_dirty=true`). Lighter alternatives: `health` for bare server liveness, `trust` for just the rollup score + blocking flag. (CLI: `asd status`.)"
    )]
    async fn status(&self, params: Parameters<StatusParams>) -> String {
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();

        let fts = match SearchFtsDb::open(&db_path) {
            Ok(f) => f,
            Err(e) => return err_json(&format!("cannot open FTS db: {}", e)),
        };

        let project_root = db_path.parent().unwrap_or(std::path::Path::new("."));
        let sidecar_state = sidecar_lifecycle_state(project_root);
        let sidecar_key = match sidecar_state {
            SidecarState::Missing => "missing",
            SidecarState::Present => "present",
            SidecarState::Hydrated => "hydrated",
            SidecarState::FreshReset => "fresh-reset",
        };
        let sidecar_action = match sidecar_state {
            SidecarState::Missing => "run 'asd sync' to create sidecar",
            SidecarState::Present => "run 'asd hydrate' to load sidecar into ASG",
            SidecarState::Hydrated => "sidecar is current",
            SidecarState::FreshReset => "re-run 'asd index' then 'asd sync'",
        };

        if !fts.has_data() {
            return serde_json::to_string(&serde_json::json!({
                "state": "empty",
                "note": "run 'asd index <dir>' to build",
                "sidecar": sidecar_key,
            }))
            .unwrap_or_else(|_| "{}".to_string());
        }

        let count = fts.symbol_count();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        let (indexed_at, age_hours, index_state) = match fts.last_indexed_at() {
            Some(ts) => {
                let age_h = (now - ts).max(0) / 3600;
                let state = if age_h == 0 {
                    "fresh"
                } else if age_h >= 1 {
                    "stale"
                } else {
                    "ok"
                };
                (Some(ts), Some(age_h), state)
            }
            None => (None, None, "unknown"),
        };

        let dirty_files: Vec<String> = if p.show_dirty {
            match Proc::new("git")
                .args(["status", "--short", "--untracked-files=no"])
                .current_dir(project_root)
                .output()
            {
                Ok(o) if o.status.success() => {
                    let source_exts = [
                        ".swift", ".py", ".ts", ".tsx", ".js", ".rs", ".go", ".kt", ".java", ".rb",
                        ".cs",
                    ];
                    String::from_utf8_lossy(&o.stdout)
                        .lines()
                        .filter(|l| source_exts.iter().any(|ext| l.ends_with(ext)))
                        .map(|l| l.trim().to_string())
                        .collect()
                }
                _ => vec![],
            }
        } else {
            vec![]
        };

        // Concept gaps
        let concept_gaps: Vec<serde_json::Value> = {
            let ledger_store = AsgLedgerStore::from_engine(&engine);
            let tree = engine
                .repo
                .get_tree(&ref_name, "/asd/v1/index/by-qname")
                .unwrap_or(serde_json::Value::Object(Default::default()));
            tree.as_object()
                .map(|m| {
                    m.values()
                        .filter_map(|v| serde_json::from_value::<Symbol>(v.clone()).ok())
                        .filter_map(|sym| {
                            let entries = ledger_store
                                .list_entries(&ref_name, &sym.symbol_id)
                                .unwrap_or_default();
                            let has_ownership =
                                entries.iter().any(|e| e.kind == LedgerKind::Ownership);
                            let has_concept = entries.iter().any(|e| e.kind == LedgerKind::Concept);
                            if has_ownership && !has_concept {
                                Some(serde_json::json!({"qname": sym.qname, "file": sym.file}))
                            } else {
                                None
                            }
                        })
                        .collect()
                })
                .unwrap_or_default()
        };

        let trust = compute_trust_score(&db_path);

        // Plan J t-005: walk by-qname once to also report the
        // ASG-side symbol count alongside the FTS-side `count`,
        // so MCP `status` matches MCP `health`'s reconciliation
        // view and field-eval no longer sees two divergent
        // numbers without explanation.
        let asg_symbol_count = engine
            .repo
            .get_tree(&ref_name, "/asd/v1/index/by-qname")
            .ok()
            .and_then(|v| v.as_object().map(|m| m.len()));
        let index_consistency = asg_symbol_count
            .map(|asg| agentstatedeveloper_core::compute_index_consistency(asg, count as usize))
            .unwrap_or(serde_json::Value::Null);

        // Cache vs store vs sidecar ledger counts — see `asd status`. A
        // "hydrated" marker alone said nothing about lost entries.
        let ledger = agentstatedeveloper_core::ledger_counts(
            &engine.repo,
            &ref_name,
            engine.fts.as_ref(),
            Some(project_root),
        )
        .ok();
        let ledger_warning = ledger.as_ref().and_then(|l| l.warning());
        let sidecar_action = ledger_warning
            .clone()
            .unwrap_or_else(|| sidecar_action.to_string());

        let out = serde_json::json!({
            "db": db_path.display().to_string(),
            "symbols": count,
            "indexed_at_unix": indexed_at,
            "age_hours": age_hours,
            "state": index_state,
            "sidecar": sidecar_key,
            "sidecar_action": sidecar_action,
            "ledger": ledger,
            "ledger_warning": ledger_warning,
            "hooks_warning": agentstatedeveloper_core::outdated_hooks(project_root),
            "dirty_files": dirty_files,
            "concept_gaps": concept_gaps,
            "index_consistency": index_consistency,
            "trust": trust.to_json(),
        });
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    // -----------------------------------------------------------------------
    // Tool 6: scorecard — Benchmark dimensions
    // -----------------------------------------------------------------------

    #[tool(
        description = "Five-dimension benchmark scorecard: truth, feedback, change, uncertainty, workflow. Each scored 0-100. Use drill_down to see which symbols are gaps."
    )]
    async fn scorecard(&self, params: Parameters<ScorecardParams>) -> String {
        // Arithmetic lives in core::scorecard, shared with `asd scorecard`
        // and GET /api/v1/scorecard. This tool used to carry its own copy,
        // which had quietly fallen behind the CLI's: no token_economy, no
        // coverage_pct, no sparse-ledger note. Those arrive here now as a
        // side effect of there being one implementation.
        let p = params.0;
        let db_path = self.db_path();
        let engine = self.engine.lock().await;
        let card = agentstatedeveloper_core::scorecard::compute(
            &engine,
            &db_path,
            &agentstatedeveloper_core::scorecard::ScorecardOptions {
                scope: p.scope.as_deref(),
                paths: p.paths.as_deref(),
                drill_down: p.drill_down.as_deref(),
                drill_limit: p.limit as usize,
            },
        );

        let mut out = card.to_json();
        if card.matched_nothing {
            if let Some(obj) = out.as_object_mut() {
                obj.insert(
                    "note".into(),
                    serde_json::json!(if card.scoped {
                        "no symbols matched the path filter"
                    } else {
                        "no symbols indexed — run `asd index` first"
                    }),
                );
            }
        }
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }

    // -----------------------------------------------------------------------
    // Tool 7: annotate_commit — Derive ledger annotations from a commit
    // -----------------------------------------------------------------------

    #[tool(
        description = "Derive ledger annotations (decisions, invariants, hazards, proofs) from a git commit's message and changed files. Dry-run by default; pass write=true to persist."
    )]
    async fn annotate_commit(&self, params: Parameters<AnnotateCommitParams>) -> String {
        let p = params.0;
        let _db_path = self.db_path();
        let sha = p.sha.clone().unwrap_or_else(|| "HEAD".to_string());

        // Commit metadata
        let log_out = match Proc::new("git")
            .args(["log", "-1", "--format=%H%n%s%n%b", &sha])
            .output()
        {
            Ok(o) => o,
            Err(e) => return err_json(&format!("git log failed: {}", e)),
        };
        let log_str = String::from_utf8_lossy(&log_out.stdout);
        let mut log_lines = log_str.lines();
        let commit_hash = log_lines.next().unwrap_or("").trim().to_string();
        let subject = log_lines.next().unwrap_or("").trim().to_string();
        let body: String = log_lines.collect::<Vec<_>>().join("\n");

        if commit_hash.is_empty() {
            return err_json(&format!("could not resolve commit: {}", sha));
        }

        let full_body = if let Some(ref td) = p.task_description {
            format!("{body}\n{td}")
        } else {
            body
        };

        // Changed files
        let diff_out = match Proc::new("git")
            .args([
                "diff-tree",
                "--no-commit-id",
                "-r",
                "--name-only",
                &commit_hash,
            ])
            .output()
        {
            Ok(o) => o,
            Err(e) => return err_json(&format!("git diff-tree failed: {}", e)),
        };
        let changed_files: Vec<String> = String::from_utf8_lossy(&diff_out.stdout)
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty())
            .collect();

        if changed_files.is_empty() {
            return serde_json::to_string(&serde_json::json!({
                "commit": commit_hash, "subject": subject,
                "note": "no changed files detected", "suggested_entries": []
            }))
            .unwrap_or_else(|_| "{}".to_string());
        }

        let engine = self.engine.lock().await;
        let ref_name = engine.ref_name.clone();
        let index_store = AsgIndexStore::from_engine(&engine);
        let ledger_store = AsgLedgerStore::from_engine(&engine);

        let all_syms: Vec<Symbol> = index_store.build_id_map(&engine).into_values().collect();
        let mut touched_symbols: Vec<Symbol> = Vec::new();
        let mut seen_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
        for sym in &all_syms {
            if changed_files
                .iter()
                .any(|f| sym.file.ends_with(f.as_str()) || sym.file == *f)
            {
                if seen_ids.insert(sym.symbol_id.clone()) {
                    touched_symbols.push(sym.clone());
                }
            }
        }
        touched_symbols.truncate(20);

        // Docs-only path
        let all_docs = !changed_files.is_empty()
            && changed_files
                .iter()
                .all(|f| agentstatedeveloper_core::is_doc_file(std::path::Path::new(f)));

        if all_docs && touched_symbols.is_empty() {
            let candidate_syms: Vec<&Symbol> = all_syms
                .iter()
                .filter(|s| !agentstatedeveloper_core::is_doc_file(std::path::Path::new(&s.file)))
                .collect();
            for doc_file in &changed_files {
                let stem = std::path::Path::new(doc_file)
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("")
                    .to_lowercase();
                let file_terms: Vec<String> = stem
                    .replace(['-', '_', '.'], " ")
                    .split_whitespace()
                    .filter(|w| {
                        w.len() >= 3
                            && !matches!(
                                *w,
                                "the"
                                    | "and"
                                    | "for"
                                    | "doc"
                                    | "docs"
                                    | "readme"
                                    | "design"
                                    | "notes"
                                    | "plan"
                                    | "spec"
                                    | "guide"
                                    | "api"
                            )
                    })
                    .map(|w| w.to_string())
                    .collect();
                if file_terms.is_empty() {
                    continue;
                }
                let best = candidate_syms
                    .iter()
                    .copied()
                    .map(|s| {
                        let haystack =
                            format!("{} {}", s.qname.to_lowercase(), s.file.to_lowercase());
                        let ts = file_terms
                            .iter()
                            .filter(|t| haystack.contains(t.as_str()))
                            .count();
                        let kb: isize = match kind_str(&s.kind) {
                            "module" | "class" | "struct" | "enum" | "trait" | "type"
                            | "interface" | "protocol" | "namespace" => 2,
                            _ => 0,
                        };
                        ((ts as isize) * 2 + kb, ts, s)
                    })
                    .filter(|(_, ts, _)| *ts >= 1)
                    .max_by_key(|(score, _, _)| *score);
                if let Some((_, _, sym)) = best {
                    if seen_ids.insert(sym.symbol_id.clone()) {
                        touched_symbols.push(sym.clone());
                    }
                }
            }
        }

        // Parse commit body for annotations
        struct Annotation {
            kind: LedgerKind,
            summary: String,
        }
        let mut annotations: Vec<Annotation> = Vec::new();
        if !subject.is_empty() {
            let subject_kind = if all_docs {
                LedgerKind::Concept
            } else {
                LedgerKind::Decision
            };
            annotations.push(Annotation {
                kind: subject_kind,
                summary: subject.clone(),
            });
        }
        for line in full_body.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            let (kind, text) = if let Some(rest) = line.strip_prefix("invariant:") {
                (LedgerKind::Invariant, rest.trim())
            } else if let Some(rest) = line.strip_prefix("hazard:") {
                (LedgerKind::Hazard, rest.trim())
            } else if let Some(rest) = line.strip_prefix("proof:") {
                (LedgerKind::Proof, rest.trim())
            } else if let Some(rest) = line.strip_prefix("validation_scenario:") {
                (LedgerKind::ValidationScenario, rest.trim())
            } else if let Some(rest) = line.strip_prefix("known_bug:") {
                (LedgerKind::KnownBug, rest.trim())
            } else if let Some(rest) = line.strip_prefix("concept:") {
                (LedgerKind::Concept, rest.trim())
            } else if let Some(rest) = line.strip_prefix("decision:") {
                (LedgerKind::Decision, rest.trim())
            } else {
                continue;
            };
            if !text.is_empty() {
                annotations.push(Annotation {
                    kind,
                    summary: text.to_string(),
                });
            }
        }

        // CTX provenance tags
        let ctx_plan = p.ctx_plan.clone().unwrap_or_default();
        let ctx_task_id = p.ctx_task.clone().unwrap_or_default();
        let mut ctx_tags: Vec<String> = Vec::new();
        if !ctx_plan.is_empty() {
            ctx_tags.push(format!("ctx:plan:{}", ctx_plan));
        }
        if !ctx_task_id.is_empty() {
            ctx_tags.push(format!("ctx:task:{}", ctx_task_id));
        }
        ctx_tags.push(format!(
            "commit:{}",
            &commit_hash[..8.min(commit_hash.len())]
        ));

        let author_id = p.author.clone().unwrap_or_else(|| {
            Proc::new("git")
                .args(["config", "user.name"])
                .output()
                .ok()
                .and_then(|o| String::from_utf8(o.stdout).ok())
                .unwrap_or_default()
                .trim()
                .to_string()
        });
        let author = Author {
            kind: AuthorKind::Human,
            id: author_id,
        };

        let mut suggested: Vec<serde_json::Value> = Vec::new();
        let mut written: Vec<serde_json::Value> = Vec::new();

        for sym in &touched_symbols {
            for ann in &annotations {
                let existing = ledger_store
                    .list_entries(&ref_name, &sym.symbol_id)
                    .unwrap_or_default();
                let already_exists = existing.iter().any(|e| {
                    e.kind == ann.kind && e.summary.to_lowercase() == ann.summary.to_lowercase()
                });
                if already_exists {
                    continue;
                }

                let entry_val = serde_json::json!({
                    "symbol": sym.qname,
                    "file": sym.file,
                    "kind": format!("{:?}", ann.kind).to_lowercase(),
                    "summary": ann.summary,
                });

                if p.write {
                    let mut entry = LedgerEntry::new(
                        sym.symbol_id.clone(),
                        ann.kind,
                        ann.summary.clone(),
                        author.clone(),
                    );
                    entry.tags.extend(ctx_tags.iter().cloned());
                    match ledger_store.append_entry(&ref_name, &entry, &author.id) {
                        Ok(_) => written.push(entry_val),
                        Err(e) => eprintln!("warn: could not write entry for {}: {e}", sym.qname),
                    }
                } else {
                    suggested.push(entry_val);
                }
            }
        }

        let out = if p.write {
            serde_json::json!({
                "commit": commit_hash, "subject": subject,
                "changed_files": changed_files,
                "touched_symbols": touched_symbols.len(),
                "written_entries": written,
            })
        } else {
            serde_json::json!({
                "commit": commit_hash, "subject": subject,
                "changed_files": changed_files,
                "touched_symbols": touched_symbols.iter().map(|s| &s.qname).collect::<Vec<_>>(),
                "suggested_entries": suggested,
                "note": "dry-run — pass write=true to record these entries",
            })
        };
        serde_json::to_string(&out).unwrap_or_else(|_| "{}".to_string())
    }
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for AsdMcpServer {}

// -- Helpers ----------------------------------------------------------------

fn mcp_git_recent_touches(files: &[(String, usize)], git_depth: usize) -> serde_json::Value {
    let mut result: Vec<serde_json::Value> = Vec::new();
    let mut sorted = files.to_vec();
    sorted.sort_by_key(|(_, d)| *d);
    for (file, _) in &sorted {
        let output = Proc::new("git")
            .args([
                "log",
                "--follow",
                &format!("-n{git_depth}"),
                "--pretty=format:%H\x1f%an\x1f%ad\x1f%s",
                "--date=short",
                "--",
                file,
            ])
            .output();
        let commits: Vec<serde_json::Value> = match output {
            Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter(|l| !l.is_empty())
                .filter_map(|line| {
                    let p: Vec<&str> = line.splitn(4, '\x1f').collect();
                    if p.len() == 4 {
                        Some(serde_json::json!({
                            "sha": &p[0][..8.min(p[0].len())],
                            "author": p[1], "date": p[2], "message": p[3],
                        }))
                    } else {
                        None
                    }
                })
                .collect(),
            _ => vec![],
        };
        if !commits.is_empty() {
            result.push(serde_json::json!({ "file": file, "commits": commits }));
        }
    }
    serde_json::json!(result)
}

fn err_json(msg: &str) -> String {
    serde_json::to_string(&serde_json::json!({ "error": msg }))
        .unwrap_or_else(|_| "{\"error\":\"unknown\"}".to_string())
}

/// Plan G t-003: deterministic ledger entry id for `asd think` writes so
/// re-running the initial-read prompt overwrites rather than duplicates.
/// Mirror of the CLI helper in commands/think.rs.
fn think_det_id(intent: &str, qname: &str, content: &str) -> String {
    let key = format!("think:{intent}:{qname}:{content}");
    let h = blake3::hash(key.as_bytes()).to_hex();
    let short: String = h.chars().take(24).collect();
    format!("led_think_{short}")
}

/// Plan G t-007: read the active CTX task id (env `CTX_ACTIVE_TASK`
/// JSON `{"task_id": "..."}`, fallback `.asd/cache/active-task.json`
/// under the DB parent). Mirrors the CLI helper so MCP-driven writes
/// inherit the same `ctx:task:<id>` provenance trail.
fn think_active_ctx_task_tag(db_path: &std::path::Path) -> Option<String> {
    let env_raw = std::env::var("CTX_ACTIVE_TASK").ok();
    let db_parent = db_path.parent();
    let raw = match env_raw {
        Some(s) if !s.is_empty() => s,
        _ => {
            let p = db_parent?
                .join(".asd")
                .join("cache")
                .join("active-task.json");
            std::fs::read_to_string(p).ok()?
        }
    };
    let v: serde_json::Value = serde_json::from_str(&raw).ok()?;
    let id = v.get("task_id")?.as_str()?;
    Some(format!("ctx:task:{id}"))
}

/// Stamp every `think_*` write with `source:asd-think` and (when set)
/// the active `ctx:task:<id>` tag.
fn think_push_provenance_tags(db_path: &std::path::Path, tags: &mut Vec<String>) {
    tags.push("source:asd-think".into());
    if let Some(t) = think_active_ctx_task_tag(db_path) {
        tags.push(t);
    }
}

fn parse_ledger_kind(s: &str) -> Result<LedgerKind, String> {
    match s.to_lowercase().as_str() {
        "decision" => Ok(LedgerKind::Decision),
        "assumption" => Ok(LedgerKind::Assumption),
        "constraint" => Ok(LedgerKind::Constraint),
        "rationale" => Ok(LedgerKind::Rationale),
        "hazard" => Ok(LedgerKind::Hazard),
        "tradeoff" => Ok(LedgerKind::Tradeoff),
        "invariant" => Ok(LedgerKind::Invariant),
        "ownership" => Ok(LedgerKind::Ownership),
        "proof" => Ok(LedgerKind::Proof),
        "validation_scenario" | "validationscenario" => Ok(LedgerKind::ValidationScenario),
        "known_bug" | "knownbug" => Ok(LedgerKind::KnownBug),
        "concept" => Ok(LedgerKind::Concept),
        "mapping" => Ok(LedgerKind::Mapping),
        "follow_up" | "followup" => Ok(LedgerKind::FollowUp),
        other => Err(format!(
            "unknown ledger kind: {}. Valid: decision, assumption, constraint, rationale, hazard, tradeoff, invariant, ownership, proof, validation_scenario, known_bug, concept, mapping, follow_up",
            other
        )),
    }
}

fn parse_author_kind(s: &str) -> Result<AuthorKind, String> {
    match s.to_lowercase().as_str() {
        "agent" => Ok(AuthorKind::Agent),
        "human" => Ok(AuthorKind::Human),
        other => Err(format!("unknown author kind: {}", other)),
    }
}

/// Resolve symbol_ids to full Symbol records by scanning the qname index.
fn resolve_symbols_by_ids(
    engine: &Engine,
    ids: &[String],
) -> agentstatedeveloper_core::Result<Vec<agentstatedeveloper_core::Symbol>> {
    let ref_name = &engine.ref_name;
    let prefix = format!(
        "{}/index/by-qname",
        agentstatedeveloper_core::ASD_PATH_PREFIX
    );
    let tree = match engine.repo.get_tree(ref_name, &prefix) {
        Ok(t) => t,
        Err(_) => return Ok(Vec::new()),
    };
    let qnames: Vec<String> = match tree {
        serde_json::Value::Object(map) => map.keys().cloned().collect(),
        _ => return Ok(Vec::new()),
    };
    let index = AsgIndexStore::from_engine(&engine);
    let id_set: std::collections::HashSet<&String> = ids.iter().collect();
    let mut out = Vec::new();
    for qn in qnames {
        if let Some(sym) = index.get_symbol_by_qname(ref_name, &qn)? {
            if id_set.contains(&sym.symbol_id) {
                out.push(sym);
            }
        }
    }
    out.sort_by(|a, b| a.qname.cmp(&b.qname));
    Ok(out)
}

/// Shell out to `rg --json --fixed-strings --word-regexp <name>` and return
/// a flat occurrence list. Used by the `references` MCP tool to provide rg
/// parity for literal symbol queries (Plan A, t-004).
fn rg_scan(
    root: &std::path::Path,
    name: &str,
    globs: &[String],
    limit: usize,
) -> Result<Vec<serde_json::Value>, String> {
    let mut cmd = Proc::new("rg");
    cmd.arg("--json")
        .arg("--fixed-strings")
        .arg("--word-regexp")
        .arg("--no-messages");
    for g in globs {
        cmd.arg("--glob").arg(g);
    }
    cmd.arg("--").arg(name).arg(".");
    cmd.current_dir(root);

    let output = cmd
        .output()
        .map_err(|e| format!("failed to spawn `rg` ({e}). Install ripgrep or skip this tool."))?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut occurrences = Vec::new();
    for line in stdout.lines() {
        let v: serde_json::Value = match serde_json::from_str(line) {
            Ok(v) => v,
            Err(_) => continue,
        };
        if v.get("type").and_then(|t| t.as_str()) != Some("match") {
            continue;
        }
        let data = match v.get("data") {
            Some(d) => d,
            None => continue,
        };
        let path = data
            .get("path")
            .and_then(|p| p.get("text"))
            .and_then(|t| t.as_str())
            .unwrap_or("");
        let line_no = data
            .get("line_number")
            .and_then(|n| n.as_u64())
            .unwrap_or(0);
        let text = data
            .get("lines")
            .and_then(|l| l.get("text"))
            .and_then(|t| t.as_str())
            .unwrap_or("")
            .trim_end_matches('\n')
            .to_string();
        let columns: Vec<u64> = data
            .get("submatches")
            .and_then(|s| s.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|sm| sm.get("start").and_then(|s| s.as_u64()))
                    .collect()
            })
            .unwrap_or_default();
        occurrences.push(serde_json::json!({
            "file": path,
            "line": line_no,
            "columns": columns,
            "text": text,
        }));
        if limit > 0 && occurrences.len() >= limit {
            break;
        }
    }
    Ok(occurrences)
}

#[cfg(test)]
mod tool_name_regression {
    //! MCP/CLI parity regression probe (Plan A, t-002).
    //!
    //! Asserts that the canonical tool names land in the router and that the
    //! drift patterns we explicitly retired (the `_of` suffix) do not return.
    //! If this test fails, the parity audit needs to be redone.

    use super::AsdMcpServer;

    #[test]
    fn renamed_tools_are_present_under_canonical_names() {
        let r = AsdMcpServer::tool_router();
        for name in ["callers", "callees", "effects", "traces"] {
            assert!(
                r.has_route(name),
                "expected canonical MCP tool `{name}` to be registered"
            );
        }
    }

    #[test]
    fn retired_of_suffix_names_are_absent() {
        let r = AsdMcpServer::tool_router();
        for name in ["callers_of", "callees_of", "effects_of", "traces_of"] {
            assert!(
                !r.has_route(name),
                "retired MCP tool name `{name}` is registered — drift has crept back in"
            );
        }
    }

    #[test]
    fn no_tool_name_uses_of_suffix() {
        let r = AsdMcpServer::tool_router();
        let offenders: Vec<String> = r
            .into_iter()
            .map(|route| route.attr.name.to_string())
            .filter(|n| n.ends_with("_of"))
            .collect();
        assert!(
            offenders.is_empty(),
            "MCP tool names must not end with `_of`; offenders: {offenders:?}"
        );
    }

    #[test]
    fn references_tool_is_registered() {
        // Plan A, t-004: `references` is the exact-symbol rg-parity tool.
        assert!(
            AsdMcpServer::tool_router().has_route("references"),
            "expected `references` MCP tool to be registered"
        );
    }

    #[test]
    fn sync_test_summary_map_tools_are_registered() {
        // Added so agents can flush the sidecar (the reindex tool points here),
        // summarize test output, and build the initial-read map over MCP.
        let r = AsdMcpServer::tool_router();
        assert!(r.has_route("sync"), "expected `sync` MCP tool registered");
        assert!(
            r.has_route("test_summary"),
            "expected `test_summary` MCP tool registered"
        );
        assert!(r.has_route("map"), "expected `map` MCP tool registered");
    }

    #[test]
    fn scopes_list_tool_is_registered() {
        // Plan A, t-005: discoverability for `--scope` / `--paths` filters.
        assert!(
            AsdMcpServer::tool_router().has_route("scopes_list"),
            "expected `scopes_list` MCP tool to be registered"
        );
    }

    #[test]
    fn conclusions_list_tool_is_registered() {
        // Plan B, t-003: bucketed view over the new conclusion classes.
        assert!(
            AsdMcpServer::tool_router().has_route("conclusions_list"),
            "expected `conclusions_list` MCP tool to be registered"
        );
    }

    #[test]
    fn conclusions_export_tool_is_registered() {
        // Plan B, t-004: write ledger → .asd/conclusions/*.jsonl.
        assert!(
            AsdMcpServer::tool_router().has_route("conclusions_export"),
            "expected `conclusions_export` MCP tool to be registered"
        );
    }

    #[test]
    fn conclusions_import_tool_is_registered() {
        // Plan B, t-005: read .asd/conclusions/*.jsonl → ledger.
        assert!(
            AsdMcpServer::tool_router().has_route("conclusions_import"),
            "expected `conclusions_import` MCP tool to be registered"
        );
    }

    #[test]
    fn recipe_classify_test_migration_tool_is_registered() {
        // Plan C t-004: first concrete recipe.
        assert!(
            AsdMcpServer::tool_router().has_route("recipe_classify_test_migration"),
            "expected `recipe_classify_test_migration` MCP tool to be registered"
        );
    }

    #[test]
    fn recipe_migrate_stale_tests_tool_is_registered() {
        // Plan F t-002: second recipe, adds Move action.
        assert!(
            AsdMcpServer::tool_router().has_route("recipe_migrate_stale_tests"),
            "expected `recipe_migrate_stale_tests` MCP tool to be registered"
        );
    }

    #[test]
    fn plan_g_think_tools_are_registered() {
        // Plan G t-003: agent-thinking write surface.
        let router = AsdMcpServer::tool_router();
        for name in [
            "think_speculate",
            "think_model",
            "think_failed",
            "think_question",
            "think_list",
        ] {
            assert!(
                router.has_route(name),
                "expected `{name}` MCP tool to be registered"
            );
        }
    }

    #[test]
    fn prefix_drifted_tools_keep_code_prefix() {
        // `code_*` names exist because the bare CLI counterparts (`search`,
        // `read`) would collide in MCP's flat namespace.
        let r = AsdMcpServer::tool_router();
        for name in ["code_search", "code_read", "code_query"] {
            assert!(
                r.has_route(name),
                "expected `{name}` to remain registered with the `code_` prefix"
            );
        }
    }
}

/// How often the registry watcher polls `~/.config/asd/repos.toml` for an
/// mtime change. Below the round-trip of any meaningful MCP tool call, so a
/// `asd repo use <other>` triggered from a separate shell becomes visible
/// before the agent's next tool invocation lands.
const REGISTRY_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(250);

/// Spawn a background task that follows the active repo recorded in
/// `~/.config/asd/repos.toml`. On every mtime change we re-read the registry
/// and, if the active repo's db path differs from what the engine currently
/// holds, open the new db and swap it in place. Errors are logged at WARN —
/// the watcher never poisons the running engine.
fn spawn_registry_watcher(engine: Arc<Mutex<Engine>>, db_path: Arc<std::sync::RwLock<PathBuf>>) {
    let registry_path = match agentstatedeveloper_core::registry::Registry::path() {
        Ok(p) => p,
        Err(e) => {
            tracing::warn!(error = %e, "registry watcher disabled: cannot resolve registry path");
            return;
        }
    };
    tokio::spawn(async move {
        let mut cached_mtime: Option<std::time::SystemTime> = None;
        loop {
            tokio::time::sleep(REGISTRY_POLL_INTERVAL).await;

            let mtime = std::fs::metadata(&registry_path)
                .and_then(|m| m.modified())
                .ok();
            if mtime == cached_mtime {
                continue;
            }
            cached_mtime = mtime;

            // Mtime changed (or first observation). Re-read the registry and
            // decide whether the active path actually moved.
            let reg = match agentstatedeveloper_core::registry::Registry::load_from(&registry_path)
            {
                Ok(r) => r,
                Err(e) => {
                    tracing::warn!(error = %e, "registry watcher: load failed");
                    continue;
                }
            };
            let Some(active) = reg.active() else {
                continue;
            };
            let current = db_path.read().ok().map(|g| g.clone()).unwrap_or_default();
            if active.path == current {
                continue;
            }

            match Engine::open_sqlite(&active.path) {
                Ok(new_engine) => {
                    {
                        let mut guard = engine.lock().await;
                        *guard = new_engine;
                    }
                    if let Ok(mut g) = db_path.write() {
                        *g = active.path.clone();
                    }
                    tracing::info!(
                        from = %current.display(),
                        to = %active.path.display(),
                        name = %active.name,
                        "switched active repo via registry",
                    );
                }
                Err(e) => {
                    tracing::warn!(
                        error = %e,
                        path = %active.path.display(),
                        "registry watcher: opening new db failed; keeping current engine",
                    );
                }
            }
        }
    });
}