khive-mcp 0.7.0

khive MCP server library — served via the kkernel binary
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
//! KhiveMcpServer — rmcp-based MCP server exposing a single `request` tool.
//!
//! Accepts the function-call DSL or JSON form and dispatches each parsed operation
//! through the [`VerbRegistry`] built from the configured packs.
//!
// FILE SIZE JUSTIFICATION: `run_parsed` is long because it encodes the
// execution-mode contract (Single/Parallel/Chain) as a single match
// expression. Splitting the three branches into separate functions would
// scatter the contract invariants (summary shape, aborted semantics,
// $prev substitution ordering) across files, making them harder to review
// as a unit. The module is the authoritative implementation of request
// dispatch and is intentionally co-located.

use std::{
    future::Future,
    sync::{
        atomic::{AtomicI64, Ordering},
        Arc,
    },
};

use futures::{stream::FuturesUnordered, StreamExt};
use rmcp::{
    handler::server::wrapper::Parameters,
    model::{Implementation, ServerCapabilities, ServerInfo},
    tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler, ServiceExt,
};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};

use khive_db::ConnectionPool;
use khive_request::{parse_request, ArgValue, DslError, ExecutionMode, ParsedOp, PrevFailure};
use khive_runtime::{
    present, render_format, KhiveRuntime, OutputFormat, PackLoadError, PackRegistry,
    PresentationMode, RuntimeConfig, RuntimeError, VerbPresentationPolicy, VerbRegistry,
    VerbRegistryBuilder,
};

use khive_storage::EdgeRelation;

use crate::coordinator::CoordinatorService;
use crate::tools::request::RequestParams;

/// Per-request parallelism stays bounded even when the parser accepts 100 ops; must be nonzero.
const MAX_BATCH_CONCURRENCY: usize = 8;

/// Half the frame remains for the daemon's outer serialization and budget-error entries.
const BATCH_RESPONSE_BUDGET_BYTES: usize = khive_runtime::daemon::MAX_FRAME_BYTES / 2;

struct BatchTask<F> {
    index: usize,
    tool: String,
    future: F,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum DispatchOrigin {
    Local,
    Daemon,
}

#[derive(Clone, Copy)]
struct RunParsedContext<'a> {
    enforce_response_budget: bool,
    from_wire: bool,
    identity: Option<&'a khive_runtime::RequestIdentity>,
}

/// Fingerprint the engine-coherence parts of a resolved [`RuntimeConfig`].
///
/// Two servers produce the same id iff they can safely share one warm engine:
/// same pack set (order-independent), same storage target, same embedders, same
/// backend topology/routing, and same construction-baked outbound and git-write
/// policies.
/// Identity fields (`namespace`, `actor_id`, `visible_namespaces`) are carried
/// per request in the daemon frame and must never enter this key. The daemon
/// compares this against each forwarded request's `config_id` and rejects
/// mismatches so a restricted client (e.g. `--pack kg`, `--db :memory:`) cannot
/// execute through the broader default daemon.
///
/// When `khive_cfg` is supplied and contains a non-empty `[[backends]]`
/// declaration, the backend topology (sorted backend list and pack→backend
/// assignments) is folded into the fingerprint so that two configs differing
/// only in pack routing produce different ids (ADR-049 / B-SHOULD-FIX-4).
///
/// When `khive_cfg` is `None` or its `backends` list is empty, the fingerprint
/// is byte-identical to what it would have been before this parameter was added.
///
/// `config.db_path` and each declared backend path are canonicalized against
/// the process's current working directory before entering the fingerprint. A
/// raw relative string (e.g. `./data/main.db`) would otherwise fingerprint
/// identically for two different projects that happen to declare or override
/// the same relative path, even though they resolve to two different files —
/// letting a warm daemon started for one project accept requests meant for
/// the other's database.
pub fn compute_config_id(
    config: &RuntimeConfig,
    khive_cfg: Option<&khive_runtime::KhiveConfig>,
) -> String {
    let mut packs = config.packs.clone();
    packs.sort();
    let db = config
        .db_path
        .as_deref()
        .map(canonical_fingerprint_path)
        .unwrap_or_else(|| ":memory:".to_string());
    let primary = config
        .embedding_model
        .as_ref()
        .map(|m| format!("{m:?}"))
        .unwrap_or_else(|| "none".to_string());
    let mut extra: Vec<String> = config
        .additional_embedding_models
        .iter()
        .map(|m| format!("{m:?}"))
        .collect();
    extra.sort();
    let mut outbound: Vec<String> = config
        .allowed_outbound_namespaces
        .iter()
        .map(|ns| ns.as_str().to_owned())
        .collect();
    outbound.sort();
    outbound.dedup();
    let mut git_write_hasher = Sha256::new();
    git_write_hasher.update(b"khive.git-write-policy.v1");
    git_write_hasher.update((config.git_write.allowed.len() as u64).to_be_bytes());
    for entry in &config.git_write.allowed {
        git_write_hasher.update((entry.repo.len() as u64).to_be_bytes());
        git_write_hasher.update(entry.repo.as_bytes());
        git_write_hasher.update((entry.branches.len() as u64).to_be_bytes());
        for branch in &entry.branches {
            git_write_hasher.update((branch.len() as u64).to_be_bytes());
            git_write_hasher.update(branch.as_bytes());
        }
    }
    let git_write = format!("{:x}", git_write_hasher.finalize());

    let base = format!(
        "packs=[{}];db={};embed={};extra=[{}];backend={:?};outbound=[{}];git_write={}",
        packs.join(","),
        db,
        primary,
        extra.join(","),
        config.backend_id,
        outbound.join(","),
        git_write,
    );

    // Fold backend topology when non-empty so two configs differing only in
    // pack→backend routing produce different config_ids (ADR-049).
    // When backends is empty this branch is skipped, preserving byte-identity
    // with the pre-change fingerprint.
    let topology = khive_cfg
        .filter(|cfg| !cfg.backends.is_empty())
        .map(|cfg| {
            let mut backend_entries: Vec<String> = cfg
                .backends
                .iter()
                .map(|b| {
                    let path = b
                        .path
                        .as_deref()
                        .map(canonical_fingerprint_path)
                        .unwrap_or_else(|| ":memory:".to_string());
                    format!("{}:{:?}:{}", b.name, b.kind, path)
                })
                .collect();
            backend_entries.sort();

            let mut pack_entries: Vec<String> = cfg
                .packs
                .iter()
                .map(|(pack, pc)| format!("{}={}", pack, pc.backend))
                .collect();
            pack_entries.sort();

            format!(
                ";backends=[{}];pack_backends=[{}]",
                backend_entries.join(","),
                pack_entries.join(","),
            )
        })
        .unwrap_or_default();

    format!("{base}{topology}")
}

/// Resolve any path headed into `config_id` fingerprinting — a declared
/// `[[backends]].path` or the resolved `RuntimeConfig.db_path` (itself
/// derived from `--db`/`KHIVE_DB`) — to a stable, cwd-independent string
/// without creating anything on disk.
///
/// Delegates to [`crate::serve::canonical_path_no_side_effects`] — the same
/// no-side-effects canonicalization the `--db` override equivalence check
/// uses — so a relative path resolves against the process's current working
/// directory the same way a real backend open would. Falls back to the raw
/// display string only on a canonicalization error (e.g. an unreadable
/// ancestor directory); this is strictly no worse than the pre-fix behavior,
/// which always used the raw string.
fn canonical_fingerprint_path(path: &std::path::Path) -> String {
    crate::serve::canonical_path_no_side_effects(path)
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| path.display().to_string())
}

/// Build a sorted, human-readable verb catalog from `(pack_name, verb_name, description)` triples.
///
/// When multiple packs register the same verb name, each pack's description is
/// emitted on its own continuation line with a `[pack]` prefix so the caller can
/// see every contributing pack. A `tracing::warn!` is emitted once per duplicate.
fn build_verb_catalog(verbs: impl IntoIterator<Item = (String, String, String)>) -> String {
    let mut by_verb: std::collections::BTreeMap<String, Vec<(String, String)>> =
        std::collections::BTreeMap::new();
    for (pack_name, verb_name, description) in verbs {
        by_verb
            .entry(verb_name)
            .or_default()
            .push((pack_name, description));
    }
    let mut out = String::new();
    for (name, pack_descs) in &by_verb {
        if pack_descs.len() > 1 {
            let packs: Vec<&str> = pack_descs.iter().map(|(p, _)| p.as_str()).collect();
            tracing::warn!(
                verb = %name,
                packs = ?packs,
                "verb registered by multiple packs; all descriptions included in catalog"
            );
        }
        out.push_str("  ");
        out.push_str(name);
        out.push_str("");
        if pack_descs.len() == 1 {
            out.push_str(&pack_descs[0].1);
        } else {
            for (i, (pack, desc)) in pack_descs.iter().enumerate() {
                if i > 0 {
                    out.push_str("\n    ");
                }
                out.push('[');
                out.push_str(pack);
                out.push_str("] ");
                out.push_str(desc);
            }
        }
        out.push('\n');
    }
    out
}

/// MCP server that dispatches all verbs through a [`VerbRegistry`].
#[derive(Clone)]
pub struct KhiveMcpServer {
    registry: VerbRegistry,
    /// Namespace this registry was built for. The stdio client passes it to the
    /// daemon; a namespace mismatch triggers local-dispatch fallback.
    default_namespace: String,
    /// Fingerprint of the resolved runtime config (packs, db target, embedders).
    /// The stdio client passes it to the daemon; a config mismatch triggers
    /// local-dispatch fallback so a restricted client never runs through the
    /// broader default daemon.
    config_id: String,
    /// Cross-backend coordinator (ADR-029 Phase 2). Present only in multi-backend
    /// deployments. `None` in single-backend mode — all dispatch goes through the
    /// `VerbRegistry` unchanged (zero-change invariant).
    coordinator: Option<Arc<dyn CoordinatorService>>,
    /// Pool arc for the WAL checkpoint background task. `None` for in-memory
    /// or registry-only servers that have no persistent database.
    pool: Option<Arc<ConnectionPool>>,
    /// File-backed backend pools beyond `pool` (ADR-091 Amendment 3
    /// fan-out): every additional backend a multi-backend boot wired, so the
    /// session sweep and the daemon's checkpoint ownership can cover them
    /// too. Always empty for a single-backend server — `pool` alone is that
    /// server's one backend.
    secondary_pools: Vec<Arc<ConnectionPool>>,
    /// Server-level default output format (ADR-078). Resolved from TOML →
    /// `KHIVE_OUTPUT_FORMAT` → builtin `json`. Per-request `format` fields
    /// override this at dispatch time.
    default_output_format: OutputFormat,
    /// Last instant at which this process's daemon schedule loop began a tick.
    /// Zero means this server instance has never observed the loop running.
    /// Shared by server clones but never persisted, so a replacement process
    /// cannot inherit a plausible-looking heartbeat from its predecessor.
    schedule_ticker_last_tick_micros: Arc<AtomicI64>,
}

/// Failure reason inside a [`PackRegError`].
pub enum PackRegFailure {
    UnknownPack(String),
    MissingDependency { pack: String, dep: String },
    Registry(khive_runtime::RuntimeError),
}

/// Returned by [`KhiveMcpServer::with_packs`] when pack registration fails.
/// The original runtime is returned so the caller can recover.
pub struct PackRegError {
    pub failure: PackRegFailure,
    pub runtime: KhiveRuntime,
}

impl std::fmt::Debug for PackRegError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut dbg = f.debug_struct("PackRegError");
        match &self.failure {
            PackRegFailure::UnknownPack(unknown) => dbg.field("unknown", unknown),
            PackRegFailure::MissingDependency { pack, dep } => {
                dbg.field("pack", pack).field("missing_dep", dep)
            }
            PackRegFailure::Registry(source) => dbg.field("source", source),
        }
        .finish_non_exhaustive()
    }
}

impl std::fmt::Display for PackRegError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.failure {
            PackRegFailure::UnknownPack(unknown) => write!(
                f,
                "unknown pack name {:?} — built-in packs: {}",
                unknown,
                builtin_pack_names().join(", ")
            ),
            PackRegFailure::MissingDependency { pack, dep } => write!(
                f,
                "pack {pack:?} requires {dep:?}, which is not in the requested pack list; \
                 add --pack {dep} before --pack {pack}"
            ),
            PackRegFailure::Registry(source) => write!(f, "pack registry build failed: {source}"),
        }
    }
}

impl std::error::Error for PackRegError {}

/// Built-in pack names known to this binary.
///
/// Sourced from `PackRegistry::discovered_names()` so the list always reflects
/// whatever pack crates are linked into the binary.
pub fn builtin_pack_names() -> Vec<&'static str> {
    PackRegistry::discovered_names()
}

/// Which MCP handshake mode [`KhiveMcpServer::serve_stdio`] should use for
/// this process instance (#714). Unix-only: the resumed-generation self-heal
/// re-exec this decides between requires `crate::daemon`'s Unix-only
/// mismatch-recovery machinery (in turn only ever armed by a Unix-domain-socket
/// daemon-forwarding protocol mismatch); non-Unix `serve_stdio` always takes
/// the plain handshake path (see its `#[cfg(not(unix))]` variant below).
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StdioServeMode {
    /// Normal MCP `initialize` handshake — the overwhelmingly common case.
    Handshake,
    /// Skip the handshake (`serve_directly`): this process is a resumed
    /// generation of a prior self-heal re-exec (`crate::daemon`, #714 §2.3).
    Resumed,
}

/// Pure decision behind [`StdioServeMode`], factored out so it is
/// unit-testable without driving real stdio I/O. `resumed_generation` is
/// [`crate::daemon::resumed_generation`]'s return value.
#[cfg(unix)]
fn stdio_serve_mode_for(resumed_generation: Option<u32>) -> StdioServeMode {
    match resumed_generation {
        Some(_) => StdioServeMode::Resumed,
        None => StdioServeMode::Handshake,
    }
}

impl KhiveMcpServer {
    /// Build a server from `runtime.config().packs`. Errors if any pack is unknown or missing deps.
    // The error variant intentionally carries the runtime so callers can recover.
    #[allow(clippy::result_large_err)]
    pub fn new(runtime: KhiveRuntime) -> Result<Self, PackRegError> {
        let packs: Vec<String> = runtime.config().packs.clone();
        // Fail-fast on bad packs so callers can decide recovery.
        // Schema plan application happens inside with_packs.
        Self::with_packs(runtime, &packs)
    }

    /// Build a server with an explicit pack list (strict — fails on unknown names).
    // The error variant intentionally carries the runtime by value so callers
    // can recover and retry. Boxing would force every recovery path through a
    // deref for no real benefit.
    #[allow(clippy::result_large_err)]
    pub fn with_packs(runtime: KhiveRuntime, packs: &[String]) -> Result<Self, PackRegError> {
        let gate = runtime.config().gate.clone();
        let default_namespace = runtime.config().default_namespace.clone();
        let config_id = compute_config_id(runtime.config(), None);
        let visible_namespaces = runtime.config().visible_namespaces.clone();
        let actor_id = runtime.config().actor_id.clone();
        let mut builder = VerbRegistryBuilder::new();
        builder.with_gate(gate);
        builder.with_default_namespace(default_namespace.as_str());
        builder.with_visible_namespaces(visible_namespaces);
        builder.with_actor_id(actor_id);
        // Wire the EventStore into the registry for audit persistence.
        if let Ok(tok) = runtime.authorize(khive_runtime::Namespace::local()) {
            if let Ok(event_store) = runtime.events(&tok) {
                builder.with_event_store(event_store);
            }
        }
        if let Err(load_err) = PackRegistry::register_packs(packs, runtime.clone(), &mut builder) {
            let failure = match load_err {
                PackLoadError::UnknownPack(name) => PackRegFailure::UnknownPack(name),
                PackLoadError::MissingDependency { pack, dep } => {
                    PackRegFailure::MissingDependency { pack, dep }
                }
            };
            return Err(PackRegError { failure, runtime });
        }
        let registry = builder.build().map_err(|source| PackRegError {
            failure: PackRegFailure::Registry(source),
            runtime: runtime.clone(),
        })?;
        // Aggregate pack-declared edge endpoint rules into the runtime
        // so `validate_edge_relation_endpoints` can consult them.
        runtime.install_edge_rules(registry.all_edge_rules());
        // Invoke `PackRuntime::register_embedders` on every pack so custom
        // embedding providers are available before the first verb dispatch.
        // Must happen after the registry is built (packs are ordered)
        // and before any `remember`/`recall` calls that would resolve embedders.
        registry.call_register_embedders(&runtime);
        // Invoke `PackRuntime::register_entity_type_validator` on every pack so
        // entity-type validation is active at the runtime layer for all write
        // paths, including direct `create_many` callers that bypass the handler.
        registry.call_register_entity_type_validators(&runtime);
        // #750: install pack-owned note-mutation hooks (currently
        // only khive-pack-memory's warm-ANN-cache invalidation) so KG's
        // update/delete verbs notify caching packs even though there is no
        // crate-level dependency between them.
        registry.call_register_note_mutation_hooks(&runtime);
        // Apply pack-auxiliary schema plans at startup so pack tables are
        // present before any handler runs. Errors are logged but not propagated
        // so a single pack's schema failure cannot abort startup.
        registry.apply_schema_plans(runtime.backend());
        // Capture the pool arc for the WAL checkpoint task. Only available for
        // file-backed databases; in-memory backends return None here.
        let pool = if runtime.backend().is_file_backed() {
            Some(runtime.backend().pool_arc())
        } else {
            None
        };
        Ok(Self {
            registry,
            default_namespace: default_namespace.as_str().to_string(),
            config_id,
            coordinator: None,
            pool,
            secondary_pools: Vec::new(),
            default_output_format: OutputFormat::Json,
            schedule_ticker_last_tick_micros: Arc::new(AtomicI64::new(0)),
        })
    }

    /// Build a server directly from a pre-configured registry.
    ///
    /// Intended for tests that need to inject mock packs (e.g. packs that
    /// return `RuntimeError::Khive` to exercise structured error serialization).
    /// Production code should use [`Self::new`] or [`Self::with_packs`].
    #[doc(hidden)]
    pub fn from_registry(registry: VerbRegistry) -> Self {
        Self {
            registry,
            default_namespace: "local".to_string(),
            // A registry injected directly has no resolved RuntimeConfig; use a
            // sentinel that matches no real daemon so such servers always
            // dispatch locally rather than forward.
            config_id: "registry-only".to_string(),
            coordinator: None,
            pool: None,
            secondary_pools: Vec::new(),
            default_output_format: OutputFormat::Json,
            schedule_ticker_last_tick_micros: Arc::new(AtomicI64::new(0)),
        }
    }

    /// Build a server from a pre-built registry with explicit namespace and config_id.
    ///
    /// Used by the multi-backend boot path in `serve.rs` where the registry is
    /// assembled externally before constructing the server.
    pub fn from_registry_with_meta(
        registry: VerbRegistry,
        default_namespace: &str,
        config_id: &str,
    ) -> Self {
        Self {
            registry,
            default_namespace: default_namespace.to_string(),
            config_id: config_id.to_string(),
            coordinator: None,
            pool: None,
            secondary_pools: Vec::new(),
            default_output_format: OutputFormat::Json,
            schedule_ticker_last_tick_micros: Arc::new(AtomicI64::new(0)),
        }
    }

    /// Override the server-level default output format (ADR-078).
    ///
    /// Called after construction to wire in the format resolved from
    /// `KHIVE_OUTPUT_FORMAT` or `[runtime] default_output_format` in
    /// `khive.toml`. Per-request `format` fields override this at dispatch time.
    pub fn with_default_output_format(mut self, fmt: OutputFormat) -> Self {
        self.default_output_format = fmt;
        self
    }

    /// Attach a cross-backend coordinator (ADR-029 Phase 2).
    ///
    /// Only multi-backend servers need a coordinator. Single-backend servers
    /// leave `coordinator` as `None` (zero-change invariant: all dispatch goes
    /// through `VerbRegistry` unchanged).
    pub fn with_coordinator(mut self, coordinator: Arc<dyn CoordinatorService>) -> Self {
        self.coordinator = Some(coordinator);
        self
    }

    /// Attach a connection pool for the WAL checkpoint background task.
    ///
    /// Used by the multi-backend boot path to wire the main backend's pool into a
    /// server built via `from_registry_with_meta` (which cannot carry a pool itself
    /// because registry-only construction has no access to the backend layer).
    pub fn with_pool(mut self, pool: Arc<ConnectionPool>) -> Self {
        self.pool = Some(pool);
        self
    }

    /// Attach every file-backed backend pool beyond the main one (ADR-091
    /// Amendment 3 fan-out), so the session sweep and the daemon's
    /// checkpoint task can cover the full multi-backend deployment instead
    /// of only `pool`.
    pub fn with_secondary_pools(mut self, pools: Vec<Arc<ConnectionPool>>) -> Self {
        self.secondary_pools = pools;
        self
    }

    /// Clone the verb registry for use by background tasks (e.g. channel polling loops).
    ///
    /// `VerbRegistry` is internally `Arc`-wrapped so this clone is cheap. The returned
    /// registry shares the same packs and dispatch state as the server.
    #[cfg(any(feature = "channel-email", feature = "channel-telegram"))]
    pub(crate) fn verb_registry_clone(&self) -> VerbRegistry {
        self.registry.clone()
    }

    /// Route a `link` or `search` verb through the coordinator when in multi-backend mode.
    ///
    /// Returns `Some(result)` when the coordinator handled the op (caller should skip
    /// `registry.dispatch`). Returns `None` (fall-through) when:
    /// - no coordinator is attached (`coordinator == None`)
    /// - the coordinator reports a single backend (`is_single_backend()`)
    /// - the verb is not `link` or `search`
    /// - args cannot be extracted for coordinator dispatch (e.g. non-UUID source/target)
    ///
    /// Result semantics mirror the per-op envelope from the registry:
    /// `Ok(Value)` → success payload (caller wraps in `{ok:true, tool, result}`).
    /// `Err((tool, error_value))` → error payload (caller wraps in `{ok:false, tool, error}`).
    ///
    /// `identity` mirrors the override [`Self::dispatch_op`] applies to the
    /// registry path (ADR-096 Fork 1): when present, its namespace is used
    /// instead of `self.default_namespace` so a per-request identity can't
    /// diverge between the coordinator intercept and the registry dispatch
    /// it falls through to.
    async fn dispatch_via_coordinator(
        &self,
        tool: &str,
        args_value: &Value,
        identity: Option<&khive_runtime::RequestIdentity>,
    ) -> Option<Result<Value, (String, Value)>> {
        let coord = self.coordinator.as_ref()?;
        if coord.is_single_backend() {
            return None;
        }
        dispatch_via_coordinator_inner(coord.as_ref(), &self.registry, tool, args_value, identity)
            .await
    }

    /// Namespace this server's registry was built for.
    pub fn default_namespace(&self) -> &str {
        &self.default_namespace
    }

    /// Fingerprint of the runtime config this server's registry was built for.
    pub fn config_id(&self) -> &str {
        &self.config_id
    }

    /// This server's resolved actor identity label, if configured (ADR-057).
    ///
    /// Read when building the daemon request frame (ADR-096 Fork 1) to carry
    /// this server's own identity on the wire, so a warm daemon with a
    /// different baked identity serves the request under this caller's
    /// actor instead of the daemon's.
    pub fn actor_id(&self) -> Option<&str> {
        self.registry.actor_id()
    }

    /// This server's resolved extra read-visibility namespaces (ADR-007
    /// Rev 4 Rule 3b). See [`Self::actor_id`] for why this is exposed
    /// (ADR-096 Fork 1).
    pub fn visible_namespaces(&self) -> &[khive_runtime::Namespace] {
        self.registry.visible_namespaces()
    }

    /// The connection pool to use for background WAL checkpointing, if any.
    ///
    /// Returns `None` for in-memory or registry-only servers.
    pub fn pool(&self) -> Option<Arc<ConnectionPool>> {
        self.pool.clone()
    }

    /// File-backed backend pools beyond [`Self::pool`] (ADR-091 Amendment 3
    /// fan-out). Empty for a single-backend server.
    pub fn secondary_pools(&self) -> Vec<Arc<ConnectionPool>> {
        self.secondary_pools.clone()
    }

    /// This server's configured audit `EventStore`, if any (ADR-094).
    ///
    /// Exposed so the `DaemonDispatch::event_store_for_checkpoint` impl and
    /// the email channel poll loop can append best-effort lifecycle events
    /// to the same sink gate-check audit rows already use, without a second
    /// constructor argument threaded everywhere a registry is built.
    pub fn event_store(&self) -> Option<Arc<dyn khive_storage::EventStore>> {
        self.registry.event_store()
    }

    /// The server-level default output format (ADR-078), as resolved at
    /// construction by [`crate::serve::apply_env_output_format`].
    pub fn default_output_format(&self) -> OutputFormat {
        self.default_output_format
    }

    /// Record that this process's daemon schedule loop began a tick.
    ///
    /// The loop calls this before starting its drain pass, including passes
    /// that find no due rows or return an error. A pass that wedges after this
    /// point leaves a frozen timestamp for callers to classify as stale.
    pub(crate) fn record_schedule_ticker_tick(&self) {
        self.schedule_ticker_last_tick_micros
            .store(chrono::Utc::now().timestamp_micros(), Ordering::Release);
    }

    /// Warm every pack's in-memory state. Called by the daemon in a background
    /// task after the socket is bound.
    pub async fn warm_all(&self) {
        self.registry.call_warm_all().await;
    }

    /// Serve over stdio (blocks until the connection closes).
    ///
    /// #714: a resumed generation (produced by `crate::daemon`'s in-place
    /// re-exec self-heal on a stale-protocol mismatch) skips the normal MCP
    /// initialize handshake via `serve_directly` — by construction, its peer
    /// already completed a real handshake with the prior generation over this
    /// same, uninterrupted stdio pipe pair, so waiting for another one would
    /// hang forever (the client has no reason to send a second `initialize`).
    /// A cold start (the overwhelmingly common case) is unaffected: no
    /// `--resumed-generation` marker means the normal `.serve()` handshake
    /// runs exactly as before this change.
    ///
    /// Both branches wrap the raw stdio transport in
    /// `crate::daemon::SelfHealOnFlushTransport` — the actual happens-after
    /// edge that fires an armed self-heal re-exec (or drain-and-exit) only
    /// once a message has genuinely finished flushing to the client, never
    /// on a fixed timer that could race a slow or backpressured stdout.
    #[cfg(unix)]
    pub async fn serve_stdio(self) -> anyhow::Result<()> {
        use rmcp::transport::{async_rw::AsyncRwTransport, stdio};

        let build_transport = || {
            let (read, write) = stdio();
            crate::daemon::SelfHealOnFlushTransport::new(AsyncRwTransport::new_server(read, write))
        };

        match stdio_serve_mode_for(crate::daemon::resumed_generation()) {
            StdioServeMode::Resumed => {
                let service = rmcp::service::serve_directly(self, build_transport(), None);
                service.waiting().await?;
            }
            StdioServeMode::Handshake => {
                let service = self.serve(build_transport()).await?;
                service.waiting().await?;
            }
        }
        Ok(())
    }

    /// Non-Unix stdio serving. The #714 self-heal re-exec mechanism
    /// (`crate::daemon`'s `SelfHealOnFlushTransport`/resumed-generation
    /// machinery) requires `exec()` (POSIX-only) and is only ever armed by a
    /// Unix-domain-socket daemon-forwarding protocol mismatch — there is
    /// nothing to self-heal from on this target (`--daemon` mode itself is
    /// Unix-only, see `serve.rs::serve_server`), so this path always runs the
    /// normal MCP `initialize` handshake directly over the raw stdio
    /// transport, with no resumed-generation skip and no flush-triggered hook.
    #[cfg(not(unix))]
    pub async fn serve_stdio(self) -> anyhow::Result<()> {
        use rmcp::transport::stdio;

        let service = self.serve(stdio()).await?;
        service.waiting().await?;
        Ok(())
    }

    /// Build the textual verb catalog included in the request tool's description.
    ///
    /// The list is rebuilt from the runtime registry so it always reflects which
    /// packs are actually loaded.
    fn verb_catalog(&self) -> String {
        let verbs = self
            .registry
            .all_verbs_with_names()
            .into_iter()
            .map(|(pack, v)| (pack.to_owned(), v.name.to_owned(), v.description.to_owned()));
        build_verb_catalog(verbs)
    }

    /// Dispatch a single [`ParsedOp`] by resolving its args (potentially
    /// substituting `$prev` references) and calling the [`VerbRegistry`].
    ///
    /// Returns a per-op result object: `{ok, tool, result}` on success or
    /// `{ok: false, tool, error}` on failure.
    async fn dispatch_op(
        &self,
        op: ParsedOp,
        prev_result: Option<&Value>,
        from_wire: bool,
        identity: Option<&khive_runtime::RequestIdentity>,
    ) -> Result<Value, (String, Value)> {
        let ParsedOp { tool, args } = op;

        // Resolve args — substitute $prev references when prev_result is Some.
        // Handles flat PrevRef as well as Array/Object containing nested refs.
        let mut resolved: serde_json::Map<String, Value> = serde_json::Map::new();
        for (name, arg_val) in args {
            let needs_prev = !matches!(&arg_val, ArgValue::Value(_));
            let value = if needs_prev {
                // `dispatch_op` only ever runs inside a chain (see `run_parsed`'s
                // `ExecutionMode::Chain` arm); `prev_result` is `None` here
                // exactly when this is the chain's first op, so there is no
                // preceding result to substitute from at all.
                let prev = prev_result.ok_or_else(|| {
                    (
                        tool.clone(),
                        json!({
                            "kind": "substitution_error",
                            "reason": "no_preceding_op",
                            "message": format!(
                                "argument {name:?}: $prev has no preceding op to resolve \
                                 against — this is the first operation in the chain. $prev \
                                 always resolves against the immediately preceding op's result \
                                 only; it cannot reach further back or forward. Move this op \
                                 after the one that produces the value, or pass a literal value \
                                 here instead of $prev."
                            )
                        }),
                    )
                })?;
                let resolved_val = arg_val.resolve_all(prev).ok_or_else(|| {
                    (
                        tool.clone(),
                        substitution_error_payload(&name, &arg_val, prev),
                    )
                })?;
                // UE4-H1: bare `$prev` (no path) resolving to a map or array
                // will cause a confusing downstream type error. Detect it here and
                // surface a clear substitution error with available field names.
                if matches!(&arg_val, ArgValue::PrevRef { path } if path.is_empty()) {
                    match &resolved_val {
                        Value::Object(map) => {
                            let fields: Vec<&str> = map.keys().map(String::as_str).collect();
                            return Err((
                                tool.clone(),
                                json!({
                                    "kind": "substitution_error",
                                    "reason": "bare_ref_ambiguous",
                                    "message": format!(
                                        "argument {name:?}: $prev requires a dotted path \
                                         (e.g. $prev.id) when the prior result is a map. \
                                         Available top-level fields: [{}]",
                                        fields.join(", ")
                                    ),
                                }),
                            ));
                        }
                        Value::Array(_) => {
                            return Err((
                                tool.clone(),
                                json!({
                                    "kind": "substitution_error",
                                    "reason": "bare_ref_ambiguous",
                                    "message": format!(
                                        "argument {name:?}: $prev requires a dotted path \
                                         (e.g. $prev.0) when the prior result is an array. \
                                         Use $prev.N to select a specific element."
                                    ),
                                }),
                            ));
                        }
                        _ => {}
                    }
                }
                resolved_val
            } else {
                match arg_val {
                    ArgValue::Value(v) => v,
                    _ => unreachable!(),
                }
            };
            resolved.insert(name, value);
        }

        let args_value = Value::Object(resolved);

        // Subhandler verbs are operator-only — block them at the MCP wire
        // boundary (`from_wire`), never on the operator path (`kkernel exec`,
        // in-process callers). Exception: `help=true` is short-circuited in
        // VerbRegistry::dispatch before reaching the pack, so introspection works.
        let is_help = args_value
            .get("help")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        if from_wire && !is_help && self.registry.is_subhandler_verb(&tool) {
            return Err((
                tool.clone(),
                json!(format!(
                    "permission denied for verb {tool:?}: verb '{tool}' is an internal \
                     subhandler and cannot be invoked via the MCP request surface"
                )),
            ));
        }

        // Multi-backend interception: route link/search through the coordinator (ADR-029 D3/D4).
        // Single-backend and non-link/search verbs fall through to the registry unchanged.
        if let Some(coord_result) = self
            .dispatch_via_coordinator(&tool, &args_value, identity)
            .await
        {
            return coord_result.and_then(|result| chain_ok_envelope_or_depth_error(tool, result));
        }

        match self
            .registry
            .dispatch_with_identity(&tool, args_value, identity.cloned())
            .await
        {
            Ok(result) => {
                let result = decorate_schedule_agenda_with_ticker_health(
                    &tool,
                    is_help,
                    result,
                    self.schedule_ticker_last_tick_micros.as_ref(),
                );
                chain_ok_envelope_or_depth_error(tool, result)
            }
            Err(RuntimeError::Khive(k)) => {
                let error_payload = serde_json::to_value(&k)
                    .unwrap_or_else(|_| json!({ "kind": "internal", "message": k.to_string() }));
                Err((tool, error_payload))
            }
            Err(e) => Err((tool, json!(e.to_string()))),
        }
    }

    /// Execute a parsed request, dispatching according to its [`ExecutionMode`].
    ///
    /// - `Single` / `Parallel`: at most [`MAX_BATCH_CONCURRENCY`] ops run at
    ///   once; per-op failure does not abort siblings. `aborted` count is 0.
    /// - `Chain`: ops run sequentially; `$prev` from each op's result is
    ///   substituted into the next op's args. If any op fails (or a `$prev`
    ///   substitution fails), remaining ops appear as `aborted: true`.
    ///
    /// Presentation transforms are applied per-op AFTER dispatch,
    /// using `mode_for_op` to determine the mode per position. Chain `$prev`
    /// substitution uses canonical (verbose) handler output; the transform runs
    /// only at the final response-envelope boundary.
    ///
    /// Response envelope:
    /// ```json
    /// {
    ///   "results": [...],
    ///   "summary": { "total": N, "succeeded": K, "failed": M, "aborted": A },
    ///   "status": "success" | "partial"
    /// }
    /// ```
    ///
    /// `status` is a structural signal for a partially-failed batch (#1220):
    /// per-op `results` entries and `summary.failed`/`summary.aborted` counts
    /// already carry this information, but a caller that checks only for the
    /// absence of a top-level RPC error has nothing to branch on. `"partial"`
    /// means at least one op in this response failed or was aborted;
    /// `"success"` means every op in `results` reports `ok: true`.
    async fn run_parsed(
        &self,
        ops: Vec<ParsedOp>,
        mode: ExecutionMode,
        presentation: PresentationMode,
        presentation_per_op: Option<Vec<Option<PresentationMode>>>,
        context: RunParsedContext<'_>,
    ) -> Value {
        let RunParsedContext {
            enforce_response_budget,
            from_wire,
            identity,
        } = context;
        let response_budget = if mode == ExecutionMode::Parallel && enforce_response_budget {
            BATCH_RESPONSE_BUDGET_BYTES
        } else {
            usize::MAX
        };
        let now_unix = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()
            .and_then(|d| i64::try_from(d.as_secs()).ok())
            .unwrap_or(0);

        // Resolve per-op presentation mode: per-op entry overrides batch default.
        let mode_for_op = |i: usize| -> PresentationMode {
            presentation_per_op
                .as_ref()
                .and_then(|v| v.get(i))
                .and_then(|o| *o)
                .unwrap_or(presentation)
        };

        match mode {
            ExecutionMode::Single | ExecutionMode::Parallel => {
                // Write-key conflict preflight.
                //
                // Detect ops that target the same write key in the same parallel/single
                // batch. Conflicting ops receive per-op error entries; non-conflicting ops
                // execute normally. `results.length == summary.total` is preserved.
                let conflict_indices: std::collections::HashSet<usize> = {
                    let mut seen: std::collections::HashMap<String, usize> =
                        std::collections::HashMap::new();
                    let mut bad: std::collections::HashSet<usize> =
                        std::collections::HashSet::new();
                    for (i, op) in ops.iter().enumerate() {
                        for key in khive_request::write_keys_for_op_pub(op) {
                            if let Some(&prior) = seen.get(&key) {
                                bad.insert(prior);
                                bad.insert(i);
                            } else {
                                seen.insert(key, i);
                            }
                        }
                    }
                    bad
                };

                // Clone coordinator and namespace for use in the per-op closures (ADR-029 D3/D4).
                let coordinator: Option<Arc<dyn CoordinatorService>> = self.coordinator.clone();
                let schedule_ticker_last_tick_micros =
                    self.schedule_ticker_last_tick_micros.clone();
                // ADR-096 Fork 1: a per-request identity overrides the default
                // namespace for both the coordinator intercept and the registry
                // dispatch below, so the two can't drift out of sync per op.
                let identity_owned: Option<khive_runtime::RequestIdentity> = identity.cloned();

                // Independent dispatch — bounded concurrency, results restored to input order.
                let futures = ops.into_iter().enumerate().map(|(i, op)| {
                    let conflict_with: Option<String> = if conflict_indices.contains(&i) {
                        Some(format!(
                            "conflict: writes overlap with another op in this batch (op #{})",
                            i
                        ))
                    } else {
                        None
                    };

                    let registry = self.registry.clone();
                    let coord = coordinator.clone();
                    let schedule_ticker_last_tick_micros =
                        schedule_ticker_last_tick_micros.clone();
                    let op_identity = identity_owned.clone();
                    let op_mode = mode_for_op(i);
                    let task_tool = op.tool.clone();
                    BatchTask {
                        index: i,
                        tool: task_tool,
                        future: async move {
                        // ADR-103 Amendment 2: one dispatch-accounting context
                        // per op; the entry is stamped with the frozen usage
                        // snapshot after dispatch resolves.
                        let usage_ctx = khive_runtime::usage::UsageContext::new();
                        let mut entry = khive_runtime::usage::scope(usage_ctx.clone(), async {
                        let tool = op.tool.clone();
                        // Conflicting ops get a per-op error; skip dispatch.
                        if let Some(msg) = conflict_with {
                            return json!({ "ok": false, "tool": tool, "error": msg });
                        }
                        // AlwaysVerbose verbs override the caller's presentation mode.
                        let effective_mode =
                            if registry.presentation_policy_for(&tool)
                                == VerbPresentationPolicy::AlwaysVerbose
                            {
                                PresentationMode::Verbose
                            } else {
                                op_mode
                            };
                        // No $prev in parallel/single mode — PrevRef, Array(PrevRef),
                        // and Object(PrevRef) are all errors here.
                        let mut resolved: serde_json::Map<String, Value> =
                            serde_json::Map::new();
                        let mut prev_error: Option<Value> = None;
                        for (name, arg_val) in &op.args {
                            if matches!(arg_val, ArgValue::Value(_)) {
                                if let ArgValue::Value(v) = arg_val {
                                    resolved.insert(name.clone(), v.clone());
                                }
                            } else {
                                prev_error = Some(json!({
                                    "ok": false,
                                    "tool": tool,
                                    "error": format!(
                                        "argument {name:?}: $prev reference is only valid in chain (|) mode"
                                    )
                                }));
                                break;
                            }
                        }
                        if let Some(err) = prev_error {
                            return err;
                        }
                        let args_value = Value::Object(resolved);

                        // Block subhandler verbs at the MCP wire boundary
                        // (`from_wire`) only — operator paths pass through.
                        // Exception: help=true is short-circuited in
                        // VerbRegistry::dispatch before the pack, so
                        // introspection passes through.
                        let is_help = args_value
                            .get("help")
                            .and_then(Value::as_bool)
                            .unwrap_or(false);
                        if from_wire && !is_help && registry.is_subhandler_verb(&tool) {
                            return json!({
                                "ok": false,
                                "tool": tool,
                                "error": format!(
                                    "permission denied for verb {tool:?}: verb '{tool}' is an \
                                     internal subhandler and cannot be invoked via the MCP \
                                     request surface"
                                )
                            });
                        }

                        // Multi-backend interception: route link/search through the coordinator
                        // (ADR-029 D3/D4). Falls through to registry for single-backend and
                        // non-link/search verbs.
                        if let Some(active_coord) = coord.as_ref() {
                            if !active_coord.is_single_backend() {
                                if let Some(coord_result) = dispatch_via_coordinator_inner(
                                    active_coord.as_ref(),
                                    &registry,
                                    &tool,
                                    &args_value,
                                    op_identity.as_ref(),
                                )
                                .await
                                {
                                    return match coord_result {
                                        Ok(result) => present_ok_envelope_or_depth_error(
                                            tool,
                                            result,
                                            effective_mode,
                                            now_unix,
                                        ),
                                        Err((_, error_payload)) => {
                                            json!({ "ok": false, "tool": tool, "error": error_payload })
                                        }
                                    };
                                }
                            }
                        }

                        match registry
                            .dispatch_with_identity(&tool, args_value, op_identity)
                            .await
                        {
                            Ok(result) => {
                                let result = decorate_schedule_agenda_with_ticker_health(
                                    &tool,
                                    is_help,
                                    result,
                                    schedule_ticker_last_tick_micros.as_ref(),
                                );
                                present_ok_envelope_or_depth_error(
                                    tool,
                                    result,
                                    effective_mode,
                                    now_unix,
                                )
                            }
                            Err(RuntimeError::Khive(k)) => {
                                let error_payload = serde_json::to_value(&k).unwrap_or_else(
                                    |_| json!({ "kind": "internal", "message": k.to_string() }),
                                );
                                json!({ "ok": false, "tool": tool, "error": error_payload })
                            }
                            Err(e) => json!({ "ok": false, "tool": tool, "error": e.to_string() }),
                        }
                        })
                        .await;
                        stamp_usage(&mut entry, &usage_ctx);
                        entry
                        },
                    }
                });
                let results = execute_bounded_batch(futures, response_budget).await;
                parallel_batch_envelope(results)
            }
            ExecutionMode::Chain => {
                // Sequential execution with $prev substitution and abort-on-failure.
                // $prev uses canonical (verbose) handler output — presentation runs
                // only at the final response-envelope boundary.
                let total = ops.len();
                let mut results: Vec<Value> = Vec::with_capacity(total);
                // prev_result holds the CANONICAL result (pre-presentation) for $prev.
                let mut prev_result: Option<Value> = None;
                let mut aborted_from: Option<usize> = None;

                for (i, op) in ops.into_iter().enumerate() {
                    if let Some(failed_at) = aborted_from {
                        // A prior op failed — mark remaining as aborted, and say so
                        // plainly: this op was never dispatched (its own $prev, if any,
                        // was never attempted), so the failure to debug lives at the
                        // earlier op, not here.
                        let failed_index = failed_at - 1;
                        let failed_tool = results
                            .get(failed_index)
                            .and_then(|r| r.get("tool"))
                            .and_then(Value::as_str)
                            .unwrap_or("<unknown>");
                        results.push(json!({
                            "ok": false,
                            "tool": op.tool,
                            "aborted": true,
                            "message": format!(
                                "not executed: op #{failed_index} ({failed_tool:?}) failed \
                                 earlier in this chain, so the chain aborted before reaching \
                                 this op. Fix op #{failed_index} — this op's own arguments, \
                                 including any $prev reference, were never evaluated."
                            ),
                        }));
                        continue;
                    }
                    let op_mode = mode_for_op(i);
                    // AlwaysVerbose verbs override the caller's presentation mode.
                    let effective_mode = if self.registry.presentation_policy_for(&op.tool)
                        == VerbPresentationPolicy::AlwaysVerbose
                    {
                        PresentationMode::Verbose
                    } else {
                        op_mode
                    };
                    let usage_ctx = khive_runtime::usage::UsageContext::new();
                    match khive_runtime::usage::scope(
                        usage_ctx.clone(),
                        self.dispatch_op(op, prev_result.as_ref(), from_wire, identity),
                    )
                    .await
                    {
                        Ok(mut result_obj) => {
                            stamp_usage(&mut result_obj, &usage_ctx);
                            // Guard against a pathologically deep handler result
                            // (e.g. `traverse`/`context`) before it is ever cloned
                            // into `$prev` context or handed to presentation/
                            // serialization, both of which recurse natively over
                            // `Value` and would otherwise be exposed to the same
                            // unbounded-nesting stack-overflow risk (CWE-674) the
                            // DSL parser guard already closes for syntax input.
                            match chain_aggregation_depth_reject(result_obj) {
                                Err(error_entry) => {
                                    results.push(error_entry);
                                    prev_result = None;
                                    aborted_from = Some(i + 1);
                                    continue;
                                }
                                Ok(result_obj) => {
                                    // Extract canonical result for $prev (pre-presentation).
                                    prev_result = result_obj.get("result").cloned();
                                    // Apply presentation to the result field only,
                                    // using the effective mode (AlwaysVerbose override honored).
                                    let presented_obj = apply_presentation_to_result(
                                        result_obj,
                                        effective_mode,
                                        now_unix,
                                    );
                                    results.push(presented_obj);
                                }
                            }
                        }
                        Err((tool, error_payload)) => {
                            let mut entry =
                                json!({ "ok": false, "tool": tool, "error": error_payload });
                            stamp_usage(&mut entry, &usage_ctx);
                            results.push(entry);
                            aborted_from = Some(i + 1);
                        }
                    }
                }

                let succeeded = results
                    .iter()
                    .filter(|r| r.get("ok").and_then(Value::as_bool) == Some(true))
                    .count();
                let aborted = results
                    .iter()
                    .filter(|r| r.get("aborted").and_then(Value::as_bool) == Some(true))
                    .count();
                let failed = total - succeeded - aborted;
                json!({
                    "results": results,
                    "summary": { "total": total, "succeeded": succeeded, "failed": failed, "aborted": aborted },
                    "status": batch_status(failed, aborted),
                })
            }
        }
    }
}

/// Route a `link` or `search` verb through `coord` when in multi-backend mode.
/// Shared logic behind both dispatch sites (`dispatch_op` chain mode and the
/// parallel/single closure in `run_parsed`). Returns `Some(Ok(Value))` when
/// the coordinator handled the op, `Some(Err((tool, error_value)))` on a
/// coordinator error (including fail-closed namespace rejection), `None` to
/// fall through to the registry. Must apply the exact same fail-closed
/// namespace rule as `VerbRegistry::dispatch` (RUNTIME-AUD-002, #433) — see
/// `crates/khive-mcp/docs/api/coordinator.md`.
async fn dispatch_via_coordinator_inner(
    coord: &dyn CoordinatorService,
    registry: &VerbRegistry,
    tool: &str,
    args_value: &Value,
    identity: Option<&khive_runtime::RequestIdentity>,
) -> Option<Result<Value, (String, Value)>> {
    // Only link/search are ever intercepted here.
    if !matches!(tool, "link" | "search") {
        return None;
    }

    match tool {
        "link" => {
            // Only intercept single-link form (not bulk `links` array).
            // Bulk link falls through to the registry for now.
            if args_value.get("links").is_some() {
                return None;
            }
            let source_str = args_value.get("source_id")?.as_str()?;
            let target_str = args_value.get("target_id")?.as_str()?;
            let relation_str = args_value.get("relation")?.as_str()?;

            // Only intercept when both endpoints are parseable UUIDs.
            // Name/prefix resolution requires single-backend context — fall through.
            let source_id: uuid::Uuid = source_str.parse().ok()?;
            let target_id: uuid::Uuid = target_str.parse().ok()?;
            let relation: EdgeRelation = relation_str.parse().ok()?;
            let weight = args_value
                .get("weight")
                .and_then(Value::as_f64)
                .unwrap_or(1.0);
            let metadata = args_value.get("metadata").cloned();

            let result = registry
                .dispatch_intercepted_with_identity(
                    tool,
                    args_value,
                    identity,
                    |namespace| async move {
                        let coord_result = coord
                            .link(&namespace, source_id, target_id, relation, weight, metadata)
                            .await
                            .map_err(RuntimeError::from)?;
                        let mut raw = serde_json::to_value(&coord_result.edge)
                            .unwrap_or_else(|e| json!({"error": format!("serialize edge: {e}")}));
                        if relation.is_symmetric() {
                            if let Some(obj) = raw.as_object_mut() {
                                obj.insert("source_id".to_string(), json!(source_id.to_string()));
                                obj.insert("target_id".to_string(), json!(target_id.to_string()));
                            }
                        }
                        Ok(raw)
                    },
                )
                .await;
            Some(result.map_err(|error| runtime_error_payload(tool, error)))
        }
        "search" => {
            let kind = args_value.get("kind")?.as_str()?;
            let query = args_value.get("query")?.as_str()?;
            let result = registry
                .dispatch_intercepted_with_identity(
                    tool,
                    args_value,
                    identity,
                    |namespace| async move {
                        // Parse strictly as u32 (matching the single-backend `SearchParams { limit:
                        // Option<u32> }` contract) instead of parsing as u64 and casting — `as u32`
                        // wraps values above `u32::MAX` (e.g. 4294967297 as u32 == 1) before the
                        // `.min(100)` cap ever runs, silently truncating a huge limit to a near-empty
                        // result set rather than rejecting it (MCP-AUD-003).
                        let limit = match args_value.get("limit") {
                            None | Some(Value::Null) => 10,
                            Some(v) => match serde_json::from_value::<u32>(v.clone()) {
                                Ok(limit) => limit.min(100),
                                Err(_) => {
                                    return Err(RuntimeError::InvalidInput(
                                        "limit must be an unsigned 32-bit integer".to_string(),
                                    ));
                                }
                            },
                        };
                        let score_floor = args_value
                            .get("min_score")
                            .and_then(Value::as_f64)
                            .unwrap_or(0.0)
                            .max(0.0);

                        // For substrate-level kinds ("entity" / "note"), pass None so the search
                        // is unrestricted. For granular kinds ("concept", "observation", etc.) pass
                        // the kind string so each backend filters at the storage layer — matching
                        // the behaviour of the single-backend handler (search.rs).
                        let kind_filter: Option<&str> = match kind {
                            "entity" | "note" => None,
                            other => Some(other),
                        };

                        // Extract entity-substrate filters and forward them to each backend.
                        // When either is active the coordinator widens the per-backend candidate
                        // window so that sparse matches ranked below the bare limit are not cut
                        // off before filtering (before-truncation parity with the single-backend
                        // handler in search.rs).
                        let props_filter: Option<&serde_json::Value> =
                            args_value.get("properties").and_then(|v| {
                                if v.as_object().is_some_and(|m| !m.is_empty()) {
                                    Some(v)
                                } else {
                                    None
                                }
                            });
                        // Parse tags strictly: absent/null → no filter (empty Vec); present and
                        // valid Vec<String> → use as-is (including empty array → no filter);
                        // present but not a Vec<String> → reject with a per-op error so the
                        // multi-backend path matches single-backend behaviour, which rejects
                        // malformed tags via SearchParams deserialisation (RuntimeError::InvalidInput).
                        // filter_map(as_str) would silently drop non-string entries and produce
                        // an empty Vec, bypassing the filter and returning unfiltered results.
                        let tags_owned: Vec<String> = match args_value.get("tags") {
                            None | Some(Value::Null) => vec![],
                            Some(v) => match serde_json::from_value::<Vec<String>>(v.clone()) {
                                Ok(t) => t,
                                Err(_) => {
                                    return Err(RuntimeError::InvalidInput(
                                        "tags must be an array of strings".to_string(),
                                    ));
                                }
                            },
                        };

                        let coord_result = coord
                            .fan_out_search(
                                kind,
                                query,
                                &namespace,
                                limit,
                                kind_filter,
                                props_filter,
                                &tags_owned,
                            )
                            .await;

                        // Shape result to match the kg search handler's output fields exactly.
                        // Entity hits: [{id, entity_kind, score, title, snippet}]
                        //   - entity_kind: real kind string fetched from the owning backend
                        //   - score: RRF-merged, subject to min_score floor
                        // Note hits:   [{id, note_kind, score, title, snippet}]
                        //   - note_kind: real kind string fetched from the owning backend
                        let result_val = if !coord_result.note_hits.is_empty()
                            || (coord_result.entity_hits.is_empty()
                                && coord_result.note_hits.is_empty())
                        {
                            // Note substrate or empty — return note-shaped result.
                            let items: Vec<Value> = coord_result
                                .note_hits
                                .iter()
                                .filter(|h| h.score.to_f64() >= score_floor)
                                .map(|h| {
                                    let note_kind = coord_result.note_kinds.get(&h.note_id);
                                    json!({
                                        "id": h.note_id.to_string(),
                                        "note_kind": note_kind,
                                        "score": h.score.to_f64(),
                                        "source": h.source.as_str(),
                                        "title": h.title,
                                        "snippet": h.snippet,
                                    })
                                })
                                .collect();
                            serde_json::to_value(items).unwrap_or_else(|_| json!([]))
                        } else {
                            // Entity substrate — return entity-shaped result.
                            let items: Vec<Value> = coord_result
                                .entity_hits
                                .iter()
                                .filter(|h| h.score.to_f64() >= score_floor)
                                .map(|h| {
                                    let entity_kind = coord_result.entity_kinds.get(&h.entity_id);
                                    json!({
                                        "id": h.entity_id.to_string(),
                                        "entity_kind": entity_kind,
                                        "score": h.score.to_f64(),
                                        "source": h.source.as_str(),
                                        "title": h.title,
                                        "snippet": h.snippet,
                                    })
                                })
                                .collect();
                            serde_json::to_value(items).unwrap_or_else(|_| json!([]))
                        };

                        Ok(result_val)
                    },
                )
                .await;
            Some(result.map_err(|error| runtime_error_payload(tool, error)))
        }
        _ => None,
    }
}

fn runtime_error_payload(tool: &str, error: RuntimeError) -> (String, Value) {
    match error {
        RuntimeError::Khive(k) => {
            let error_payload = serde_json::to_value(&k)
                .unwrap_or_else(|_| json!({"kind": "internal", "message": k.to_string()}));
            (tool.to_string(), error_payload)
        }
        other => (tool.to_string(), json!(other.to_string())),
    }
}

/// Returns `true` when a raw handler `result` value's container nesting is
/// within [`khive_request::NESTING_DEPTH_LIMIT`]. Callers MUST call this on
/// the raw value straight out of coordinator/registry dispatch, before any
/// recursive `Value` operation (clone, serialize, presentation transform)
/// touches it — see `crates/khive-mcp/docs/design.md` (Result depth guard).
fn result_within_depth_limit(result: &Value) -> bool {
    khive_request::value_nesting_within_limit(result, khive_request::NESTING_DEPTH_LIMIT)
}

/// Per-op error payload for a handler result that failed
/// [`result_within_depth_limit`]. Carries only the configured depth limit,
/// never the oversized value itself.
fn depth_error_payload(context: &str) -> Value {
    json!({
        "kind": "result_too_deep",
        "message": format!(
            "op result nesting depth exceeds max {}{context}",
            khive_request::NESTING_DEPTH_LIMIT
        ),
    })
}

/// Build the `{ok: true, tool, result}` envelope for a successful op,
/// without re-serializing an already-owned `Value` through `json!` (which
/// would call `serde_json::to_value` and recurse over the whole tree
/// again). The depth check must already have passed before this is called.
fn ok_envelope(tool: String, result: Value) -> Value {
    let mut map = serde_json::Map::with_capacity(3);
    map.insert("ok".to_string(), Value::Bool(true));
    map.insert("tool".to_string(), Value::String(tool));
    map.insert("result".to_string(), result);
    Value::Object(map)
}

/// Discard a rejected over-limit `Value` without native recursion.
///
/// `Value`'s derived `Drop` walks nested containers the same way `Clone`
/// and `Serialize` do, so simply letting a pathologically deep `result`
/// fall out of scope after the depth guard rejects it would trade a stack
/// overflow during serialization for one during drop. Draining containers
/// onto an explicit heap-allocated worklist keeps each removal O(1) on the
/// call stack regardless of nesting depth.
fn drop_value_iteratively(value: Value) {
    let mut stack = vec![value];
    while let Some(v) = stack.pop() {
        match v {
            Value::Array(items) => stack.extend(items),
            Value::Object(map) => stack.extend(map.into_values()),
            _ => {}
        }
    }
}

/// Builds a `substitution_error` payload for a `$prev` argument that failed
/// to resolve (`resolve_all` returned `None`). Uses [`ArgValue::find_prev_failure`]
/// to identify exactly which lookup failed and why — a missing field/index, a
/// path segment applied to the wrong JSON type, or unsupported bracket syntax
/// — each worded differently so the caller isn't left with one generic
/// "not found" for three different mistakes. Falls back to a generic message
/// only if `find_prev_failure` cannot explain a miss `resolve_all` reported
/// (defensive; the two are expected to always agree).
fn substitution_error_payload(name: &str, arg_val: &ArgValue, prev: &Value) -> Value {
    let Some(failure) = arg_val.find_prev_failure(prev) else {
        let fields_hint = if let Value::Object(map) = prev {
            let mut fields: Vec<&str> = map.keys().map(String::as_str).collect();
            fields.sort_unstable();
            format!(" Available top-level fields: [{}]", fields.join(", "))
        } else {
            String::new()
        };
        return json!({
            "kind": "substitution_error",
            "reason": "path_not_found",
            "message": format!(
                "argument {name:?}: one or more $prev paths not found in prior result.{fields_hint}"
            ),
        });
    };
    let reason = match &failure {
        PrevFailure::NotFound { .. } => "path_not_found",
        PrevFailure::WrongType { .. } => "path_wrong_type",
        PrevFailure::Unsupported { .. } => "path_unsupported",
    };
    json!({
        "kind": "substitution_error",
        "reason": reason,
        "message": format!(
            "argument {name:?}: {failure}. $prev resolves only against the immediately \
             preceding op's result — a non-adjacent dependency cannot be expressed inside \
             one chain; split into separate calls and carry the value across yourself."
        ),
    })
}

/// ADR-103 Amendment 2: stamp the per-op envelope entry with the dispatch's
/// frozen usage snapshot. All-or-nothing: an empty snapshot (nothing measured
/// counted, but the context WAS armed) still stamps `{}`; the key is absent
/// only when no context existed. Best-effort — never alters ok/error status.
fn stamp_usage(entry: &mut Value, ctx: &khive_runtime::usage::UsageContext) {
    if let Value::Object(map) = entry {
        map.insert("usage".to_string(), ctx.frozen_or_snapshot());
    }
}

/// Add host-owned ticker liveness to the schedule pack's canonical agenda
/// payload. The pack owns scheduled intent; the MCP host owns the daemon loop,
/// so this decoration stays at their dispatch boundary instead of persisting a
/// process heartbeat in schedule data.
fn decorate_schedule_agenda_with_ticker_health(
    tool: &str,
    is_help: bool,
    mut result: Value,
    last_tick_micros: &AtomicI64,
) -> Value {
    if tool != "schedule.agenda" || is_help {
        return result;
    }
    let last_tick = last_tick_micros.load(Ordering::Acquire);
    let last_tick_at = (last_tick > 0).then(|| khive_runtime::micros_to_iso(last_tick));
    if let Some(result) = result.as_object_mut() {
        result.insert(
            "ticker".to_string(),
            json!({ "last_tick_at": last_tick_at }),
        );
    }
    result
}

/// Chain-mode (`dispatch_op`) success path: check the raw handler `result`
/// against the depth guard before it is ever cloned into `$prev` context or
/// wrapped in the response envelope. On violation returns a `result_too_deep`
/// error that does not embed the oversized value, and discards the rejected
/// value iteratively so its own drop can't overflow the stack either.
fn chain_ok_envelope_or_depth_error(tool: String, result: Value) -> Result<Value, (String, Value)> {
    if !result_within_depth_limit(&result) {
        drop_value_iteratively(result);
        return Err((
            tool,
            depth_error_payload("; cannot be used as $prev chain context"),
        ));
    }
    Ok(ok_envelope(tool, result))
}

/// Parallel/single-mode success path: check the raw handler `result` against
/// the depth guard *before* it is handed to `present` (which recurses
/// natively over `Value` in agent mode) or wrapped in the response envelope.
/// On violation returns a `result_too_deep` per-op error entry that does not
/// embed the oversized value, and discards the rejected value iteratively
/// (see [`drop_value_iteratively`]).
fn present_ok_envelope_or_depth_error(
    tool: String,
    result: Value,
    mode: PresentationMode,
    now_unix: i64,
) -> Value {
    if !result_within_depth_limit(&result) {
        drop_value_iteratively(result);
        return json!({ "ok": false, "tool": tool, "error": depth_error_payload("") });
    }
    let presented = present(result, mode, now_unix);
    ok_envelope(tool, presented)
}

/// Returns `true` if a dispatched op's canonical `result` field nests
/// container values (`[`/`{`) deeper than [`khive_request::NESTING_DEPTH_LIMIT`].
///
/// This is a second, defense-in-depth check retained on the chain-mode
/// aggregation path in [`KhiveMcpServer::run_parsed`]: by the time it runs,
/// [`chain_ok_envelope_or_depth_error`] has already screened the same
/// `result` field inside `dispatch_op`, so this should never trip in
/// practice. It stays cheap (iterative, not recursive) so keeping it costs
/// nothing and catches a future refactor that bypasses the earlier guard.
fn result_exceeds_depth_limit(result_obj: &Value) -> bool {
    result_obj
        .get("result")
        .is_some_and(|v| !result_within_depth_limit(v))
}

/// Chain-mode aggregation-loop seam in [`KhiveMcpServer::run_parsed`]:
/// defense-in-depth depth check on a dispatched op's full `result_obj`
/// envelope (should never trip — `dispatch_op` already screened `result`).
/// Returns the unchanged envelope on success, or an already-built error
/// entry on rejection. See `crates/khive-mcp/docs/design.md` (Result depth
/// guard) for why the rejected envelope is drained iteratively.
fn chain_aggregation_depth_reject(result_obj: Value) -> Result<Value, Value> {
    if result_exceeds_depth_limit(&result_obj) {
        let tool_name = result_obj
            .get("tool")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let error_entry = json!({
            "ok": false,
            "tool": tool_name,
            "error": {
                "kind": "result_too_deep",
                "message": format!(
                    "op result nesting depth exceeds max {}; \
                     cannot be used as $prev chain context",
                    khive_request::NESTING_DEPTH_LIMIT
                ),
            },
        });
        drop_value_iteratively(result_obj);
        return Err(error_entry);
    }
    Ok(result_obj)
}

/// Apply the presentation transform to the `result` field of a successful
/// per-op envelope, leaving error envelopes unchanged.
///
/// Error envelopes are never transformed — only successful `result` fields.
fn apply_presentation_to_result(
    mut result_obj: Value,
    mode: PresentationMode,
    now_unix: i64,
) -> Value {
    if result_obj.get("ok").and_then(Value::as_bool) == Some(true) {
        if let Some(result_field) = result_obj.get("result").cloned() {
            let presented = present(result_field, mode, now_unix);
            if let Some(obj) = result_obj.as_object_mut() {
                obj.insert("result".to_string(), presented);
            }
        }
    }
    result_obj
}

// ── single MCP tool ─────────────────────────────────────────────────────────

#[tool_router]
impl KhiveMcpServer {
    #[tool(description = r#"Run one or more khive verbs in a single MCP call.

ops syntax:

  Single op   : verb(name=value, name=value)
  Batch       : [verb(...), verb(...)]                 — parallel, max 100
  Chain       : verb1(...) | verb2(id=$prev.id)        — sequential, $prev
  JSON form   : [{"tool":"verb","args":{...}}, ...]    — INDEPENDENT ops only

Argument values are JSON literals: strings (double-quoted), numbers, booleans,
null, arrays, objects. Strings may contain commas / parens; escape with \".

Chain-only: $prev resolves to the prior op's result. Path extraction syntax:
  $prev               — full result
  $prev.field         — nested object field
  $prev.items[0].id   — array index
  $prev[2]            — top-level array index
Quoted strings that contain $prev are promoted to substitutions (e.g. id="$prev.id"
is the same as id=$prev.id). To pass a literal "$prev", escape with backslash:
\"\\$prev\". JSON form is for independent ops only — any $prev string in JSON
form is rejected.

Response shape:

  {
    "results": [ {"ok": true, "tool": "verb", "result": {...}}, ... ],
    "summary": { "total": N, "succeeded": N, "failed": N, "aborted": N },
    "status": "success" | "partial"
  }

Parallel: a failed op does NOT abort siblings. Chain: failure aborts remaining
ops (reported as {"ok": false, "aborted": true}). Committed ops are not rolled back.
`status` is "partial" whenever summary.failed or summary.aborted is non-zero — check
it (or summary) rather than relying on the absence of a top-level error.

Verb discovery: install the `kg` / `gtd` plugins for usage skills. The verbs
currently registered on this server (pack-derived) are listed below. Argument
schemas live in each pack's docs and SKILL.md files.

Tip: for one-shot calls, the single-op form is the densest. Use batch when
several independent ops can run together; use chain when each op needs the prior
result (e.g. create then link with the new entity's id)."#)]
    async fn request(&self, Parameters(p): Parameters<RequestParams>) -> Result<String, McpError> {
        // Forward to the warm daemon when reachable, auto-spawning it
        // on first use. An ordinary no-socket condition, a namespace
        // mismatch, or KHIVE_NO_DAEMON falls through to local dispatch.
        // A confirmed respawn failure (spawn error, or the child exits
        // before binding the socket) instead returns a caller-visible
        // `respawn_failed` error without local dispatch, per ADR-049
        // Amendment 2.
        //
        // MCP-AUD-002: the daemon wire frame has no `save_to` field, so
        // daemon-forwarded requests silently drop the sink and return the
        // inline result instead. Bypass daemon forwarding whenever `save_to`
        // is set so the local path's manifest/file behavior always applies,
        // matching the existing `kkernel exec --save-file` precedent.
        #[cfg(unix)]
        if p.save_to.is_none() {
            let frame = self.wire_daemon_frame(&p);
            if let Some(res) = crate::daemon::forward_or_spawn(&frame).await {
                return match res {
                    Ok(s) => Ok(s),
                    // #947/#898: a strict-mode pre-dispatch rejection is
                    // tagged with
                    // `daemon::STRICT_FALLBACK_MARKER` so it can be reshaped
                    // into the normal per-op envelope instead of surfacing as
                    // an RPC-level error. Every other daemon-forward error
                    // (non-strict respawn failure, protocol mismatch,
                    // oversized frame, ambiguous post-write outcome) is
                    // untagged and passes through unchanged.
                    Err(e) => match strict_fallback_reason(&e) {
                        Some(reason) => strict_fallback_envelope_response(&p, reason),
                        None => Err(e),
                    },
                };
            }
        }
        self.dispatch_request_wire(p).await
    }
}

/// Response-envelope `status` for a batch of `failed`/`aborted` counts
/// (#1220): `"partial"` when either is non-zero, `"success"` otherwise. A
/// caller that only checks for the absence of a top-level RPC error has
/// nothing else to branch on for a batch where some ops failed or were
/// skipped after a chain abort.
fn batch_status(failed: usize, aborted: usize) -> &'static str {
    if failed == 0 && aborted == 0 {
        "success"
    } else {
        "partial"
    }
}

fn batch_budget_error(tool: &str, response_budget: usize) -> Value {
    json!({
        "ok": false,
        "tool": tool,
        "error": format!(
            "batch response budget of {response_budget} serialized bytes exceeded"
        ),
    })
}

async fn execute_bounded_batch<I, F>(tasks: I, response_budget: usize) -> Vec<Value>
where
    I: IntoIterator<Item = BatchTask<F>>,
    F: Future<Output = Value>,
{
    let mut queued: std::collections::VecDeque<_> = tasks.into_iter().collect();
    let total = queued.len();
    let mut in_flight = FuturesUnordered::new();
    let start = |task: BatchTask<F>| async move {
        let entry = task.future.await;
        (task.index, task.tool, entry)
    };
    for _ in 0..MAX_BATCH_CONCURRENCY {
        if let Some(task) = queued.pop_front() {
            in_flight.push(start(task));
        }
    }

    let mut results: Vec<Option<Value>> = (0..total).map(|_| None).collect();
    let mut accumulated_bytes = 0usize;
    let mut budget_breached = false;

    while let Some((index, _tool, entry)) = in_flight.next().await {
        if budget_breached {
            results[index] = Some(entry);
            continue;
        }
        let serialized_bytes = serde_json::to_vec(&entry)
            .expect("serde_json::Value is always serializable")
            .len();
        if serialized_bytes > response_budget.saturating_sub(accumulated_bytes) {
            results[index] = Some(entry);
            budget_breached = true;
            continue;
        }

        accumulated_bytes += serialized_bytes;
        results[index] = Some(entry);
        if let Some(task) = queued.pop_front() {
            in_flight.push(start(task));
        }
    }

    for task in queued {
        results[task.index] = Some(batch_budget_error(&task.tool, response_budget));
    }

    results
        .into_iter()
        .map(|entry| entry.expect("every started or queued batch task has a result"))
        .collect()
}

fn parallel_batch_envelope(results: Vec<Value>) -> Value {
    let total = results.len();
    let succeeded = results
        .iter()
        .filter(|result| result.get("ok").and_then(Value::as_bool) == Some(true))
        .count();
    let failed = total - succeeded;
    json!({
        "results": results,
        "summary": { "total": total, "succeeded": succeeded, "failed": failed, "aborted": 0 },
        "status": batch_status(failed, 0),
    })
}

/// Extract the fallback-reason string from a strict-mode rejection's
/// [`McpError`] (#947), or `None` if `e` is not tagged with
/// [`crate::daemon::STRICT_FALLBACK_MARKER`] — i.e. some other daemon-forward
/// error that must stay an RPC-level error.
#[cfg(unix)]
fn strict_fallback_reason(e: &McpError) -> Option<String> {
    let data = e.data.as_ref()?;
    if data.get(crate::daemon::STRICT_FALLBACK_MARKER)?.as_bool() != Some(true) {
        return None;
    }
    data.get("reason")
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// Build the wire-contract failed-op envelope for a strict-mode daemon
/// fallback rejection (#947 Medium finding).
///
/// The request was never attempted — locally or on the daemon — but the wire
/// response must still be a normal per-op envelope
/// (`{"results": [...], "summary": {...}}`) reporting the fallback reason as
/// each op's `error`, not an RPC-level `McpError`. Chain mode aborts after the
/// first op, matching `run_parsed`'s `Chain` arm and the wire contract's
/// documented abort-on-failure behavior for `|`-chained ops.
#[cfg(unix)]
fn strict_fallback_envelope_response(
    p: &RequestParams,
    reason: String,
) -> Result<String, McpError> {
    let parsed = parse_request(&p.ops).map_err(dsl_err_to_mcp)?;
    let total = parsed.ops.len();
    let error_msg = format!(
        "daemon fallback rejected under KHIVE_DAEMON_STRICT=1: reason={reason}; \
         refusing to complete the request via local dispatch; \
         rebuild with `make local` and retry"
    );

    let results: Vec<Value> = match parsed.mode {
        ExecutionMode::Chain => parsed
            .ops
            .iter()
            .enumerate()
            .map(|(i, op)| {
                if i == 0 {
                    json!({ "ok": false, "tool": op.tool, "error": error_msg })
                } else {
                    json!({ "ok": false, "tool": op.tool, "aborted": true })
                }
            })
            .collect(),
        ExecutionMode::Single | ExecutionMode::Parallel => parsed
            .ops
            .iter()
            .map(|op| json!({ "ok": false, "tool": op.tool, "error": error_msg }))
            .collect(),
    };

    let aborted = if parsed.mode == ExecutionMode::Chain {
        total.saturating_sub(1)
    } else {
        0
    };
    let failed = total - aborted;
    Ok(serde_json::to_string(&json!({
        "results": results,
        "summary": { "total": total, "succeeded": 0, "failed": failed, "aborted": aborted },
        "status": batch_status(failed, aborted),
    }))
    .expect("envelope of string/bool JSON values always serializes"))
}

impl KhiveMcpServer {
    /// Build the daemon forward-frame for an agent-facing `request` tool call.
    ///
    /// `from_wire` is unconditionally `true`: this is the agent wire surface, so
    /// `Visibility::Subhandler` verbs must be rejected whether the request runs
    /// on the warm daemon or via the local fallback. Keeping the bit in one
    /// named, unit-tested place stops the daemon-forward path from silently
    /// diverging from `dispatch_request_wire`.
    #[cfg(unix)]
    pub(crate) fn wire_daemon_frame(&self, p: &RequestParams) -> khive_runtime::DaemonRequestFrame {
        khive_runtime::DaemonRequestFrame {
            ops: p.ops.clone(),
            presentation: p.presentation.clone(),
            presentation_per_op: p.presentation_per_op.clone(),
            namespace: self.default_namespace.clone(),
            // ADR-096 Fork 1: carry this server's OWN resolved actor/visibility
            // identity on the frame so a warm daemon with a *different* baked
            // identity serves the request under this caller's identity instead
            // of rejecting it or silently stamping writes under its own actor.
            actor_id: self.actor_id().map(str::to_string),
            process_ref: khive_runtime::process_ref_from_env(),
            visible_namespaces: self
                .visible_namespaces()
                .iter()
                .map(|ns| ns.as_str().to_string())
                .collect(),
            config_id: self.config_id.clone(),
            protocol_version: khive_runtime::daemon::PROTOCOL_VERSION,
            probe_only: false,
            metrics_only: false,
            format: p.format.clone(),
            format_per_op: p.format_per_op.clone(),
            from_wire: true,
            // khive#948: forwarded unchanged from the tool caller's params.
            // `None` when the caller supplied no id (pre-#948 client).
            request_id: p.request_id,
        }
    }

    /// Parse and dispatch a request against this server's own registry.
    ///
    /// This is the canonical **operator** dispatch path: subhandler verbs are
    /// allowed. `kkernel exec`, in-process callers, and tests use this. The
    /// agent-facing MCP wire surface goes through `dispatch_request_wire`
    /// (or sets `from_wire` on the daemon frame), which enforces verb visibility.
    ///
    /// Pure local dispatch: no [`khive_runtime::RequestIdentity`] override is
    /// applied by this caller (ADR-096 Fork 1) — this server's own
    /// construction-baked namespace/actor/visibility is used, unchanged from
    /// before per-request identity existed. `dispatch_request_inner` (khive#948)
    /// may still synthesize an identity carrying those same baked scalars if
    /// `p.request_id` is set, purely so the audit row is correlatable.
    pub async fn dispatch_request_local(&self, p: RequestParams) -> Result<String, McpError> {
        self.dispatch_request_inner(p, false, None, DispatchOrigin::Local)
            .await
    }

    /// Replay one stored public-surface request under a host-verified actor.
    ///
    /// An attributed actor must come from an out-of-band provenance check,
    /// never from a field inside the stored request. `None` is reserved for a
    /// provenance-verified anonymous/local creator, preserving that actor kind.
    /// Replay deliberately sets `from_wire=true`: scheduling delays a public
    /// request; it does not upgrade that request into the operator-only local
    /// surface where [`khive_runtime::Visibility::Subhandler`] verbs are callable.
    pub(crate) async fn dispatch_request_replay_as(
        &self,
        p: RequestParams,
        namespace: &str,
        verified_actor: Option<khive_runtime::VerifiedActor>,
    ) -> Result<String, McpError> {
        let identity = khive_runtime::RequestIdentity {
            namespace: namespace.to_string(),
            // `None` is the provenance-verified anonymous/local identity;
            // spelling that identity as `Some("local")` would incorrectly
            // reconstruct it as the distinct authenticated `actor:local`.
            actor_id: verified_actor.map(|actor| actor.as_str().to_string()),
            process_ref: khive_runtime::process_ref_from_env(),
            // A scheduled action is scoped exactly to its event namespace;
            // it never inherits the daemon's broader read visibility.
            visible_namespaces: Vec::new(),
            request_id: None,
        };
        self.dispatch_request_inner(p, true, Some(identity), DispatchOrigin::Local)
            .await
    }

    /// Wire-surface dispatch: same as [`Self::dispatch_request_local`] but
    /// enforces verb visibility (`Visibility::Subhandler` verbs are rejected).
    /// Used by the stdio `request` tool's local-fallback path.
    pub(crate) async fn dispatch_request_wire(&self, p: RequestParams) -> Result<String, McpError> {
        self.dispatch_request_inner(p, true, None, DispatchOrigin::Local)
            .await
    }

    /// Shared body for both dispatch surfaces. `from_wire` decides whether the
    /// subhandler-visibility gate fires (see [`run_parsed`](Self::run_parsed)).
    ///
    /// `identity` is the per-request identity context threaded from a daemon
    /// frame (ADR-096 Fork 1, see `crate::daemon`'s `DaemonDispatch` impl).
    /// `None` for every local (non-daemon-served) call — this server's own
    /// baked identity applies, exactly as before this parameter existed.
    /// `origin` independently controls daemon-frame response fitting; wire
    /// visibility does not imply that the response travels through the daemon.
    ///
    /// khive#948: when `identity` is `None` (every local-dispatch call —
    /// `KHIVE_NO_DAEMON`/soft daemon-fallback and the `save_to` bypass both
    /// route here via `dispatch_request_wire`) and the caller supplied a
    /// `request_id`, a `RequestIdentity` is synthesized so the audit row
    /// stamped by this dispatch is still correlatable. The synthesized
    /// identity mirrors this server's own baked `default_namespace` /
    /// `actor_id` / `visible_namespaces` exactly — it changes no dispatch
    /// semantics, only adds the correlation id — so a request with no
    /// `request_id` still dispatches through the untouched `identity = None`
    /// path.
    pub(crate) async fn dispatch_request_inner(
        &self,
        p: RequestParams,
        from_wire: bool,
        identity: Option<khive_runtime::RequestIdentity>,
        origin: DispatchOrigin,
    ) -> Result<String, McpError> {
        let save_to = p.save_to.clone();
        let identity = identity.or_else(|| {
            p.request_id
                .map(|request_id| khive_runtime::RequestIdentity {
                    namespace: self.default_namespace.clone(),
                    actor_id: self.actor_id().map(str::to_string),
                    process_ref: khive_runtime::process_ref_from_env(),
                    visible_namespaces: self
                        .visible_namespaces()
                        .iter()
                        .map(|ns| ns.as_str().to_string())
                        .collect(),
                    request_id: Some(request_id),
                })
        });
        let parsed = parse_request(&p.ops).map_err(dsl_err_to_mcp)?;

        // Parse presentation strings → PresentationMode.
        let presentation = parse_presentation_mode(p.presentation.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let presentation_per_op: Option<Vec<Option<PresentationMode>>> =
            if let Some(per_op_strs) = p.presentation_per_op {
                let mut modes = Vec::with_capacity(per_op_strs.len());
                for s in per_op_strs {
                    let mode = match s.as_deref() {
                        None => None,
                        Some(v) => Some(
                            parse_presentation_mode(Some(v))
                                .map_err(|e| McpError::invalid_params(e, None))?,
                        ),
                    };
                    modes.push(mode);
                }
                Some(modes)
            } else {
                None
            };

        // Resolve the output format for this request (ADR-078 §2 precedence):
        // per-request `format` field → server default (already resolved from
        // env + toml + builtin by `serve.rs`).
        let batch_format = parse_output_format(p.format.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .unwrap_or(self.default_output_format);

        // Per-op format overrides (ADR-078 §8.4).
        let format_per_op: Option<Vec<Option<OutputFormat>>> =
            if let Some(per_op_strs) = p.format_per_op {
                let mut fmts = Vec::with_capacity(per_op_strs.len());
                for s in per_op_strs {
                    let fmt = match s.as_deref() {
                        None => None,
                        Some(v) => Some(
                            parse_output_format(Some(v))
                                .map_err(|e| McpError::invalid_params(e, None))?
                                .unwrap_or(batch_format),
                        ),
                    };
                    fmts.push(fmt);
                }
                Some(fmts)
            } else {
                None
            };

        let result = self
            .run_parsed(
                parsed.ops,
                parsed.mode,
                presentation,
                presentation_per_op.clone(),
                RunParsedContext {
                    enforce_response_budget: save_to.is_none(),
                    from_wire,
                    identity: identity.as_ref(),
                },
            )
            .await;

        if let Some(path_str) = save_to {
            let path = std::path::Path::new(&path_str);
            // `from_wire` gates the destination policy: the agent-facing MCP
            // `request` tool (`from_wire = true`) restricts `save_to` to the
            // allowed export root; the trusted operator CLI path
            // (`kkernel exec --save-file`, `from_wire = false`) is unrestricted,
            // matching its documented "write anywhere" behavior.
            let manifest = crate::save_sink::write_and_manifest(&result, path, from_wire)
                .map_err(|e| McpError::internal_error(format!("save_to: {e}"), None))?;
            // Manifests are always compact JSON regardless of format (lossless metadata).
            return serde_json::to_string(&manifest)
                .map_err(|e| McpError::internal_error(format!("serialize manifest: {e}"), None));
        }

        // Apply per-op format rendering (ADR-078 §8.4 and §9).
        Ok(render_result(
            result,
            batch_format,
            &format_per_op,
            presentation,
            &presentation_per_op,
            &self.registry,
            (origin == DispatchOrigin::Daemon).then_some(self.config_id.as_str()),
        ))
    }
}

fn dsl_err_to_mcp(e: DslError) -> McpError {
    McpError::invalid_params(e.to_string(), None)
}

/// Parse an optional presentation mode string from the request envelope.
///
/// `None` → default (`Agent`). Known values: `"agent"`, `"verbose"`, `"human"`.
fn parse_presentation_mode(s: Option<&str>) -> Result<PresentationMode, String> {
    match s {
        None | Some("agent") => Ok(PresentationMode::Agent),
        Some("verbose") => Ok(PresentationMode::Verbose),
        Some("human") => Ok(PresentationMode::Human),
        Some(other) => Err(format!(
            "unknown presentation mode {other:?}; valid values: \"agent\", \"verbose\", \"human\""
        )),
    }
}

/// Parse an optional output format string from the request envelope (ADR-078).
///
/// `None` → `None` (caller uses server default). Known values: `"json"`, `"auto"`, `"table"`.
fn parse_output_format(s: Option<&str>) -> Result<Option<OutputFormat>, String> {
    match s {
        None => Ok(None),
        Some("json") => Ok(Some(OutputFormat::Json)),
        Some("auto") => Ok(Some(OutputFormat::Auto)),
        Some("table") => Ok(Some(OutputFormat::Table)),
        Some(other) => Err(format!(
            "unknown output format {other:?}; valid values: \"json\", \"auto\", \"table\""
        )),
    }
}

/// Render the `run_parsed` result envelope using per-op format dispatch (ADR-078 §8.4).
///
/// For each op entry in `results`:
/// - If `ok=false` (error entry): always compact JSON, never reformatted (§8.2).
/// - If `ok=true`: resolve per-op format (per_op_formats[i] → batch_format) and
///   per-op presentation (presentation_per_op[i] → batch presentation, then the
///   verb's AlwaysVerbose policy forces Verbose), apply `render_format` to the
///   `result` payload with the effective presentation so that both
///   `presentation_per_op=["verbose"]` and AlwaysVerbose verbs (get/link/query/
///   traverse/neighbors/brain.feedback) correctly skip the redundancy-drop
///   pre-pass (ADR-078 §7 + §8.4; mirrors `run_parsed`).
///
/// The outer envelope (`{results:[...], summary:{...}}`) is always compact JSON (§8.4).
/// Daemon-served responses are rendered before fitting. If the rendered envelope
/// exceeds the frame allowance, entries fall back to compact JSON before payload
/// details are omitted. Local dispatch has no daemon-frame allowance and returns
/// the requested representation without fitting. Every daemon fit decision
/// serializes the actual response-frame shape so JSON string escaping is included.
fn render_result(
    value: serde_json::Value,
    batch_format: OutputFormat,
    format_per_op: &Option<Vec<Option<OutputFormat>>>,
    presentation: PresentationMode,
    presentation_per_op: &Option<Vec<Option<PresentationMode>>>,
    registry: &VerbRegistry,
    daemon_frame_config_id: Option<&str>,
) -> String {
    // Try to detect the compound batch envelope shape: { results: [...], summary: {...} }
    if let serde_json::Value::Object(ref map) = value {
        if let Some(serde_json::Value::Array(results)) = map.get("results") {
            let out_results = results
                .iter()
                .enumerate()
                .map(|(index, entry)| {
                    render_batch_entry(
                        index,
                        entry,
                        batch_format,
                        format_per_op,
                        presentation,
                        presentation_per_op,
                        registry,
                    )
                })
                .collect();
            let out_map = match daemon_frame_config_id {
                Some(config_id) => {
                    fit_rendered_batch_envelope(map, results, out_results, config_id)
                }
                None => {
                    let mut out_map = map.clone();
                    out_map.insert("results".to_string(), Value::Array(out_results));
                    out_map
                }
            };
            return serialize_response_value(&serde_json::Value::Object(out_map));
        }
    }

    let rendered = render_format(value.clone(), batch_format, presentation);
    let Some(config_id) = daemon_frame_config_id else {
        return rendered;
    };
    if rendered_response_fits_daemon_frame(&rendered, config_id) {
        return rendered;
    }
    let compact = serialize_response_value(&value);
    if rendered_response_fits_daemon_frame(&compact, config_id) {
        return compact;
    }
    serde_json::to_string(&json!({
        "ok": false,
        "error": "response payload omitted because it exceeds the daemon frame budget",
    }))
    .expect("static frame-budget error is serializable")
}

fn render_batch_entry(
    index: usize,
    entry: &Value,
    batch_format: OutputFormat,
    format_per_op: &Option<Vec<Option<OutputFormat>>>,
    presentation: PresentationMode,
    presentation_per_op: &Option<Vec<Option<PresentationMode>>>,
    registry: &VerbRegistry,
) -> Value {
    let per_op_format = format_per_op
        .as_ref()
        .and_then(|formats| formats.get(index))
        .and_then(|format| *format)
        .unwrap_or(batch_format);
    let is_ok = entry.get("ok").and_then(Value::as_bool).unwrap_or(false);
    if !is_ok || per_op_format == OutputFormat::Json {
        return entry.clone();
    }

    let base_presentation = presentation_per_op
        .as_ref()
        .and_then(|modes| modes.get(index))
        .and_then(|mode| *mode)
        .unwrap_or(presentation);
    let effective_presentation = match entry.get("tool").and_then(Value::as_str) {
        Some(tool)
            if registry.presentation_policy_for(tool) == VerbPresentationPolicy::AlwaysVerbose =>
        {
            PresentationMode::Verbose
        }
        _ => base_presentation,
    };
    let Some(result) = entry.get("result") else {
        return entry.clone();
    };
    let mut rendered_entry = entry.clone();
    if let Value::Object(ref mut fields) = rendered_entry {
        fields.insert(
            "result".to_string(),
            Value::String(render_format(
                result.clone(),
                per_op_format,
                effective_presentation,
            )),
        );
    }
    rendered_entry
}

fn fit_rendered_batch_envelope(
    map: &serde_json::Map<String, Value>,
    compact_results: &[Value],
    mut out_results: Vec<Value>,
    served_config_id: &str,
) -> serde_json::Map<String, Value> {
    let mut out_map = map.clone();
    out_map.insert(
        "results".to_string(),
        serde_json::Value::Array(out_results.clone()),
    );
    if response_value_fits_daemon_frame(
        &serde_json::Value::Object(out_map.clone()),
        served_config_id,
    ) {
        return out_map;
    }

    let rendered_frame_bytes = response_value_daemon_frame_len(
        &serde_json::Value::Object(out_map.clone()),
        served_config_id,
    );
    let mut compact_fallbacks: Vec<(usize, usize)> = compact_results
        .iter()
        .zip(&out_results)
        .enumerate()
        .filter_map(|(index, (compact, rendered))| {
            if compact == rendered {
                return None;
            }
            let mut candidate_results = out_results.clone();
            candidate_results[index] = compact.clone();
            let mut candidate_map = out_map.clone();
            candidate_map.insert("results".to_string(), Value::Array(candidate_results));
            let compact_frame_bytes =
                response_value_daemon_frame_len(&Value::Object(candidate_map), served_config_id);
            (compact_frame_bytes < rendered_frame_bytes)
                .then_some((index, rendered_frame_bytes - compact_frame_bytes))
        })
        .collect();
    compact_fallbacks.sort_unstable_by_key(|&(_, saved_bytes)| std::cmp::Reverse(saved_bytes));
    for (index, _) in compact_fallbacks {
        out_results[index] = compact_results[index].clone();
        out_map.insert("results".to_string(), Value::Array(out_results.clone()));
        if response_value_fits_daemon_frame(&Value::Object(out_map.clone()), served_config_id) {
            return out_map;
        }
    }

    let mut by_size: Vec<(usize, usize)> = out_results
        .iter()
        .enumerate()
        .map(|(index, entry)| (index, serialized_response_len(entry)))
        .collect();
    by_size.sort_unstable_by_key(|&(_, bytes)| std::cmp::Reverse(bytes));
    for (index, _) in by_size {
        out_results[index] = frame_budget_omission(&compact_results[index]);
        out_map.insert(
            "results".to_string(),
            serde_json::Value::Array(out_results.clone()),
        );
        if response_value_fits_daemon_frame(
            &serde_json::Value::Object(out_map.clone()),
            served_config_id,
        ) {
            break;
        }
    }
    out_map
}

fn frame_budget_omission(entry: &Value) -> Value {
    let ok = entry.get("ok").and_then(Value::as_bool).unwrap_or(false);
    let mut omitted = serde_json::Map::new();
    for key in ["ok", "tool", "usage", "aborted"] {
        if let Some(value) = entry.get(key) {
            omitted.insert(key.to_string(), value.clone());
        }
    }
    if ok {
        omitted.insert(
            "result_omitted".to_string(),
            json!("operation succeeded; result omitted because the response frame budget was exceeded"),
        );
    } else {
        omitted.insert(
            "error".to_string(),
            json!("operation failed; error details omitted because the response frame budget was exceeded"),
        );
    }
    Value::Object(omitted)
}

fn serialized_response_len(value: &Value) -> usize {
    serde_json::to_vec(value)
        .expect("serde_json::Value is always serializable")
        .len()
}

fn serialize_response_value(value: &Value) -> String {
    serde_json::to_string(value).expect("serde_json::Value is always serializable")
}

fn response_value_fits_daemon_frame(value: &Value, served_config_id: &str) -> bool {
    response_value_daemon_frame_len(value, served_config_id)
        <= khive_runtime::daemon::MAX_FRAME_BYTES
}

fn response_value_daemon_frame_len(value: &Value, served_config_id: &str) -> usize {
    rendered_response_daemon_frame_len(&serialize_response_value(value), served_config_id)
}

fn rendered_response_fits_daemon_frame(rendered: &str, served_config_id: &str) -> bool {
    rendered_response_daemon_frame_len(rendered, served_config_id)
        <= khive_runtime::daemon::MAX_FRAME_BYTES
}

fn rendered_response_daemon_frame_len(rendered: &str, served_config_id: &str) -> usize {
    let frame = khive_runtime::DaemonResponseFrame {
        ok: true,
        result: Some(rendered.to_string()),
        error: None,
        namespace_mismatch: false,
        config_mismatch: false,
        served_config_id: Some(served_config_id.to_string()),
        version_mismatch: false,
        daemon_protocol_version: khive_runtime::PROTOCOL_VERSION,
        metrics: None,
        request_id: Some(u64::MAX),
    };
    serde_json::to_vec(&frame)
        .expect("daemon response frame is always serializable")
        .len()
}

/// Build the `initialize` instructions string from the verb catalog and the
/// loaded builtin pack names. Extracted from [`ServerHandler::get_info`] so
/// the docs-pointer section (#594) is unit-testable without standing up a
/// full server.
fn build_instructions(catalog: &str, builtins: &str) -> String {
    format!(
        "khive — request-only MCP surface. One tool, `request`, \
         dispatches verbs through the loaded pack registry. Configure packs via \
         KHIVE_PACKS or --pack (built-ins: {builtins}). Verbs registered on this \
         server:\n{catalog}\nFor detailed usage of each verb, see the corresponding \
         plugin's SKILL.md files.\n\
         Docs: https://ohdearquant.github.io/khive/ (hosted) or docs/*.md in the repo \
         checkout. Treat the live verb catalog above and help=true as authoritative over \
         cached/training knowledge. Config/backend issues: docs/configuration.md. Usage \
         patterns: docs/guide/tips-and-tricks.md."
    )
}

#[tool_handler]
impl ServerHandler for KhiveMcpServer {
    fn get_info(&self) -> ServerInfo {
        let catalog = self.verb_catalog();
        let builtins = builtin_pack_names().join(", ");
        let instructions = build_instructions(&catalog, &builtins);
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new(
                env!("CARGO_PKG_NAME"),
                env!("CARGO_PKG_VERSION"),
            ))
            .with_instructions(instructions)
    }

    /// Override the macro-generated `list_tools` so the `request` tool's
    /// description carries the dynamic verb catalog built from the loaded
    /// pack registry. Many MCP clients only surface `tools/list` descriptions
    /// (not server instructions) — discovery must work via tool listing.
    async fn list_tools(
        &self,
        _request: Option<rmcp::model::PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::RoleServer>,
    ) -> Result<rmcp::model::ListToolsResult, McpError> {
        let mut tools = Self::tool_router().list_all();
        let catalog = self.verb_catalog();
        for t in &mut tools {
            if t.name == "request" {
                let base = t.description.as_deref().unwrap_or("");
                t.description = Some(std::borrow::Cow::Owned(format!(
                    "{base}\n\nVerbs registered on this server:\n{catalog}"
                )));
            }
        }
        Ok(rmcp::model::ListToolsResult {
            tools,
            meta: None,
            next_cursor: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use khive_runtime::Namespace;
    use khive_storage::{EventFilter, PageRequest};
    use serial_test::serial;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    async fn observed_batch_entry(
        _index: usize,
        delay_ms: u64,
        entry: Value,
        in_flight: Arc<AtomicUsize>,
        max_in_flight: Arc<AtomicUsize>,
    ) -> Value {
        let current = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
        max_in_flight.fetch_max(current, Ordering::SeqCst);
        tokio::time::sleep(Duration::from_millis(delay_ms)).await;
        in_flight.fetch_sub(1, Ordering::SeqCst);
        entry
    }

    fn batch_task<F>(index: usize, future: F) -> BatchTask<F>
    where
        F: Future<Output = Value>,
    {
        BatchTask {
            index,
            tool: "probe".to_string(),
            future,
        }
    }

    struct LargeResultPack;

    impl khive_types::Pack for LargeResultPack {
        const NAME: &'static str = "large-result-test";
        const NOTE_KINDS: &'static [&'static str] = &[];
        const ENTITY_KINDS: &'static [&'static str] = &[];
        const HANDLERS: &'static [khive_runtime::HandlerDef] = &[khive_runtime::HandlerDef {
            name: "large_result",
            description: "returns a caller-sized test result",
            visibility: khive_runtime::Visibility::Verb,
            category: khive_runtime::VerbCategory::Assertive,
            params: &[],
        }];
    }

    #[async_trait::async_trait]
    impl khive_runtime::PackRuntime for LargeResultPack {
        fn name(&self) -> &str {
            <Self as khive_types::Pack>::NAME
        }

        fn note_kinds(&self) -> &'static [&'static str] {
            <Self as khive_types::Pack>::NOTE_KINDS
        }

        fn entity_kinds(&self) -> &'static [&'static str] {
            <Self as khive_types::Pack>::ENTITY_KINDS
        }

        fn handlers(&self) -> &'static [khive_runtime::HandlerDef] {
            <Self as khive_types::Pack>::HANDLERS
        }

        async fn dispatch(
            &self,
            _verb: &str,
            params: Value,
            _registry: &VerbRegistry,
            _token: &khive_runtime::NamespaceToken,
        ) -> Result<Value, RuntimeError> {
            if let Some(bytes) = params
                .get("table_bytes")
                .and_then(Value::as_u64)
                .and_then(|n| usize::try_from(n).ok())
            {
                let payload = "x".repeat(bytes);
                return Ok(json!([
                    {"payload": payload},
                    {"payload": payload},
                ]));
            }
            let bytes = params
                .get("bytes")
                .and_then(Value::as_u64)
                .and_then(|n| usize::try_from(n).ok())
                .expect("test supplies a valid byte count");
            Ok(json!("x".repeat(bytes)))
        }
    }

    async fn dispatch_large_result_through_daemon(
        server: &KhiveMcpServer,
        ops: String,
        format: Option<String>,
    ) -> String {
        khive_runtime::daemon::DaemonDispatch::dispatch(
            server, ops, None, None, format, None, false, None,
        )
        .await
        .expect("daemon dispatch")
    }

    fn large_result_test_server() -> KhiveMcpServer {
        let mut builder = VerbRegistryBuilder::new();
        builder.register(LargeResultPack);
        KhiveMcpServer::from_registry(builder.build().expect("test registry"))
    }

    #[tokio::test]
    async fn bounded_batch_preserves_input_order() {
        let count = MAX_BATCH_CONCURRENCY + 3;
        let in_flight = Arc::new(AtomicUsize::new(0));
        let max_in_flight = Arc::new(AtomicUsize::new(0));
        let futures = (0..count).map(|index| {
            batch_task(
                index,
                observed_batch_entry(
                    index,
                    (count - index) as u64,
                    json!({"ok": true, "tool": "probe", "result": {"index": index}}),
                    in_flight.clone(),
                    max_in_flight.clone(),
                ),
            )
        });

        let results = execute_bounded_batch(futures, usize::MAX).await;

        let indices: Vec<u64> = results
            .iter()
            .map(|entry| entry["result"]["index"].as_u64().expect("result index"))
            .collect();
        assert_eq!(indices, (0..count as u64).collect::<Vec<_>>());
    }

    #[tokio::test]
    async fn bounded_batch_enforces_aggregate_response_budget() {
        assert_eq!(
            BATCH_RESPONSE_BUDGET_BYTES,
            khive_runtime::daemon::MAX_FRAME_BYTES / 2
        );
        let count = MAX_BATCH_CONCURRENCY * 2;
        let budget = BATCH_RESPONSE_BUDGET_BYTES;
        let small = json!({
            "ok": true,
            "tool": "probe",
            "result": "x".repeat(budget / 4 - 128),
        });
        let in_flight = Arc::new(AtomicUsize::new(0));
        let max_in_flight = Arc::new(AtomicUsize::new(0));
        let futures = (0..count).map(|index| {
            let (delay_ms, entry) = if index < 2 {
                (index as u64, small.clone())
            } else if index == 2 {
                (
                    30,
                    json!({"ok": true, "tool": "probe", "result": "x".repeat(budget)}),
                )
            } else {
                (
                    60,
                    json!({"ok": true, "tool": "probe", "result": {"index": index}}),
                )
            };
            batch_task(
                index,
                observed_batch_entry(
                    index,
                    delay_ms,
                    entry,
                    in_flight.clone(),
                    max_in_flight.clone(),
                ),
            )
        });

        let results = tokio::time::timeout(
            Duration::from_secs(1),
            execute_bounded_batch(futures, budget),
        )
        .await
        .expect("started operations must settle promptly after a budget breach");
        let response = parallel_batch_envelope(results);

        assert_eq!(
            response["summary"],
            json!({"total": count, "succeeded": 10, "failed": count - 10, "aborted": 0})
        );
        assert_eq!(response["results"][0]["ok"], true);
        assert_eq!(response["results"][1]["ok"], true);
        assert_eq!(
            response["results"][2]["result"]
                .as_str()
                .expect("breaching result remains truthful")
                .len(),
            budget
        );
        for index in 3..10 {
            assert_eq!(response["results"][index]["ok"], true);
            assert_eq!(response["results"][index]["result"]["index"], index);
        }
        for entry in response["results"]
            .as_array()
            .expect("results")
            .iter()
            .skip(10)
        {
            assert_eq!(entry["ok"], false);
            let error = entry["error"].as_str().expect("budget error string");
            assert!(error.contains("batch response budget"));
            assert!(error.contains(&budget.to_string()));
        }
        assert_eq!(in_flight.load(Ordering::SeqCst), 0);
        serde_json::to_vec(&response).expect("budgeted response must serialize");
    }

    #[tokio::test]
    async fn save_to_writes_full_results_without_inline_response_budgeting() {
        let server = large_result_test_server();
        let dir = tempfile::tempdir().expect("tempdir");
        let sink_path = dir.path().join("full-results.jsonl");
        let result_bytes = BATCH_RESPONSE_BUDGET_BYTES * 3 / 4;
        let response = server
            .dispatch_request_inner(
                RequestParams {
                    ops: format!(
                        "[large_result(bytes={result_bytes}), large_result(bytes={result_bytes})]"
                    ),
                    presentation: None,
                    presentation_per_op: None,
                    save_to: Some(sink_path.to_string_lossy().into_owned()),
                    format: None,
                    format_per_op: None,
                    request_id: None,
                },
                false,
                None,
                DispatchOrigin::Local,
            )
            .await
            .expect("save_to dispatch");

        let manifest: Value = serde_json::from_str(&response).expect("manifest JSON");
        assert_eq!(manifest["rows"], 2);
        assert_eq!(manifest["summary"]["succeeded"], 2);
        let rows: Vec<Value> = std::fs::read_to_string(&sink_path)
            .expect("read JSONL")
            .lines()
            .map(|line| serde_json::from_str(line).expect("valid JSONL row"))
            .collect();
        assert_eq!(rows.len(), 2);
        for row in rows {
            assert_eq!(row["ok"], true);
            assert_eq!(
                row["result"].as_str().expect("full result string").len(),
                result_bytes
            );
        }
    }

    #[tokio::test]
    async fn local_dispatch_returns_result_larger_than_daemon_frame() {
        let server = large_result_test_server();
        let result_bytes = khive_runtime::daemon::MAX_FRAME_BYTES + 1_024;
        let response = server
            .dispatch_request_local(RequestParams {
                ops: format!("large_result(bytes={result_bytes})"),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("local dispatch");

        let envelope: Value = serde_json::from_str(&response).expect("response envelope");
        assert_eq!(envelope["results"][0]["ok"], true);
        assert_eq!(
            envelope["results"][0]["result"]
                .as_str()
                .expect("full local result")
                .len(),
            result_bytes
        );
        assert!(envelope["results"][0].get("result_omitted").is_none());
    }

    #[tokio::test]
    async fn daemon_dispatch_degrades_result_larger_than_frame() {
        let server = large_result_test_server();
        let result_bytes = khive_runtime::daemon::MAX_FRAME_BYTES + 1_024;
        let response = dispatch_large_result_through_daemon(
            &server,
            format!("large_result(bytes={result_bytes})"),
            None,
        )
        .await;

        let envelope: Value = serde_json::from_str(&response).expect("response envelope");
        assert_eq!(envelope["results"][0]["ok"], true);
        assert!(envelope["results"][0].get("result").is_none());
        assert!(envelope["results"][0].get("result_omitted").is_some());
        assert!(rendered_response_fits_daemon_frame(
            &response,
            &server.config_id
        ));
    }

    #[tokio::test]
    async fn daemon_batch_keeps_rendered_result_when_compact_result_exceeds_frame() {
        let server = large_result_test_server();
        let row_bytes = khive_runtime::daemon::MAX_FRAME_BYTES / 2;
        let response = dispatch_large_result_through_daemon(
            &server,
            format!("large_result(table_bytes={row_bytes})"),
            Some("auto".to_string()),
        )
        .await;

        let envelope: Value = serde_json::from_str(&response).expect("response envelope");
        let entry = &envelope["results"][0];
        assert_eq!(entry["ok"], true);
        assert!(entry.get("result_omitted").is_none());
        let rendered = entry["result"].as_str().expect("rendered table result");
        assert!(rendered.starts_with("| payload |"));
        assert!(rendered.len() < row_bytes);
        assert!(rendered_response_fits_daemon_frame(
            &response,
            &server.config_id
        ));
    }

    #[test]
    fn auto_rendered_batch_stays_within_daemon_frame_cap() {
        let mut leaves = serde_json::Map::new();
        for index in 0..80_000 {
            leaves.insert(format!("k{index}"), json!(0));
        }
        let result = nest_object(60, Value::Object(leaves));
        let envelope = parallel_batch_envelope(vec![json!({
            "ok": true,
            "tool": "probe",
            "result": result,
        })]);
        let compact_bytes = serde_json::to_vec(&envelope)
            .expect("compact envelope")
            .len();
        assert!(compact_bytes < BATCH_RESPONSE_BUDGET_BYTES);

        let rendered = render_result(
            envelope,
            OutputFormat::Auto,
            &None,
            PresentationMode::Agent,
            &None,
            &large_result_test_server().registry,
            Some("test"),
        );
        let rendered_value: Value = serde_json::from_str(&rendered).expect("response envelope");
        assert_eq!(rendered_value["status"], "success");
        assert_eq!(rendered_value["results"][0]["ok"], true);
        assert!(
            rendered_value["results"][0]["result"].is_object(),
            "oversized auto output must fall back to the truthful compact result"
        );
        let frame = khive_runtime::DaemonResponseFrame {
            ok: true,
            result: Some(rendered),
            error: None,
            namespace_mismatch: false,
            config_mismatch: false,
            served_config_id: Some("test".to_string()),
            version_mismatch: false,
            daemon_protocol_version: khive_runtime::PROTOCOL_VERSION,
            metrics: None,
            request_id: None,
        };
        let frame_bytes = serde_json::to_vec(&frame).expect("daemon frame").len();
        assert!(
            frame_bytes <= khive_runtime::daemon::MAX_FRAME_BYTES,
            "rendered daemon frame was {frame_bytes} bytes"
        );
    }

    #[tokio::test]
    async fn bounded_batch_op_error_does_not_abort_siblings() {
        let count = 5;
        let in_flight = Arc::new(AtomicUsize::new(0));
        let max_in_flight = Arc::new(AtomicUsize::new(0));
        let futures = (0..count).map(|index| {
            let entry = if index == 2 {
                json!({"ok": false, "tool": "probe", "error": "expected failure"})
            } else {
                json!({"ok": true, "tool": "probe", "result": {"index": index}})
            };
            batch_task(
                index,
                observed_batch_entry(
                    index,
                    (count - index) as u64,
                    entry,
                    in_flight.clone(),
                    max_in_flight.clone(),
                ),
            )
        });

        let response = parallel_batch_envelope(execute_bounded_batch(futures, usize::MAX).await);

        assert_eq!(
            response["summary"],
            json!({"total": 5, "succeeded": 4, "failed": 1, "aborted": 0})
        );
        assert_eq!(response["results"][2]["error"], "expected failure");
        assert!(response["results"][3]["ok"].as_bool().unwrap_or(false));
        assert!(response["results"][4]["ok"].as_bool().unwrap_or(false));
    }

    #[tokio::test]
    async fn bounded_batch_never_exceeds_concurrency_limit() {
        let count = MAX_BATCH_CONCURRENCY * 3;
        let in_flight = Arc::new(AtomicUsize::new(0));
        let max_in_flight = Arc::new(AtomicUsize::new(0));
        let futures = (0..count).map(|index| {
            batch_task(
                index,
                observed_batch_entry(
                    index,
                    10,
                    json!({"ok": true, "tool": "probe", "result": index}),
                    in_flight.clone(),
                    max_in_flight.clone(),
                ),
            )
        });

        let results = execute_bounded_batch(futures, usize::MAX).await;

        assert_eq!(results.len(), count);
        assert_eq!(max_in_flight.load(Ordering::SeqCst), MAX_BATCH_CONCURRENCY);
        assert_eq!(in_flight.load(Ordering::SeqCst), 0);
    }

    fn t(pack: &str, verb: &str, desc: &str) -> (String, String, String) {
        (pack.to_owned(), verb.to_owned(), desc.to_owned())
    }

    // ── serve_stdio handshake-mode decision (#714) ────────────────────────────

    #[cfg(unix)]
    #[test]
    fn stdio_serve_mode_cold_start_uses_handshake() {
        assert_eq!(stdio_serve_mode_for(None), StdioServeMode::Handshake);
    }

    #[cfg(unix)]
    #[test]
    fn stdio_serve_mode_resumed_generation_skips_handshake() {
        assert_eq!(stdio_serve_mode_for(Some(1)), StdioServeMode::Resumed);
    }

    #[test]
    fn single_pack_verbs_unchanged() {
        let catalog = build_verb_catalog([
            t("kg", "create", "Create an entity or note."),
            t("kg", "list", "List entities."),
        ]);
        assert_eq!(
            catalog,
            "  create — Create an entity or note.\n  list — List entities.\n"
        );
    }

    #[test]
    fn duplicate_verb_concatenates_descriptions_with_pack_attribution() {
        let catalog = build_verb_catalog([
            t("kg", "create", "Create an entity or note."),
            t("gtd", "create", "Create a task."),
        ]);
        // Both pack descriptions must appear with attribution.
        assert!(catalog.contains("[kg] Create an entity or note."));
        assert!(catalog.contains("[gtd] Create a task."));
        // The verb name must appear exactly once in the catalog header.
        assert_eq!(catalog.matches("  create — ").count(), 1);
    }

    #[test]
    fn instructions_carry_docs_address_and_guidance_pointers() {
        let instructions = build_instructions("  create — Create an entity or note.\n", "kg, gtd");
        assert!(instructions.contains("https://ohdearquant.github.io/khive/"));
        assert!(instructions.contains("docs/configuration.md"));
        assert!(instructions.contains("docs/guide/tips-and-tricks.md"));
        // help=true / live-catalog-over-training-knowledge guidance present.
        assert!(instructions.contains("help=true"));
    }

    #[test]
    fn catalog_is_sorted_alphabetically() {
        let catalog = build_verb_catalog([
            t("kg", "search", "Search."),
            t("kg", "assign", "Assign."),
            t("kg", "list", "List."),
        ]);
        let names: Vec<&str> = catalog
            .lines()
            .filter(|l| l.starts_with("  "))
            .map(|l| l.trim_start().split(' ').next().unwrap())
            .collect();
        assert_eq!(names, vec!["assign", "list", "search"]);
    }

    // ── #658 regression: brain dispatch hook wired into production builder ──

    /// The hook (registered via `PackInstall::dispatch_hook`) and the pack
    /// runtime the registry dispatches `brain.*` verbs to must be the same
    /// `BrainPack` instance — otherwise the hook's posterior updates would be
    /// invisible to `brain.state` reads. `brain.state` loads the default
    /// namespace into the shared active slot as a side effect, so a
    /// subsequent non-brain dispatch in the same namespace lands on
    /// `ApplyTarget::ActiveSlot` and is immediately observable.
    ///
    /// Uses the `local` namespace (rather than an arbitrary one) because
    /// ADR-007 Rule 3b always pins the implicit write token to `local`
    /// regardless of the registry's configured default namespace; using
    /// `local` for both keeps the dispatched event's namespace and the
    /// token's namespace identical, so the signal lands on the active slot
    /// instead of the cold-namespace queue.
    #[tokio::test]
    async fn brain_dispatch_hook_updates_state_visible_through_same_instance() {
        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::local(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string(), "brain".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        let server = KhiveMcpServer::with_packs(runtime, &["kg".to_string(), "brain".to_string()])
            .expect("server builds with kg + brain");

        server
            .registry
            .dispatch("brain.state", serde_json::Value::Null)
            .await
            .expect("brain.state loads the default namespace into the active slot");

        server
            .registry
            .dispatch("stats", serde_json::json!({}))
            .await
            .expect("kg.stats dispatch succeeds");

        let state = server
            .registry
            .dispatch("brain.state", serde_json::Value::Null)
            .await
            .expect("brain.state dispatch");
        let total_events = state["balanced_recall"]["total_events"]
            .as_u64()
            .unwrap_or(0);
        assert!(
            total_events > 0,
            "dispatch hook must update the same BrainPack instance the registry \
             dispatches brain.* verbs to; got snapshot {state:?}"
        );
    }

    // ── relative backend paths must not collide across projects ────────────

    /// RAII guard: temporarily chdirs into `dir`, restoring the original cwd
    /// on drop (even on panic/unwind). Process cwd is global state, so every
    /// test using this guard is `#[serial]`.
    struct CwdGuard {
        original: std::path::PathBuf,
    }

    impl CwdGuard {
        fn enter(dir: &std::path::Path) -> Self {
            let original = std::env::current_dir().expect("read cwd");
            std::env::set_current_dir(dir).expect("chdir into test project root");
            Self { original }
        }
    }

    impl Drop for CwdGuard {
        fn drop(&mut self) {
            let _ = std::env::set_current_dir(&self.original);
        }
    }

    /// The security finding this guards: `compute_config_id`'s backend
    /// topology fold used to embed the RAW relative path string declared in
    /// `khive.toml`. Two different projects that happen to declare the same
    /// relative string (e.g. `./data/main.db`) but resolve it against two
    /// different working directories produced the SAME `config_id` despite
    /// opening two different physical databases — a warm daemon started for
    /// one project could then accept forwarded requests meant for the other,
    /// serving or writing the wrong project's data.
    #[test]
    #[serial]
    fn config_id_does_not_collide_across_projects_with_same_relative_backend_path() {
        use khive_runtime::{BackendId, BackendKind, KhiveConfig, Namespace};

        let project_a = tempfile::tempdir().expect("project a tempdir");
        let project_b = tempfile::tempdir().expect("project b tempdir");

        let base_rt = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::parse("local").unwrap(),
            embedding_model: None,
            packs: vec!["kg".to_string()],
            backend_id: BackendId::main(),
            ..RuntimeConfig::default()
        };

        let relative_backend_cfg = || KhiveConfig {
            backends: vec![khive_runtime::BackendConfig {
                name: "main".to_string(),
                kind: BackendKind::Sqlite,
                path: Some(std::path::PathBuf::from("./data/main.db")),
                cache_mb: None,
                journal_mode: None,
                read_only: false,
            }],
            ..KhiveConfig::default()
        };

        let id_a = {
            let _cwd = CwdGuard::enter(project_a.path());
            compute_config_id(&base_rt, Some(&relative_backend_cfg()))
        };
        let id_b = {
            let _cwd = CwdGuard::enter(project_b.path());
            compute_config_id(&base_rt, Some(&relative_backend_cfg()))
        };

        assert_ne!(
            id_a, id_b,
            "two projects declaring the same relative backend path string from \
             different working directories must not share a config_id; both \
             produced: {id_a}"
        );
    }

    /// The same collision, one layer up the resolution chain: `--db`/`KHIVE_DB`
    /// resolves to a raw relative `PathBuf` (`resolve_db_anchor`) that lands in
    /// `RuntimeConfig.db_path` unchanged. Before this fix, `compute_config_id`
    /// fingerprinted that raw string directly, so two different projects both
    /// running `KHIVE_DB=./data/main.db` produced the SAME `config_id` while
    /// opening two different SQLite files — the single-backend route
    /// (`KhiveMcpServer::with_packs`) would let a warm daemon started for one
    /// project serve requests meant for the other's database.
    #[test]
    #[serial]
    fn config_id_does_not_collide_across_projects_with_same_relative_db_override() {
        use khive_runtime::Namespace;

        let project_a = tempfile::tempdir().expect("project a tempdir");
        let project_b = tempfile::tempdir().expect("project b tempdir");

        let rt_with_db = |db_path: Option<std::path::PathBuf>| RuntimeConfig {
            db_path,
            default_namespace: Namespace::parse("local").unwrap(),
            embedding_model: None,
            packs: vec!["kg".to_string()],
            ..RuntimeConfig::default()
        };

        let relative_db = std::path::PathBuf::from("./data/main.db");

        let id_a = {
            let _cwd = CwdGuard::enter(project_a.path());
            compute_config_id(&rt_with_db(Some(relative_db.clone())), None)
        };
        let id_b = {
            let _cwd = CwdGuard::enter(project_b.path());
            compute_config_id(&rt_with_db(Some(relative_db.clone())), None)
        };

        assert_ne!(
            id_a, id_b,
            "two projects overriding KHIVE_DB with the same relative path from \
             different working directories must not share a config_id; both \
             produced: {id_a}"
        );

        let id_a_again = {
            let _cwd = CwdGuard::enter(project_a.path());
            compute_config_id(&rt_with_db(Some(relative_db.clone())), None)
        };
        assert_eq!(
            id_a, id_a_again,
            "resolving the same project's KHIVE_DB override twice must produce \
             the same config_id"
        );
    }

    // ── #823: runtime `$prev` result depth guard ────────────────────────────

    /// Iteratively (no native recursion) wrap `leaf` in `depth` nested
    /// single-key objects, a synthetic stand-in for a pathologically deep
    /// handler result (e.g. from `traverse`/`context`) that would otherwise
    /// overflow the stack when cloned into `$prev` chain context.
    ///
    /// Builds each level via a direct `Map` insert rather than `json!` — the
    /// `json!` object-literal arm calls `serde_json::to_value(&v)` on the
    /// accumulated value, which would walk the whole tree built so far on
    /// every iteration (recursing to the current depth each time) and
    /// overflow the stack itself well before reaching `depth` large enough
    /// to exercise the guard under test.
    fn nest_object(depth: usize, leaf: Value) -> Value {
        let mut v = leaf;
        for _ in 0..depth {
            let mut map = serde_json::Map::with_capacity(1);
            map.insert("nested".to_string(), v);
            v = Value::Object(map);
        }
        v
    }

    #[test]
    fn deep_nested_result_over_limit_is_flagged() {
        let deep = nest_object(
            khive_request::NESTING_DEPTH_LIMIT + 5,
            json!({"leaf": true}),
        );
        let result_obj = json!({ "ok": true, "tool": "traverse", "result": deep });
        assert!(
            result_exceeds_depth_limit(&result_obj),
            "result nested past NESTING_DEPTH_LIMIT must be flagged"
        );
    }

    #[test]
    fn result_at_exactly_the_depth_limit_is_not_flagged() {
        // A scalar leaf (not a container) so the wrapping objects alone land
        // exactly at NESTING_DEPTH_LIMIT containers deep.
        let at_limit = nest_object(khive_request::NESTING_DEPTH_LIMIT, json!(true));
        let result_obj = json!({ "ok": true, "tool": "traverse", "result": at_limit });
        assert!(
            !result_exceeds_depth_limit(&result_obj),
            "result nested exactly at the limit must still be usable as $prev context"
        );
    }

    #[test]
    fn shallow_result_is_not_flagged() {
        let shallow = json!({"a": {"b": {"c": 1}}});
        let result_obj = json!({ "ok": true, "tool": "get", "result": shallow });
        assert!(!result_exceeds_depth_limit(&result_obj));
    }

    #[test]
    fn result_missing_field_is_not_flagged() {
        let result_obj = json!({ "ok": false, "tool": "get", "error": "not found" });
        assert!(!result_exceeds_depth_limit(&result_obj));
    }

    #[test]
    fn chain_aggregation_seam_rejects_over_limit_result_via_iterative_drop() {
        // Directly exercises the post-hoc aggregation-loop guard in
        // `run_parsed`'s `Chain` arm (isolated as
        // `chain_aggregation_depth_reject`) with a value nested well past
        // NESTING_DEPTH_LIMIT. If this branch let the rejected `result_obj`
        // fall out of scope instead of routing it through
        // `drop_value_iteratively`, `Value`'s derived recursive `Drop` would
        // overflow the stack on a value this deep — so this test failing to
        // complete (rather than merely asserting wrong) is itself the
        // regression signal for #823's post-hoc-rejection finding.
        let deep = nest_object(khive_request::NESTING_DEPTH_LIMIT + 50_000, json!(true));
        // Built via direct `Map` inserts, not `json!({..., "result": deep})`:
        // the object-literal macro arm calls `serde_json::to_value(&deep)` on
        // the already-deep value, which would recurse over the whole tree
        // and overflow the stack while constructing the fixture itself,
        // before the guard under test ever runs (see `nest_object` above).
        let mut envelope = serde_json::Map::with_capacity(3);
        envelope.insert("ok".to_string(), Value::Bool(true));
        envelope.insert("tool".to_string(), Value::String("traverse".to_string()));
        envelope.insert("result".to_string(), deep);
        let result_obj = Value::Object(envelope);

        let err = chain_aggregation_depth_reject(result_obj)
            .expect_err("result nested past NESTING_DEPTH_LIMIT must be rejected");

        assert_eq!(err["ok"], json!(false));
        assert_eq!(err["tool"], json!("traverse"));
        assert_eq!(err["error"]["kind"], json!("result_too_deep"));
        // The error entry must never embed the oversized value itself.
        assert!(err.get("result").is_none());
    }

    #[test]
    fn chain_aggregation_seam_accepts_result_within_limit_unchanged() {
        let shallow = json!({ "ok": true, "tool": "get", "result": {"a": {"b": 1}} });
        let accepted = chain_aggregation_depth_reject(shallow.clone())
            .expect("result within the limit must be passed through unchanged");
        assert_eq!(accepted, shallow);
    }

    // ── earliest-seam guard: raw handler `Value` before json!/present/clone ──
    //
    // These exercise `chain_ok_envelope_or_depth_error` and
    // `present_ok_envelope_or_depth_error` directly with a synthetic
    // over-limit `Value` — no DSL parsing involved, standing in for a mock
    // handler whose result is pathologically deep regardless of how shallow
    // the caller's own op args were. This is the earliest point in
    // `dispatch_op` / `run_parsed`'s parallel closure where the raw value is
    // available, strictly before it is ever cloned, presented, or passed
    // through `json!`/`serde_json::to_value`.

    #[test]
    fn chain_seam_rejects_over_limit_result_before_envelope_build() {
        // Deep enough that native recursion (json!/to_value/present) over
        // this value would be a real stack risk; the guard must reject it
        // via the iterative checker without ever attempting that recursion.
        let pathological = nest_object(khive_request::NESTING_DEPTH_LIMIT + 50_000, json!(true));
        let err = chain_ok_envelope_or_depth_error("traverse".to_string(), pathological)
            .expect_err("over-limit result must be rejected, not enveloped");
        assert_eq!(err.0, "traverse");
        assert_eq!(err.1["kind"], json!("result_too_deep"));
        // The error payload must never embed the oversized value itself.
        assert!(err.1.get("result").is_none());
        assert!(err.1.get("nested").is_none());
    }

    #[test]
    fn chain_seam_accepts_at_limit_result_and_moves_value_without_reserializing() {
        let at_limit = nest_object(khive_request::NESTING_DEPTH_LIMIT, json!("leaf"));
        let envelope = chain_ok_envelope_or_depth_error("get".to_string(), at_limit.clone())
            .expect("result at exactly the limit must be accepted");
        assert_eq!(envelope["ok"], json!(true));
        assert_eq!(envelope["tool"], json!("get"));
        assert_eq!(envelope["result"], at_limit);
    }

    #[test]
    fn parallel_seam_rejects_over_limit_result_before_present() {
        let pathological = nest_object(khive_request::NESTING_DEPTH_LIMIT + 50_000, json!(true));
        let envelope = present_ok_envelope_or_depth_error(
            "context".to_string(),
            pathological,
            PresentationMode::Agent,
            0,
        );
        assert_eq!(envelope["ok"], json!(false));
        assert_eq!(envelope["tool"], json!("context"));
        assert_eq!(envelope["error"]["kind"], json!("result_too_deep"));
        assert!(envelope["error"].get("result").is_none());
    }

    #[test]
    fn parallel_seam_accepts_shallow_result_and_applies_presentation() {
        let shallow = json!({"id": "11111111-1111-1111-1111-111111111111"});
        let envelope = present_ok_envelope_or_depth_error(
            "get".to_string(),
            shallow,
            PresentationMode::Verbose,
            0,
        );
        assert_eq!(envelope["ok"], json!(true));
        assert_eq!(
            envelope["result"]["id"],
            json!("11111111-1111-1111-1111-111111111111")
        );
    }

    #[tokio::test]
    async fn chain_with_deep_accumulated_prev_result_errors_cleanly() {
        // Real end-to-end reproduction: chain N `create` ops where each step's
        // `properties.inner` embeds the previous op's full `properties` via
        // `$prev.properties`. Each op's own DSL args stay shallow (well under
        // NESTING_DEPTH_LIMIT), but the accumulated *runtime result* nests one
        // level deeper per chain step, the exact CWE-674 shape the parser's
        // syntax-tree guard cannot see. Past the limit this must surface a
        // clean per-op `result_too_deep` error and abort the remaining chain,
        // never attempting to clone/serialize the unbounded value.
        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::local(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        let server = KhiveMcpServer::new(runtime).expect("server builds with kg");

        let steps = khive_request::NESTING_DEPTH_LIMIT + 6;
        let mut dsl = String::from(
            r#"create(kind="entity", entity_kind="concept", name="d0", properties={"n": 0})"#,
        );
        for i in 1..steps {
            dsl.push_str(&format!(
                r#" | create(kind="entity", entity_kind="concept", name="d{i}", properties={{"inner": $prev.properties}})"#
            ));
        }

        let parsed = parse_request(&dsl).expect("each op's own args stay shallow; DSL must parse");
        assert_eq!(parsed.mode, ExecutionMode::Chain);

        let response = server
            .run_parsed(
                parsed.ops,
                parsed.mode,
                PresentationMode::Verbose,
                None,
                RunParsedContext {
                    enforce_response_budget: true,
                    from_wire: false,
                    identity: None,
                },
            )
            .await;

        let results = response["results"]
            .as_array()
            .expect("results must be an array");
        assert_eq!(results.len(), steps);

        let failure_idx = results
            .iter()
            .position(|r| r["ok"] == json!(false))
            .expect("accumulated nesting must trip the depth guard before the chain completes");
        assert_eq!(
            results[failure_idx]["error"]["kind"],
            json!("result_too_deep"),
            "unexpected failure shape at index {failure_idx}: {:?}",
            results[failure_idx]
        );

        // Every op after the failing one is marked aborted, not attempted,
        // proving the process kept running instead of crashing.
        for r in &results[failure_idx + 1..] {
            assert_eq!(
                r["aborted"],
                json!(true),
                "expected abort after the depth guard trips: {r:?}"
            );
        }
    }

    // ── request-boundary regression: raw controls survive wire decoding ─────

    #[tokio::test]
    async fn request_boundary_raw_control_bytes_reach_handler() {
        // Simulates the actual MCP wire: a JSON-RPC client sends the tool's
        // `ops` argument as a JSON string using the standard JSON `\n`
        // escape. Deserializing `RequestParams` decodes that escape into an
        // actual raw LF byte inside the DSL source — the exact shape
        // `normalize_quoted_string` (crates/khive-request/src/parser/scan.rs)
        // exists to accept. This confirms the decoded raw newline survives
        // parsing and dispatch all the way to the pack handler's result.
        let wire = "{\"ops\":\"create(kind=\\\"entity\\\", entity_kind=\\\"concept\\\", name=\\\"line1\\nline2\\\")\"}";
        let params: RequestParams = serde_json::from_str(wire).expect("wire JSON deserializes");
        assert!(
            params.ops.contains('\n'),
            "deserialized ops must carry a raw LF, not the two-char escape: {:?}",
            params.ops
        );

        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::local(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        let server = KhiveMcpServer::new(runtime).expect("server builds with kg");

        let parsed = parse_request(&params.ops).expect("literal newline inside quotes must parse");
        let response = server
            .run_parsed(
                parsed.ops,
                parsed.mode,
                PresentationMode::Verbose,
                None,
                RunParsedContext {
                    enforce_response_budget: true,
                    from_wire: false,
                    identity: None,
                },
            )
            .await;

        let results = response["results"]
            .as_array()
            .expect("results must be an array");
        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0]["ok"],
            json!(true),
            "unexpected result: {response:?}"
        );
        assert_eq!(results[0]["result"]["name"], json!("line1\nline2"));
    }

    // ── MCP-AUD-002 regression: save_to must bypass daemon forwarding ────────

    fn make_daemon_save_to_test_server() -> KhiveMcpServer {
        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::parse("test").unwrap(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        KhiveMcpServer::new(runtime).expect("server builds with kg")
    }

    fn clear_daemon_env() {
        std::env::remove_var("KHIVE_SOCKET");
        std::env::remove_var("KHIVE_PID");
        std::env::remove_var("KHIVE_NO_DAEMON");
        std::env::remove_var("KHIVE_LOCK");
        std::env::remove_var("KHIVE_PROCESS_REF");
    }

    /// khive#948: `wire_daemon_frame` forwards `RequestParams::request_id`
    /// onto the `DaemonRequestFrame` unchanged, and defaults to `None` when
    /// the caller supplied none.
    #[cfg(unix)]
    #[test]
    fn wire_daemon_frame_forwards_request_id() {
        let server = make_daemon_save_to_test_server();

        let with_id = RequestParams {
            ops: "stats()".to_string(),
            request_id: Some(123),
            ..Default::default()
        };
        let frame = server.wire_daemon_frame(&with_id);
        assert_eq!(frame.request_id, Some(123));

        let without_id = RequestParams {
            ops: "stats()".to_string(),
            ..Default::default()
        };
        let frame = server.wire_daemon_frame(&without_id);
        assert_eq!(frame.request_id, None);
    }

    /// Query every persisted audit event and find the one whose
    /// `resource.request_id` matches `id`, if any.
    async fn find_audit_event_with_request_id(
        store: &Arc<dyn khive_storage::EventStore>,
        id: u64,
    ) -> Option<khive_storage::Event> {
        let page = store
            .query_events(
                EventFilter::default(),
                PageRequest {
                    limit: 50,
                    offset: 0,
                },
            )
            .await
            .expect("query_events must succeed");
        page.items
            .into_iter()
            .find(|ev| ev.payload["resource"]["request_id"] == json!(id))
    }

    /// khive#948: `request_id` was previously dropped on the
    /// `KHIVE_NO_DAEMON`/soft-fallback local dispatch path because
    /// `dispatch_request_wire` always passed `identity = None`. This drives
    /// `request()` end-to-end under `KHIVE_NO_DAEMON=1` and inspects the
    /// persisted audit event, proving the id now survives to
    /// `resource.request_id` on the local-dispatch path too, not just the
    /// daemon-forward path.
    #[tokio::test]
    #[serial]
    async fn request_no_daemon_fallback_preserves_request_id_in_audit_event() {
        clear_daemon_env();
        std::env::set_var("KHIVE_NO_DAEMON", "1");

        let server = make_daemon_save_to_test_server();
        server
            .request(Parameters(RequestParams {
                // Explicit `namespace="local"` so the write lands in the
                // same namespace the server's audit `EventStore` handle is
                // scoped to at construction (`Namespace::local()`), matching
                // `find_audit_event_with_request_id`'s read scope.
                ops: "stats(namespace=\"local\")".to_string(),
                request_id: Some(9001),
                ..Default::default()
            }))
            .await
            .expect("request() must succeed via local dispatch under KHIVE_NO_DAEMON");

        let store = server
            .event_store()
            .expect("in-memory runtime must configure an EventStore");
        let matched = find_audit_event_with_request_id(&store, 9001).await;
        assert!(
            matched.is_some(),
            "KHIVE_NO_DAEMON local dispatch must stamp request_id onto the persisted \
             audit event"
        );

        clear_daemon_env();
    }

    /// khive#948: the `save_to` bypass (MCP-AUD-002) also routes through
    /// `dispatch_request_wire`'s local dispatch — this proves the id
    /// survives that path too.
    #[tokio::test]
    #[serial]
    async fn request_save_to_bypass_preserves_request_id_in_audit_event() {
        clear_daemon_env();
        let dir = tempfile::tempdir().expect("tempdir");
        std::env::set_var("KHIVE_SAVE_TO_ROOT", dir.path());

        let server = make_daemon_save_to_test_server();
        let sink_path = dir.path().join("out.jsonl");
        server
            .request(Parameters(RequestParams {
                ops: "stats(namespace=\"local\")".to_string(),
                save_to: Some(sink_path.to_string_lossy().to_string()),
                request_id: Some(9002),
                ..Default::default()
            }))
            .await
            .expect("request() with save_to must succeed");

        let store = server
            .event_store()
            .expect("in-memory runtime must configure an EventStore");
        let matched = find_audit_event_with_request_id(&store, 9002).await;
        assert!(
            matched.is_some(),
            "save_to local-dispatch bypass must stamp request_id onto the persisted \
             audit event"
        );

        clear_daemon_env();
        std::env::remove_var("KHIVE_SAVE_TO_ROOT");
    }

    #[cfg(unix)]
    async fn connect_when_daemon_ready(sock: &std::path::Path) {
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            if tokio::net::UnixStream::connect(sock).await.is_ok() {
                return;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "daemon never bound {sock:?} within 5s"
            );
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
    }

    /// Regression for MCP-AUD-002 / #440: `request()` must NOT forward a
    /// `save_to`-bearing call to a warm daemon (whose wire frame has no
    /// `save_to` field and would silently return the inline result instead of
    /// writing the sink). With a real daemon reachable at `KHIVE_SOCKET`, a
    /// `save_to` request must still take the local path and return the
    /// manifest with the file actually written — proving the daemon was
    /// bypassed rather than silently dropping the sink.
    #[cfg(unix)]
    #[tokio::test]
    #[serial]
    async fn request_save_to_bypasses_daemon_forwarding_and_writes_manifest() {
        clear_daemon_env();
        let dir = tempfile::tempdir().expect("tempdir");
        let sock = dir.path().join("khived.sock");
        let pid = dir.path().join("khived.pid");
        std::env::set_var("KHIVE_SOCKET", &sock);
        std::env::set_var("KHIVE_PID", &pid);
        std::env::remove_var("KHIVE_NO_DAEMON");
        // save_to destinations must resolve inside the allowed export root
        // (crate::save_sink); scope it to this test's tempdir.
        std::env::set_var("KHIVE_SAVE_TO_ROOT", dir.path());

        let server = make_daemon_save_to_test_server();
        let daemon_server = server.clone();
        let handle = tokio::spawn(async move {
            let _ = khive_runtime::daemon::run_daemon(daemon_server).await;
        });
        connect_when_daemon_ready(&sock).await;

        let sink_path = dir.path().join("out.jsonl");
        let resp = server
            .request(Parameters(RequestParams {
                ops: "stats()".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: Some(sink_path.to_string_lossy().to_string()),
                format: None,
                format_per_op: None,
                request_id: None,
            }))
            .await
            .expect("request with save_to must succeed even with a warm daemon reachable");

        let manifest: serde_json::Value =
            serde_json::from_str(&resp).expect("response must be the save_to manifest JSON");
        assert!(
            manifest.get("rows").is_some() && manifest.get("path").is_some(),
            "response must be the save_to manifest, not an inline daemon result; got: {resp}"
        );
        assert!(
            sink_path.exists(),
            "save_to file must be written even when a daemon is reachable"
        );
        let contents = std::fs::read_to_string(&sink_path).expect("read sink file");
        assert!(
            !contents.trim().is_empty(),
            "sink file must contain JSONL content"
        );

        handle.abort();
        let _ = handle.await;
        clear_daemon_env();
        std::env::remove_var("KHIVE_SAVE_TO_ROOT");
    }

    // ── #644 regression: ambiguous post-write outcome must not double-dispatch ──
    //
    // `request()`'s daemon-forward call site (`if let Some(res) = forward_or_spawn(...)
    // .await { return res; }`) must return BOTH `Some(Ok(_))` and `Some(Err(_))`
    // directly, never falling through to `dispatch_request_wire` on the `Err`
    // arm. If a future edit narrowed that match to only short-circuit on
    // success (e.g. `if let Some(Ok(res)) = ...`), a mutating op whose real
    // frame was already written to a now-dead daemon would ALSO run through
    // local dispatch — a duplicate execution of the exact case #644 exists to
    // prevent. This forces that ambiguous outcome (a fake socket that reads
    // the request then closes without responding, exactly as a daemon crash
    // mid-dispatch would) and proves both that the caller sees the
    // ambiguous-forward error verbatim AND that the mutating op never actually
    // ran locally.
    #[cfg(unix)]
    #[tokio::test]
    #[serial]
    async fn request_returns_ambiguous_forward_error_without_local_double_dispatch() {
        clear_daemon_env();
        let dir = tempfile::tempdir().expect("tempdir");
        let sock = dir.path().join("khived.sock");
        let pid = dir.path().join("khived.pid");
        std::env::set_var("KHIVE_SOCKET", &sock);
        std::env::set_var("KHIVE_PID", &pid);
        std::env::remove_var("KHIVE_NO_DAEMON");

        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::parse("test").unwrap(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string(), "comm".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        let server = KhiveMcpServer::new(runtime).expect("server builds with kg + comm");

        // Fake "crashed daemon": accept exactly one connection, read the
        // request frame (the real write #644 cares about), then drop the
        // stream without writing a response.
        let listener =
            tokio::net::UnixListener::bind(&sock).expect("bind fake crash-daemon socket");
        let fake_handle = tokio::spawn(async move {
            if let Ok((mut stream, _)) = listener.accept().await {
                let _ = khive_runtime::daemon::read_frame(&mut stream).await;
            }
        });

        let baseline = server
            .dispatch_request_local(RequestParams {
                ops: "stats()".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("baseline stats() must succeed");

        let resp = server
            .request(Parameters(RequestParams {
                ops: "comm.send(to=\"bob\", content=\"double-forward-probe\")".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            }))
            .await;

        match resp {
            Err(McpError { message, .. }) => {
                assert!(
                    message.contains(
                        "not retrying or locally dispatching to avoid duplicate execution"
                    ),
                    "request() must surface forward_or_spawn's ambiguous-forward error \
                     verbatim, not a local dispatch result; got: {message}"
                );
            }
            Ok(v) => panic!(
                "request() must return the ambiguous-forward error directly, not fall \
                 through to local dispatch; got Ok({v})"
            ),
        }

        let after = server
            .dispatch_request_local(RequestParams {
                ops: "stats()".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("post-request stats() must succeed");
        assert_eq!(
            after, baseline,
            "the comm.send op must NEVER have run locally after the ambiguous \
             forward outcome — a double-dispatch would mutate local state here"
        );

        let _ = tokio::time::timeout(std::time::Duration::from_secs(2), fake_handle).await;
        clear_daemon_env();
    }

    // ── #947 Medium regression: strict fallback lands as a per-op envelope ──
    //
    // Before this fix, `request()` returned `forward_or_spawn`'s strict-mode
    // rejection as a raw `Err(McpError)`, bypassing the per-op `{ok, tool,
    // result/error}` / `summary` wire contract every other failure mode goes
    // through. This drives `request()` end to end with a genuinely
    // unreachable daemon under `KHIVE_DAEMON_STRICT=1` and asserts: (1) the
    // response is `Ok(envelope_json)`, never an RPC error; (2) each shape
    // (single op, parallel batch, chain) reports the fallback reason as a
    // normal failed-op `error`, with chain aborting the remaining ops exactly
    // like a real op failure would (`run_parsed`'s `Chain` arm); (3) summary
    // counts match `results`; and (4) none of the ops ever ran locally (a
    // `stats()` snapshot taken via the trusted `dispatch_request_local` path
    // is unchanged after all three calls).
    #[cfg(unix)]
    #[tokio::test]
    #[serial]
    async fn request_strict_fallback_lands_as_failed_op_envelope_not_rpc_error() {
        clear_daemon_env();
        crate::daemon::reset_fallback_counters();
        let dir = tempfile::tempdir().expect("tempdir");
        // Never bound by anything in this test. The spawned test harness exits
        // immediately on `mcp --daemon`, so #898 classifies this as a confirmed
        // respawn failure rather than the older generic `no_socket` fallback.
        std::env::set_var("KHIVE_SOCKET", dir.path().join("khived.sock"));
        std::env::set_var("KHIVE_PID", dir.path().join("khived.pid"));
        std::env::set_var("KHIVE_LOCK", dir.path().join("khived.recovery.lock"));
        std::env::remove_var("KHIVE_NO_DAEMON");
        std::env::set_var("KHIVE_DAEMON_STRICT", "1");

        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::parse("test").unwrap(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string(), "comm".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        let server = KhiveMcpServer::new(runtime).expect("server builds with kg + comm");

        let baseline = server
            .dispatch_request_local(RequestParams {
                ops: "stats()".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("baseline stats() must succeed");

        fn assert_fallback_error(entry: &Value, tool: &str) {
            assert_eq!(entry["ok"], json!(false), "entry: {entry}");
            assert_eq!(entry["tool"], json!(tool), "entry: {entry}");
            let msg = entry["error"].as_str().expect("error must be a string");
            assert!(
                msg.contains("KHIVE_DAEMON_STRICT"),
                "error must name the strict mode that rejected the fallback: {msg}"
            );
            assert!(
                msg.contains("respawn_failed"),
                "error must name the confirmed respawn failure: {msg}"
            );
            assert!(
                msg.contains("make local"),
                "error must include the safe respawn remediation: {msg}"
            );
        }

        // ── single op ──────────────────────────────────────────────────────
        let single_resp = server
            .request(Parameters(RequestParams {
                ops: "comm.send(to=\"bob\", content=\"strict-single-probe\")".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            }))
            .await
            .expect("strict fallback must land as a normal Ok(envelope), not Err(McpError)");
        let single: Value =
            serde_json::from_str(&single_resp).expect("response must be the request envelope");
        assert_eq!(
            single["results"].as_array().expect("results array").len(),
            1
        );
        assert_fallback_error(&single["results"][0], "comm.send");
        assert_eq!(
            single["summary"],
            json!({ "total": 1, "succeeded": 0, "failed": 1, "aborted": 0 })
        );

        // ── parallel batch ─────────────────────────────────────────────────
        let batch_resp = server
            .request(Parameters(RequestParams {
                ops: "[comm.send(to=\"bob\", content=\"strict-batch-1\"), \
                       comm.send(to=\"bob\", content=\"strict-batch-2\")]"
                    .to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            }))
            .await
            .expect("strict fallback must land as a normal Ok(envelope), not Err(McpError)");
        let batch: Value =
            serde_json::from_str(&batch_resp).expect("response must be the request envelope");
        let batch_results = batch["results"].as_array().expect("results array");
        assert_eq!(batch_results.len(), 2);
        for entry in batch_results {
            assert_fallback_error(entry, "comm.send");
        }
        assert_eq!(
            batch["summary"],
            json!({ "total": 2, "succeeded": 0, "failed": 2, "aborted": 0 })
        );

        // ── chain (must abort remaining ops per the wire contract) ─────────
        let chain_resp = server
            .request(Parameters(RequestParams {
                ops: "comm.send(to=\"bob\", content=\"strict-chain-1\") | \
                      comm.send(to=\"bob\", content=\"strict-chain-2\")"
                    .to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            }))
            .await
            .expect("strict fallback must land as a normal Ok(envelope), not Err(McpError)");
        let chain: Value =
            serde_json::from_str(&chain_resp).expect("response must be the request envelope");
        let chain_results = chain["results"].as_array().expect("results array");
        assert_eq!(chain_results.len(), 2);
        assert_fallback_error(&chain_results[0], "comm.send");
        assert_eq!(
            chain_results[1],
            json!({ "ok": false, "tool": "comm.send", "aborted": true })
        );
        assert_eq!(
            chain["summary"],
            json!({ "total": 2, "succeeded": 0, "failed": 1, "aborted": 1 })
        );

        // ── no local dispatch ever happened for any of the three calls ─────
        let after = server
            .dispatch_request_local(RequestParams {
                ops: "stats()".to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("post-request stats() must succeed");
        assert_eq!(
            after, baseline,
            "no comm.send op must ever have run locally under strict-mode fallback \
             rejection — a local dispatch would mutate local state here"
        );

        crate::daemon::reset_fallback_counters();
        clear_daemon_env();
    }

    // ── #1220: top-level `status` distinguishes a partially-failed batch ──────

    fn in_memory_kg_server() -> KhiveMcpServer {
        let config = RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::local(),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string()],
            ..RuntimeConfig::default()
        };
        let runtime = KhiveRuntime::new(config).expect("in-memory runtime");
        KhiveMcpServer::new(runtime).expect("server builds with kg")
    }

    #[tokio::test]
    async fn request_status_is_success_when_every_op_in_batch_succeeds() {
        let server = in_memory_kg_server();
        let resp = server
            .dispatch_request_local(RequestParams {
                ops: "[create(kind=\"entity\", entity_kind=\"concept\", name=\"status-ok-1\"), \
                       create(kind=\"entity\", entity_kind=\"concept\", name=\"status-ok-2\")]"
                    .to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("batch dispatch must succeed");
        let parsed: Value = serde_json::from_str(&resp).expect("envelope must be JSON");
        assert_eq!(parsed["summary"]["failed"], 0);
        assert_eq!(
            parsed["status"], "success",
            "an all-succeeding batch must report status=success; got {parsed}"
        );
    }

    #[tokio::test]
    async fn request_status_is_partial_when_a_batch_op_fails() {
        let server = in_memory_kg_server();
        // The second op targets an unknown kind and fails; the first succeeds.
        let resp = server
            .dispatch_request_local(RequestParams {
                ops:
                    "[create(kind=\"entity\", entity_kind=\"concept\", name=\"status-partial-1\"), \
                       search(kind=\"not_a_real_kind\", query=\"x\")]"
                        .to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("batch dispatch must succeed at the RPC level even with a failed op");
        let parsed: Value = serde_json::from_str(&resp).expect("envelope must be JSON");
        assert!(
            parsed["summary"]["failed"].as_u64().unwrap_or(0) > 0,
            "expected at least one failed op; got {parsed}"
        );
        assert_eq!(
            parsed["status"], "partial",
            "a batch with a failed op must report status=partial; got {parsed}"
        );
    }

    #[tokio::test]
    async fn request_status_is_partial_when_a_chain_op_is_aborted() {
        let server = in_memory_kg_server();
        let resp = server
            .dispatch_request_local(RequestParams {
                ops: "search(kind=\"not_a_real_kind\", query=\"x\") | \
                      create(kind=\"entity\", entity_kind=\"concept\", name=\"status-chain-aborted\")"
                    .to_string(),
                presentation: None,
                presentation_per_op: None,
                save_to: None,
                format: None,
                format_per_op: None,
                request_id: None,
            })
            .await
            .expect("chain dispatch must succeed at the RPC level even with an aborted op");
        let parsed: Value = serde_json::from_str(&resp).expect("envelope must be JSON");
        assert!(
            parsed["summary"]["aborted"].as_u64().unwrap_or(0) > 0,
            "expected the second chain op to be aborted; got {parsed}"
        );
        assert_eq!(
            parsed["status"], "partial",
            "a chain with an aborted op must report status=partial; got {parsed}"
        );
    }
}