nornir 0.4.10

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! `nornir-mcp` — exposes the nornir library over the Model Context Protocol.
//!
//! Same surface as `nornir-cli`, different presentation: an MCP server
//! that registers each nornir API as a tool. LLM agents (Claude Desktop,
//! Copilot CLI, etc.) connect over stdio and can drive
//! guard/bench/release/docs/introspect operations directly.

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

use anyhow::{Context, Result};
use chrono::Utc;
use rmcp::{
    ErrorData as McpError,
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::*,
    tool, tool_handler, tool_router,
    ServerHandler, ServiceExt,
    transport::stdio,
};
use tokio::sync::Mutex;

use nornir::bench;
use nornir::config::{self, Loaded};
use nornir::funnel::{
    event::{Event as FunnelEvent, NodeStatus, PlanStatus},
    ids::{IdeaId, NodeId, PlanId},
    store::Store as FunnelStore,
    topo::topo_ready,
};
use nornir::change;
use nornir::guard;
use nornir::index;
use nornir::introspect;
use nornir::release;
use nornir::warehouse::dep_graph::WorkspaceGraph;
use nornir::warehouse::iceberg::{IcebergWarehouse, McpCall};
use nornir::workspace::descriptor::WorkspaceDescriptor;
use serde_json::json;

#[derive(Clone)]
struct NornirServer {
    state: Arc<Mutex<State>>,
    tool_router: ToolRouter<NornirServer>,
    /// Fire-and-forget sink for per-call telemetry (tool, status, latency). A
    /// single background thread drains it into the warehouse `mcp_requests`
    /// table; `None` if the warehouse couldn't be opened. Sending never blocks
    /// or fails a tool call.
    log_tx: Option<tokio::sync::mpsc::UnboundedSender<McpCall>>,
}

/// Background telemetry writer: owns one [`IcebergWarehouse`] for its lifetime
/// (its own runtime — runs on a plain thread, never nested in tokio) and
/// drain-batches incoming [`McpCall`]s into one snapshot per burst. Best-effort:
/// a warehouse error disables telemetry without touching the server.
fn spawn_mcp_log_writer(
    warehouse_root: PathBuf,
    mut rx: tokio::sync::mpsc::UnboundedReceiver<McpCall>,
) {
    std::thread::Builder::new()
        .name("nornir-mcp-log".into())
        .spawn(move || {
            let wh = match IcebergWarehouse::open(&warehouse_root) {
                Ok(w) => w,
                Err(e) => {
                    eprintln!("mcp-log: warehouse open failed; telemetry off: {e:#}");
                    return;
                }
            };
            while let Some(first) = rx.blocking_recv() {
                let mut batch = vec![first];
                while let Ok(more) = rx.try_recv() {
                    batch.push(more);
                    if batch.len() >= 256 {
                        break;
                    }
                }
                if let Err(e) = wh.append_mcp_calls(&batch) {
                    eprintln!("mcp-log: append {} call(s) failed: {e:#}", batch.len());
                }
            }
        })
        .expect("spawn nornir-mcp-log thread");
}

struct State {
    loaded: Loaded,
    funnel: FunnelStore,
    /// Lazily-built, cached dependency Mímir (graph + workspace name).
    /// Built on first dep-tool call from the resolved `nornir-workspace.toml`.
    mimir: Option<Arc<MimirCtx>>,
    /// Lazily-loaded embedder (model load is ~1s; cached for the server life).
    #[cfg(any(feature = "embed-tract", feature = "embed-ort"))]
    embedder: Option<Arc<dyn nornir::vector::store::Embedder>>,
}

/// The dependency-graph mimir context, cached in [`State`] after the
/// first dep-tool call so the (cargo-metadata-backed) graph build only
/// happens once per server lifetime.
struct MimirCtx {
    graph: WorkspaceGraph,
    workspace_name: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
#[allow(dead_code)] // fields read only in embed-feature builds
struct VectorSearchArgs {
    /// Natural-language or code query.
    query: String,
    /// Repo to search (embeddings are per-repo; must have been vectorized via
    /// `nornir vector index <repo>`).
    repo: String,
    /// Pin a historical git SHA prefix for time-travel; omit for the latest.
    #[serde(default)]
    sha: String,
    /// Max hits (default 10).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct RepoArg {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct WorkspaceUseArgs {
    /// Workspace to make active (see `workspaces_list`). Empty clears the
    /// override (back to `NORNIR_WORKSPACE`).
    name: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct WorkspaceRegisterArgs {
    /// Workspace name.
    name: String,
    /// Server-readable path to the workspace's `nornir-workspace.toml` descriptor.
    descriptor: String,
    /// `monitored` | `pushed` | `external` (default `monitored`).
    #[serde(default)]
    mode: String,
    /// Poll interval for monitored workspaces, e.g. `60s` (empty = server default).
    #[serde(default)]
    poll: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct WorkspaceOpt {
    /// Workspace name; empty = the active workspace.
    #[serde(default)]
    workspace: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct CratePublishedArgs {
    /// Crate name to look up on crates.io (case-insensitive).
    name: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct RegressionTraceArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Restrict to one workspace name; omit/empty = every workspace.
    #[serde(default)]
    workspace: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct SearchArgs {
    /// BM25 query (Tantivy syntax: terms, "phrases", AND/OR/NOT, +required, -excluded).
    query: String,
    /// Optional corpus filter: docs | code | bench_history | changelog | config.
    #[serde(default)]
    corpus: Option<String>,
    /// Optional repo filter (top-level workspace dir, e.g. "holger").
    #[serde(default)]
    repo: Option<String>,
    /// Max hits to return (default 10).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct SymbolLookupArgs {
    /// Path (relative to workspace root or absolute) to a debug-info binary.
    binary: String,
    /// Substring matched against demangled/mangled symbol names.
    pattern: String,
    /// Max hits to return (default 25).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DefinedInArgs {
    /// Path (relative to workspace root or absolute) to a debug-info binary.
    binary: String,
    /// Source file path suffix, e.g. `nornir/src/bench/mod.rs` or `mod.rs`.
    file: String,
    /// Max hits to return (default 100).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct CallQueryArgs {
    /// Path (relative to workspace root or absolute) to a debug-info binary.
    binary: String,
    /// Demangled (generics-stripped) function name, e.g. `nornir::index::Index::build`.
    name: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct PathBetweenArgs {
    binary: String,
    from: String,
    to: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct KnowledgeSymbolArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// SymbolLookup: substring matched against item names.
    /// DefinedIn: source-file path suffix (e.g. `falkor.rs` or `src/index/mod.rs`).
    arg: String,
    /// Max hits to return (default 50 for lookup, 100 for defined-in).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DwarfStoredArgs {
    /// Repo (or `_workspace`) the DWARF snapshot was keyed to via
    /// `introspect symbols --persist`.
    repo: String,
    /// SymbolLookup: substring matched against the demangled name.
    /// DefinedIn: source-file path suffix (e.g. `bar.rs` or `src/lib.rs`).
    arg: String,
    /// Git SHA to pin to (time-travel). Omit for the latest snapshot.
    #[serde(default)]
    sha: Option<String>,
    /// Max hits to return (default 50 for lookup, 100 for defined-in).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DwarfPathArgs {
    /// Repo (or `_workspace`) the DWARF snapshot was keyed to.
    repo: String,
    /// Source function (demangled name).
    from: String,
    /// Target function (demangled name).
    to: String,
    /// Git SHA to pin to (time-travel). Omit for the latest snapshot.
    #[serde(default)]
    sha: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct KnowledgeCallArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Function name (callee for callers, caller for callees).
    name: String,
    /// Max hits to return (default 100).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct KnowledgeCallPathArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Source function (matched by last path segment, e.g. `run_pipeline`).
    from: String,
    /// Target function (matched by last path segment, e.g. `commit`).
    to: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DocsHistoryArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Restrict to one document, e.g. "README".
    #[serde(default)]
    doc: Option<String>,
    /// Restrict to one version, e.g. "0.1.0".
    #[serde(default)]
    version: Option<String>,
    /// Restrict to one format: pdf | html | md.
    #[serde(default)]
    format: Option<String>,
    /// Max rows to return (default 50).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DocsBookArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Output format: pdf | html | md. Defaults to pdf. (md + pdf are the
    /// primary paths; html is typst's experimental HTML target.)
    #[serde(default)]
    format: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DocsExportArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Output format: pdf | html | md. Defaults to pdf.
    #[serde(default)]
    format: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelSubmitIdeaArgs {
    /// One-line description of the idea.
    text: String,
    /// Optional source/provenance tag (e.g. "agent:claude", "user").
    #[serde(default)]
    source: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelCreatePlanArgs {
    /// Idea id this plan refines, e.g. "i-002".
    idea_id: String,
    /// Short summary of the plan.
    summary: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelAddNodeArgs {
    /// Plan id, e.g. "p-002".
    plan_id: String,
    /// Verb/kind, e.g. "code:write", "test:run", "doc:update".
    kind: String,
    /// Optional human-readable title.
    #[serde(default)]
    title: Option<String>,
    /// Optional prompt/notes for the executor.
    #[serde(default)]
    prompt: Option<String>,
    /// Optional file/symbol targets the node will touch.
    #[serde(default)]
    targets: Vec<String>,
    /// Optional list of node-ids this node depends on (in same plan).
    #[serde(default)]
    needs: Vec<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelLinkArgs {
    /// Plan id both nodes belong to.
    plan_id: String,
    /// Predecessor node-id.
    from: String,
    /// Successor node-id (will gain `from` as a dependency).
    to: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelStatusArgs {
    /// Plan id, e.g. "p-002".
    plan_id: String,
    /// Node id, e.g. "n-013".
    node_id: String,
    /// One of: ready | active | blocked | done | abandoned.
    status: String,
    /// Optional reason (required when status=blocked or abandoned).
    #[serde(default)]
    why: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DepsOfArgs {
    /// Repo name as declared in the workspace descriptor / nornir.toml.
    repo: String,
    /// When true, return the full transitive closure instead of just
    /// direct neighbours. Defaults to false.
    #[serde(default)]
    transitive: bool,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct AffectedArgs {
    /// Repos that changed; the tool returns these plus everything that
    /// transitively depends on them, in build order.
    repos: Vec<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DepPathArgs {
    /// Source repo (the dependent).
    from: String,
    /// Target repo (the dependency) to reach via dependency edges.
    to: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct ExternalCrateArgs {
    /// External crate name, e.g. "serde".
    #[serde(rename = "crate")]
    krate: String,
}

#[tool_router]
impl NornirServer {
    async fn new(loaded: Loaded) -> Result<Self> {
        // Single source of truth shared with the CLI + server — see
        // `FunnelStore::resolve_root`: `NORNIR_FUNNEL_ROOT` (global override) >
        // config `[storage].local_path` > `<workspace_root>/.nornir/warehouse`.
        let funnel_root = FunnelStore::resolve_root(
            &loaded.workspace_root,
            &loaded.nornir.storage.local_path,
            None,
        );
        let funnel = FunnelStore::open_async(&funnel_root)
            .await
            .with_context(|| format!("open funnel warehouse at {}", funnel_root.display()))?;
        eprintln!(
            "funnel: {} ideas, {} plans loaded from {}",
            funnel.funnel.ideas.len(),
            funnel.funnel.plans.len(),
            funnel_root.display(),
        );
        // Per-call telemetry → warehouse `mcp_requests`, on a background thread.
        let (log_tx, log_rx) = tokio::sync::mpsc::unbounded_channel::<McpCall>();
        spawn_mcp_log_writer(loaded.warehouse_root(), log_rx);

        Ok(Self {
            state: Arc::new(Mutex::new(State {
                loaded,
                funnel,
                mimir: None,
                #[cfg(any(feature = "embed-tract", feature = "embed-ort"))]
                embedder: None,
            })),
            tool_router: Self::tool_router(),
            log_tx: Some(log_tx),
        })
    }

    #[tool(description = "Is a crate published on crates.io? Returns {published, max_version, \
                          versions_count, yanked_latest}. Use before depending on a crate (does it \
                          resolve for `cargo install` users?) or to check publish status after a \
                          release. Queries the sparse index directly; no cargo, no API key.")]
    async fn crate_published(
        &self,
        Parameters(args): Parameters<CratePublishedArgs>,
    ) -> Result<CallToolResult, McpError> {
        let name = args.name.to_lowercase();
        // crates.io sparse-index path scheme.
        let path = match name.len() {
            0 => return Err(internal("empty crate name")),
            1 => format!("1/{name}"),
            2 => format!("2/{name}"),
            3 => format!("3/{}/{name}", &name[..1]),
            _ => format!("{}/{}/{name}", &name[..2], &name[2..4]),
        };
        let url = format!("https://index.crates.io/{path}");
        let body = tokio::task::spawn_blocking(move || -> anyhow::Result<Option<String>> {
            match ureq::get(&url).call() {
                Ok(resp) => Ok(Some(resp.into_string()?)),
                Err(ureq::Error::Status(404, _)) => Ok(None),
                Err(e) => Err(e.into()),
            }
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        let Some(body) = body else {
            return ok_json(&serde_json::json!({ "name": name, "published": false }));
        };
        let mut versions = 0usize;
        let mut max_version = String::new();
        let mut yanked_latest = false;
        for line in body.lines().filter(|l| !l.trim().is_empty()) {
            if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
                versions += 1;
                if let Some(vers) = v.get("vers").and_then(|x| x.as_str()) {
                    max_version = vers.to_string();
                }
                yanked_latest = v.get("yanked").and_then(|x| x.as_bool()).unwrap_or(false);
            }
        }
        ok_json(&serde_json::json!({
            "name": name,
            "published": versions > 0,
            "max_version": max_version,
            "versions_count": versions,
            "yanked_latest": yanked_latest,
        }))
    }

    #[tool(description = "List repos declared in nornir.toml.")]
    async fn repos_list(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::repos_client::ReposClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.list(pb::Empty {}).await.map_err(internal)?.into_inner();
            let mut names: Vec<String> = resp.repos.into_iter().map(|r| r.name).collect();
            // Monitored workspaces keep their repos as registry *members*, not in
            // the (synthetic) config Repos.List reads — fall back to those.
            if names.is_empty() {
                if let Some(ws) = client_workspace() {
                    let (ch2, b2) = mcp_connect().await?;
                    let mut wc = pb::workspaces_client::WorkspacesClient::with_interceptor(ch2, mcp_auth(b2));
                    if let Ok(rec) = wc.get(pb::WorkspaceName { name: ws }).await {
                        names = rec.into_inner().members.into_iter().map(|m| m.name).collect();
                    }
                }
            }
            return ok_json(&names);
        }
        let s = self.state.lock().await;
        let names: Vec<String> = s.loaded.nornir.repo.keys().cloned().collect();
        ok_json(&names)
    }

    #[tool(
        description = "List the workspaces this MCP can target (server mode), plus the active one. \
                       One MCP serves every registered workspace — use `workspace_use` to switch \
                       without restarting."
    )]
    async fn workspaces_list(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c =
                pb::workspaces_client::WorkspacesClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.list(pb::Empty {}).await.map_err(internal)?.into_inner();
            let names: Vec<String> = resp.workspaces.into_iter().map(|w| w.name).collect();
            return ok_json(&serde_json::json!({ "active": client_workspace(), "workspaces": names }));
        }
        ok_json(&serde_json::json!({
            "active": client_workspace(),
            "note": "embedded mode (no NORNIR_SERVER) serves one workspace; set NORNIR_SERVER for multi-workspace switching",
        }))
    }

    #[tool(
        description = "Switch the active workspace for subsequent tool calls (server mode) — no \
                       restart. Every repos_list / deps_of / search / repo_overview / … then targets \
                       <name>. Closes the multi-workspace gap: one MCP serves knut, korp, znippy, \
                       skade, … without relaunching. Empty name clears the override."
    )]
    async fn workspace_use(
        &self,
        Parameters(args): Parameters<WorkspaceUseArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() && !args.name.is_empty() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c =
                pb::workspaces_client::WorkspacesClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.list(pb::Empty {}).await.map_err(internal)?.into_inner();
            let known: Vec<String> = resp.workspaces.into_iter().map(|w| w.name).collect();
            if !known.contains(&args.name) {
                return Err(internal(format!("unknown workspace `{}`; known: {known:?}", args.name)));
            }
        }
        set_active_workspace(&args.name);
        // The cached embedded graph was built for the previous workspace.
        self.state.lock().await.mimir = None;
        ok_json(&serde_json::json!({ "active": client_workspace() }))
    }

    #[tool(
        description = "Register a workspace so nornir starts tracking its git members + rebuilding \
                       the warehouse on change (server mode). `descriptor` = a server-readable path \
                       to the workspace's nornir-workspace.toml. `mode` defaults to `monitored` \
                       (polled). The single biggest agent write-side gap, closed."
    )]
    async fn workspace_register(
        &self,
        Parameters(args): Parameters<WorkspaceRegisterArgs>,
    ) -> Result<CallToolResult, McpError> {
        let (channel, bearer) = mcp_connect().await?;
        let mut c =
            pb::workspaces_client::WorkspacesClient::with_interceptor(channel, mcp_auth(bearer));
        let mode = if args.mode.is_empty() { "monitored".to_string() } else { args.mode };
        let rec = c
            .register(pb::RegisterWorkspaceRequest {
                name: args.name,
                descriptor: args.descriptor,
                mode,
                poll: args.poll,
            })
            .await
            .map_err(internal)?
            .into_inner();
        ok_json(&serde_json::json!({
            "registered": rec.name,
            "mode": rec.mode,
            "members": rec.members.into_iter().map(|m| m.name).collect::<Vec<_>>(),
        }))
    }

    #[tool(
        description = "Push-to-rebuild: force an immediate git fetch + warehouse republish for a \
                       workspace right now, without waiting for the poll loop. Returns what changed \
                       + the new snapshot. `workspace` empty = the active one. Use after you push."
    )]
    async fn sync_now(
        &self,
        Parameters(args): Parameters<WorkspaceOpt>,
    ) -> Result<CallToolResult, McpError> {
        let name = if args.workspace.is_empty() { client_workspace().unwrap_or_default() } else { args.workspace };
        let (channel, bearer) = mcp_connect().await?;
        let mut c =
            pb::workspaces_client::WorkspacesClient::with_interceptor(channel, mcp_auth(bearer));
        let rep = c
            .fetch(pb::WorkspaceFetchRequest { name: name.clone(), force: true })
            .await
            .map_err(internal)?
            .into_inner();
        ok_json(&serde_json::json!({
            "workspace": name,
            "fetched": rep.fetched,
            "changed": rep.changed,
            "snapshot": rep.snapshot,
            "errors": rep.errors,
        }))
    }

    #[tool(
        description = "Index/freshness status: the workspace's current warehouse snapshot + each git \
                       member's last-seen SHA, last-synced time, and sync state — so an agent can tell \
                       whether the cached knowledge is fresh before relying on it. `workspace` empty = \
                       the active one."
    )]
    async fn index_status(
        &self,
        Parameters(args): Parameters<WorkspaceOpt>,
    ) -> Result<CallToolResult, McpError> {
        let name = if args.workspace.is_empty() { client_workspace().unwrap_or_default() } else { args.workspace };
        let (channel, bearer) = mcp_connect().await?;
        let mut c =
            pb::workspaces_client::WorkspacesClient::with_interceptor(channel, mcp_auth(bearer));
        let rec = c.get(pb::WorkspaceName { name: name.clone() }).await.map_err(internal)?.into_inner();
        ok_json(&serde_json::json!({
            "workspace": rec.name,
            "current_snapshot": rec.current_snapshot,
            "updated_at": rec.updated_at,
            "members": rec.members.into_iter().map(|m| serde_json::json!({
                "name": m.name,
                "last_seen_sha": m.last_seen_sha,
                "last_synced": m.last_synced,
                "sync_state": m.sync_state,
            })).collect::<Vec<_>>(),
        }))
    }

    #[tool(
        description = "Dependency Mímir: cross-repo dependencies of <repo> (repos it depends on). \
                       transitive=false (default) returns direct edges with the crate names that justify \
                       each (`via`); transitive=true returns the full forward closure as repo names. \
                       Lets a model ask 'what does X build on?' without reasoning over the whole graph."
    )]
    async fn deps_of(
        &self,
        Parameters(args): Parameters<DepsOfArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.deps_of(pb::DepQuery { repo: args.repo.clone(), transitive: args.transitive })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let v = nornir::mimir::deps_of(&mimir.graph, &args.repo, args.transitive).map_err(internal)?;
        ok_json(&v)
    }

    #[tool(
        description = "Dependency Mímir: cross-repo dependents of <repo> (repos that depend ON it) — \
                       the BLAST RADIUS of changing <repo>. transitive=false (default) returns direct \
                       dependents with the `via` crates; transitive=true returns the full reverse closure. \
                       Headline tool for 'if I touch X, what must I re-validate?'."
    )]
    async fn dependents_of(
        &self,
        Parameters(args): Parameters<DepsOfArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.dependents_of(pb::DepQuery { repo: args.repo.clone(), transitive: args.transitive })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let v = nornir::mimir::dependents_of(&mimir.graph, &args.repo, args.transitive).map_err(internal)?;
        ok_json(&v)
    }

    #[tool(
        description = "Dependency Mímir: given a set of changed repos, return the invalidation set — \
                       the changed repos plus everything that transitively depends on them — in build \
                       order (dependencies first). This is exactly what a release/bench run must re-check."
    )]
    async fn affected_by_change(
        &self,
        Parameters(args): Parameters<AffectedArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.affected_by_change(pb::AffectedQuery { repos: args.repos.clone() })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let v = nornir::mimir::affected_by_change(&mimir.graph, &args.repos).map_err(internal)?;
        ok_json(&v)
    }

    #[tool(
        description = "Dependency Mímir: full workspace build order (dependencies before dependents). \
                       Errors if the cross-repo graph contains a cycle."
    )]
    async fn build_order(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.build_order(pb::Empty {}).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let v = nornir::mimir::build_order(&mimir.graph).map_err(internal)?;
        ok_json(&v)
    }

    #[tool(description = "One-shot repo orientation for an agent: <repo>'s internal dependencies + dependents (with the crates that justify each edge), its build-order position, and a knowledge digest (symbol + call-edge counts, a sample of symbol names) when a syn scan has been persisted. Lets a small/local model get its bearings in ONE call instead of orchestrating deps_of/build_order/knowledge_* separately.")]
    async fn repo_overview(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.repo_overview(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let warehouse_root = {
            let s = self.state.lock().await;
            s.loaded.warehouse_root()
        };
        let repo = args.repo.clone();
        let value = tokio::task::spawn_blocking(move || -> anyhow::Result<serde_json::Value> {
            let wh = IcebergWarehouse::open(&warehouse_root)?;
            nornir::mimir::repo_overview(&mimir.graph, &wh, &repo)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&value)
    }

    #[tool(
        description = "Dependency Mímir: shortest dependency path from <from> to <to> (following \
                       dependency edges), annotated with the crate names (`via`) that justify each hop. \
                       Answers 'why does from depend on to?'. Returns null path if to is not reachable."
    )]
    async fn dep_path(
        &self,
        Parameters(args): Parameters<DepPathArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.dep_path(pb::DepPathQuery { from: args.from.clone(), to: args.to.clone() })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let v = nornir::mimir::dep_path(&mimir.graph, &args.from, &args.to).map_err(internal)?;
        ok_json(&v)
    }

    #[tool(
        description = "Dependency Mímir: workspace repos that consume external crate <crate> \
                       (crates not produced by any repo in the workspace). Answers 'who uses serde?'."
    )]
    async fn external_dep_users(
        &self,
        Parameters(args): Parameters<ExternalCrateArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.external_dep_users(pb::CrateQuery { krate: args.krate.clone() })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        ok_json(&nornir::mimir::external_dep_users(&mimir.graph, &args.krate))
    }

    #[tool(
        description = "Dependency Mímir: render the cross-repo dependency graph as a Mermaid \
                       flowchart (edges labelled with the justifying crate names). Useful for a \
                       human/agent to visualise the whole workspace at once."
    )]
    async fn dep_graph_mermaid(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.mermaid(pb::Empty {}).await.map_err(internal)?.into_inner();
            return Ok(CallToolResult::success(vec![Content::text(r.json)]));
        }
        let mimir = self.mimir().await?;
        Ok(CallToolResult::success(vec![Content::text(nornir::mimir::mermaid(&mimir.graph))]))
    }

    #[tool(
        description = "Dependency Mímir (Urðr↔Verðandi diff): compare each repo's current HEAD against \
                       the SHA nornir last recorded as released, then expand the moved repos through the \
                       dependency graph into the build-ordered re-run set. One call answers 'what moved \
                       and what must I therefore re-validate?'. All git reads are in-process (gix)."
    )]
    async fn changed_since_last_release(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.changed_since_last_release(pb::Empty {}).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let mimir = self.mimir().await?;
        let warehouse_root = {
            let s = self.state.lock().await;
            s.loaded.warehouse_root()
        };
        let wh = IcebergWarehouse::open(&warehouse_root)
            .with_context(|| format!("open warehouse at {}", warehouse_root.display()))
            .map_err(internal)?;
        let change = change::detect(&wh, &mimir.graph, &mimir.workspace_name)
            .await
            .map_err(internal)?;
        ok_json(&change)
    }

    #[tool(description = "Regression time-bisect (deterministic, no AI): for <repo>, scan the \
        recorded release history and return the last GREEN release, the first RED one (the gate's \
        last-good → first-bad boundary), the suspect commit range, and the full oldest→newest \
        timeline. Reuses release_lineage; the backward-looking inverse of the no_regression gate. \
        Optional `workspace` restricts the scan (empty = every workspace).")]
    async fn regression_trace(
        &self,
        Parameters(args): Parameters<RegressionTraceArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.trace(pb::TraceQuery { repo: args.repo.clone(), workspace: args.workspace.clone() })
                .await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        // Best-effort dependency graph (cached MimirCtx) for suspect ranking.
        let mimir = self.mimir().await.ok();
        let warehouse_root = {
            let s = self.state.lock().await;
            s.loaded.warehouse_root()
        };
        let wh = IcebergWarehouse::open(&warehouse_root)
            .with_context(|| format!("open warehouse at {}", warehouse_root.display()))
            .map_err(internal)?;
        let graph = mimir.as_ref().map(|m| &m.graph);
        let trace =
            nornir::release::regression::trace_gate_async(&wh, &args.workspace, &args.repo, graph)
                .await
                .map_err(internal)?;
        ok_json(&trace)
    }

    #[tool(
        description = "Semantic (vector) code search. Embeds the query with jina-v2-base-code and \
            searches the repo's materialized embeddings in the warehouse — works at any historical \
            git SHA (time-travel) with no re-embed or git walk. The repo must have been vectorized \
            first via `nornir vector index <repo>`. Returns ranked {file, span, score} hits. \
            (Requires the server built with `--features embed-tract` or `embed-ort`.)"
    )]
    async fn vector_search(
        &self,
        Parameters(args): Parameters<VectorSearchArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Client mode: the server embeds + scans (it must carry an embedder).
        // Relayed regardless of whether THIS binary has an embedder feature.
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::vector_client::VectorClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c
                .search(pb::VectorSearchRequest {
                    repo: args.repo.clone(),
                    query: args.query.clone(),
                    sha: args.sha.clone(),
                    limit: args.limit.unwrap_or(0) as u32,
                })
                .await
                .map_err(internal)?
                .into_inner();
            return Ok(CallToolResult::success(vec![Content::text(resp.json)]));
        }
        #[cfg(any(feature = "embed-tract", feature = "embed-ort"))]
        {
            let embedder = self.embedder().await?;
            let warehouse_root = {
                let s = self.state.lock().await;
                s.loaded.warehouse_root()
            };
            let repo = args.repo.clone();
            let query = args.query.clone();
            let sha = args.sha.clone();
            let limit = args.limit.unwrap_or(10);
            // The embedder forward + warehouse scan both block (and the store
            // drives its own runtime via block_on), so run off the async
            // worker thread to avoid "runtime within a runtime".
            let hits = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
                let mp = embedder.profile().id();
                let q = embedder.embed(std::slice::from_ref(&query))?;
                let wh = IcebergWarehouse::open(&warehouse_root).with_context(|| {
                    format!("open warehouse at {}", warehouse_root.display())
                })?;
                let sha = (!sha.is_empty()).then_some(sha.as_str());
                nornir::vector::store::search(&wh, &repo, sha, &mp, &q[0], limit)
            })
            .await
            .map_err(internal)?
            .map_err(internal)?;
            let out: Vec<_> = hits
                .iter()
                .map(|(score, o)| {
                    json!({
                        "score": score,
                        "file": o.file,
                        "start_line": o.start_line,
                        "end_line": o.end_line,
                    })
                })
                .collect();
            ok_json(&json!({ "repo": args.repo, "hits": out }))
        }
        #[cfg(not(any(feature = "embed-tract", feature = "embed-ort")))]
        {
            let _ = args;
            Err(internal(anyhow::anyhow!(
                "this nornir-mcp was built without an embedder: rebuild with \
                 `--features mcp,embed-tract` (CPU) or `--features mcp,embed-ort` (GPU)"
            )))
        }
    }


    #[tool(description = "Guard: report writable state of every [guard].forbidden path.")]
    async fn guard_status(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::guard_client::GuardClient::with_interceptor(channel, mcp_auth(bearer));
            let report = c.status(pb::Empty {}).await.map_err(internal)?.into_inner();
            return Ok(CallToolResult::success(vec![Content::text(pb_guard_text(&report))]));
        }
        let s = self.state.lock().await;
        let report = guard::status(&s.loaded.workspace_root, &s.loaded.nornir.guard.forbidden);
        Ok(CallToolResult::success(vec![Content::text(format_status(&report))]))
    }

    #[tool(description = "Guard: chmod -w every [guard].forbidden path that exists, then record a \
        tamper-evidence manifest (sha256 + mode per path) and export guard-policy.json. \
        The manifest makes later drift non-deniable; verify it with guard_verify.")]
    async fn guard_apply(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::guard_client::GuardClient::with_interceptor(channel, mcp_auth(bearer));
            let report = c.apply(pb::Empty {}).await.map_err(internal)?.into_inner();
            return Ok(CallToolResult::success(vec![Content::text(pb_guard_text(&report))]));
        }
        let s = self.state.lock().await;
        let report = guard::apply_and_record(&s.loaded.workspace_root, &s.loaded.nornir.guard.forbidden)
            .map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format_status(&report))]))
    }

    #[tool(description = "Guard: verify every [guard].forbidden path against the manifest recorded by \
        guard_apply. Reports per-path drift (vanished/appeared/mode/content). This is the \
        tamper-evidence read; it never modifies the tree. Run guard_apply first to seed the manifest.")]
    async fn guard_verify(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::guard_client::GuardClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.verify(pb::Empty {}).await.map_err(internal)?.into_inner();
            let paths: serde_json::Value =
                serde_json::from_str(&r.paths_json).unwrap_or_else(|_| json!([]));
            return ok_json(&json!({
                "intact": r.intact, "recorded_at": r.recorded_at, "paths": paths,
            }));
        }
        let s = self.state.lock().await;
        let recorded = guard::read_manifest(&s.loaded.workspace_root).map_err(internal)?;
        let report = guard::verify(&s.loaded.workspace_root, &recorded);
        let intact = report.iter().all(|v| v.ok());
        let body = json!({
            "intact": intact,
            "recorded_at": recorded.recorded_at,
            "paths": report,
        });
        ok_json(&body)
    }

    #[tool(description = "Bench: read bench_history.jsonl for <repo> (one BenchRun per line).")]
    async fn bench_history(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::bench_client::BenchClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.history(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            let runs: Vec<bench::BenchRun> = resp.runs.into_iter().map(pb_bench_run).collect();
            return ok_json(&runs);
        }
        let s = self.state.lock().await;
        let repo = s.loaded.nornir.repo.get(&args.repo).ok_or_else(|| {
            McpError::invalid_params(format!("no [repo.{}]", args.repo), None)
        })?;
        let history = config::Nornir::repo_dir(&s.loaded.workspace_root, &args.repo)
            .join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
        let runs = bench::history::read_all(&history).map_err(internal)?;
        let body = serde_json::to_string_pretty(&runs).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Release: run the no-path-patches gate against <repo>'s Cargo.toml.")]
    async fn release_gate_path_patches(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, mcp_auth(bearer));
            let g = c.gate_path_patches(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            return pb_gate_result(g);
        }
        let s = self.state.lock().await;
        let repo_root = config::Nornir::repo_dir(&s.loaded.workspace_root, &args.repo);
        release::gate::no_path_patches(&repo_root).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: no [patch.crates-io] znippy entries in {}",
            repo_root.display()
        ))]))
    }

    #[tool(description = "Release: nexus_floor gate — holger_ops_sec ≥ nexus_ops_sec for the latest BenchRun of <repo>.")]
    async fn release_gate_nexus_floor(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, mcp_auth(bearer));
            let g = c.gate_nexus_floor(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            return pb_gate_result(g);
        }
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let run = mcp_last_run(&root, repo).map_err(internal)?;
        release::gate::nexus_floor(&run).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: nexus_floor on v{}", run.version
        ))]))
    }

    #[tool(description = "Release: no_regression gate — compare latest BenchRun to same-machine history; fails if any metric drops > max_regression_pct.")]
    async fn release_gate_no_regression(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, mcp_auth(bearer));
            let g = c.gate_no_regression(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            return pb_gate_result(g);
        }
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let run = mcp_last_run(&root, repo).map_err(internal)?;
        let pct = if repo.gates.max_regression_pct > 0.0 { repo.gates.max_regression_pct } else { 10.0 };
        let hp = root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
        release::gate::no_regression(&run, &hp, pct).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: no_regression ≤{:.1}% on v{}", pct, run.version
        ))]))
    }

    #[tool(description = "Docs: scaffold `.nornir/` for <repo> (migrate any existing README.md/CHANGELOG.md into it).")]
    async fn docs_init(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::docs_client::DocsClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.init(pb::RepoOnly { repo: args.repo.clone() }).await.map_err(internal)?.into_inner();
            return ok_json(&json!({"repo": r.repo, "status": r.status, "artifacts": r.artifacts, "detail": r.detail}));
        }
        let s = self.state.lock().await;
        let (root, _) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let srcs = nornir::docs::init_repo(&layout).map_err(internal)?;
        let body = serde_json::json!({
            "repo": args.repo,
            "nornir_dir": layout.nornir_dir(),
            "sources": srcs,
        });
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&body).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Docs: render every managed doc for <repo> from .nornir/ (full rewrite, chmod-aware).")]
    async fn docs_render(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::docs_client::DocsClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.render(pb::RepoOnly { repo: args.repo.clone() }).await.map_err(internal)?.into_inner();
            return ok_json(&json!({"repo": r.repo, "status": r.status, "artifacts": r.artifacts, "detail": r.detail}));
        }
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let last = mcp_last_run(&root, repo).ok();
        let history = mcp_history(&root, repo);
        let ctx = nornir::docs::Ctx::new(&root, &s.loaded.workspace_root, last.as_ref())
            .with_history(&history);
        let reports = nornir::docs::render_all(&layout, &ctx).map_err(internal)?;
        let body = serde_json::json!({
            "repo": args.repo,
            "reports": reports.iter().map(|r| serde_json::json!({
                "output": r.output,
                "bytes": r.bytes,
                "changed": r.changed,
                "sections": r.sections,
            })).collect::<Vec<_>>(),
        });
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&body).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Docs: dry-run check that every artifact (README.md, CHANGELOG.md) matches its .nornir/ source.")]
    async fn docs_check(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::docs_client::DocsClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.check(pb::RepoOnly { repo: args.repo.clone() }).await.map_err(internal)?.into_inner();
            return if r.status == "ok" {
                Ok(CallToolResult::success(vec![Content::text(format!(
                    "ok: every doc in {} matches its source", args.repo
                ))]))
            } else {
                Err(internal(format!("docs drift in {}: {}", args.repo, r.detail)))
            };
        }
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let last = mcp_last_run(&root, repo).ok();
        let history = mcp_history(&root, repo);
        let ctx = nornir::docs::Ctx::new(&root, &s.loaded.workspace_root, last.as_ref())
            .with_history(&history);
        nornir::docs::render_check_all(&layout, &ctx).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: every doc in {} matches its source", args.repo
        ))]))
    }

    #[tool(description = "Docs: list historical exports recorded in .nornir/warehouse/docs/ (newest first). Optional filters: doc, version, format, limit.")]
    async fn docs_history(
        &self,
        Parameters(args): Parameters<DocsHistoryArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::docs_client::DocsClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.history(pb::DocsHistoryRequest {
                repo: args.repo.clone(),
                doc: args.doc.clone().unwrap_or_default(),
                version: args.version.clone().unwrap_or_default(),
                format: args.format.clone().unwrap_or_default(),
                limit: args.limit.unwrap_or(50) as u32,
            }).await.map_err(internal)?.into_inner();
            let rows: Vec<_> = r.entries.into_iter().map(|e| json!({
                "doc": e.doc, "version": e.version, "format": e.format,
                "path": e.path, "exported_at": e.exported_at, "size_bytes": e.size_bytes,
            })).collect();
            return ok_json(&json!({"repo": args.repo, "rows": rows}));
        }
        let warehouse_root = {
            let s = self.state.lock().await;
            // Validate the repo exists, then resolve the warehouse root.
            repo_ctx(&s, &args.repo).map_err(internal)?;
            s.loaded.warehouse_root()
        };
        let repo = args.repo.clone();
        let filter = nornir::docs::ExportFilter {
            doc_name: args.doc.clone(),
            version: args.version.clone(),
            format: args.format.clone(),
            limit: args.limit.or(Some(50)),
        };
        // Opening the warehouse drives its own runtime (block_on), so run off
        // the async worker thread to avoid "runtime within a runtime".
        let rows = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            let wh = IcebergWarehouse::open(&warehouse_root)?;
            nornir::docs::list_doc_exports(&wh, &repo, &filter)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        let body = serde_json::json!({
            "repo": args.repo,
            "rows": rows,
        });
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&body).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Docs: render the WHOLE doc set for <repo> — every .nornir/*.md plus non-generated <repo>/*.md — into one typst book (format: pdf | html | md, default pdf). Renders managed docs first, writes the current artifact to <repo>/docs/book.<ext>, and historizes it in the Iceberg doc_exports table under doc name 'book'. Requires the docs-export build feature.")]
    async fn docs_book(
        &self,
        Parameters(args): Parameters<DocsBookArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Client mode: the server renders (it must carry the docs-export feature).
        if server_target().is_some() {
            return mcp_docs_export_remote(&args.repo, args.format.as_deref(), true).await;
        }
        // The tool is always registered (the #[tool_router] macro references it
        // unconditionally); only the body needs the typst-backed `docs-export`
        // feature, so a lean MCP build still advertises it and returns a clear
        // error rather than failing to compile.
        #[cfg(not(feature = "docs-export"))]
        {
            let _ = (&args.repo, &args.format);
            return Err(internal(
                "nornir-mcp was built without the `docs-export` feature; \
                 rebuild with `--features mcp,docs-export` to use docs_book",
            ));
        }
        #[cfg(feature = "docs-export")]
        {
            // Gather everything owned under the lock, then drop it: render +
            // typst export + warehouse write are all blocking work and the
            // warehouse drives its own runtime, so do them off the async worker
            // thread (avoids "runtime within a runtime") and don't hold the
            // state mutex across the heavy CPU/IO.
            let (root, repo_name, workspace_root, warehouse_root, last, history) = {
                let s = self.state.lock().await;
                let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
                let last = mcp_last_run(&root, repo).ok();
                let history = mcp_history(&root, repo);
                (
                    root,
                    args.repo.clone(),
                    s.loaded.workspace_root.clone(),
                    s.loaded.warehouse_root(),
                    last,
                    history,
                )
            };
            let fmt_str = args.format.clone().unwrap_or_else(|| "pdf".to_string());

            let (out_path, nbytes, sources, record) =
                tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
                    let layout = nornir::docs::RepoLayout::new(&root);
                    let ctx = nornir::docs::Ctx::new(&root, &workspace_root, last.as_ref())
                        .with_history(&history);
                    // Render managed artifacts first so the book reflects the latest source.
                    nornir::docs::render_all(&layout, &ctx)?;

                    let format = nornir::docs::DocFormat::parse(&fmt_str)?;
                    let (bytes, sources) = nornir::docs::build_book(&root, &ctx, format)?;

                    let version = nornir::docs::resolve_version(&root);
                    let ext = format.extension();

                    // Current artifact → <repo>/docs/book.<ext> (live copy).
                    let out_path = layout.export_path("book", ext);
                    if let Some(parent) = out_path.parent() {
                        std::fs::create_dir_all(parent)?;
                    }
                    std::fs::write(&out_path, &bytes)?;

                    // History → iceberg `doc_exports` (inline bytes, dedup by sha256).
                    let workspace = workspace_root
                        .file_name()
                        .and_then(|x| x.to_str())
                        .unwrap_or("_workspace")
                        .to_string();
                    let git_sha =
                        nornir::gitio::head_sha(&root).unwrap_or_else(|_| "unknown".to_string());
                    let wh = IcebergWarehouse::open(&warehouse_root)?;
                    let record = nornir::docs::record_doc_export(
                        &wh, &workspace, &repo_name, "book", &version, ext, &git_sha, &bytes,
                    )?;
                    Ok((out_path, bytes.len(), sources, record))
                })
                .await
                .map_err(internal)?
                .map_err(internal)?;

            let body = serde_json::json!({
                "repo": args.repo,
                "format": args.format.as_deref().unwrap_or("pdf"),
                "sources": sources,
                "bytes": nbytes,
                "out": out_path,
                "sha256": record.sha256,
                "git_sha": record.git_sha,
                "export_id": record.export_id,
            });
            Ok(CallToolResult::success(vec![Content::text(
                serde_json::to_string_pretty(&body).unwrap_or_default(),
            )]))
        }
    }

    #[tool(description = "Docs: export the assembled README for <repo> to PDF/HTML/MD (format: pdf | html | md, default pdf). Renders managed docs first, writes the artifact to <repo>/docs/README.<ext>, and historizes it in the Iceberg doc_exports table under doc name 'README'. Single-doc counterpart to docs_book. Requires the docs-export build feature.")]
    async fn docs_export(
        &self,
        Parameters(args): Parameters<DocsExportArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Client mode: the server renders (it must carry the docs-export feature).
        if server_target().is_some() {
            return mcp_docs_export_remote(&args.repo, args.format.as_deref(), false).await;
        }
        // Tool is always registered (the #[tool_router] macro references it
        // unconditionally); only the body needs the typst-backed `docs-export`
        // feature, so a lean MCP build still advertises it and returns a clear
        // error rather than failing to compile.
        #[cfg(not(feature = "docs-export"))]
        {
            let _ = (&args.repo, &args.format);
            return Err(internal(
                "nornir-mcp was built without the `docs-export` feature; \
                 rebuild with `--features mcp,docs-export` to use docs_export",
            ));
        }
        #[cfg(feature = "docs-export")]
        {
            // Gather everything owned under the lock, then drop it: render +
            // typst export + warehouse write are blocking and the warehouse
            // drives its own runtime, so run off the async worker thread
            // (avoids "runtime within a runtime") without holding the mutex.
            let (root, repo_name, workspace_root, warehouse_root, last, history) = {
                let s = self.state.lock().await;
                let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
                let last = mcp_last_run(&root, repo).ok();
                let history = mcp_history(&root, repo);
                (
                    root,
                    args.repo.clone(),
                    s.loaded.workspace_root.clone(),
                    s.loaded.warehouse_root(),
                    last,
                    history,
                )
            };
            let fmt_str = args.format.clone().unwrap_or_else(|| "pdf".to_string());

            let (out_path, nbytes, record) =
                tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
                    let layout = nornir::docs::RepoLayout::new(&root);
                    let ctx = nornir::docs::Ctx::new(&root, &workspace_root, last.as_ref())
                        .with_history(&history);
                    // Render managed artifacts first so the export reflects latest source.
                    nornir::docs::render_all(&layout, &ctx)?;

                    let format = nornir::docs::DocFormat::parse(&fmt_str)?;
                    let bytes = nornir::docs::export_repo(&root, format)?;

                    let version = nornir::docs::resolve_version(&root);
                    let ext = format.extension();

                    // Current artifact → <repo>/docs/README.<ext> (live, link-target copy).
                    let out_path = layout.export_path("README", ext);
                    if let Some(parent) = out_path.parent() {
                        std::fs::create_dir_all(parent)?;
                    }
                    std::fs::write(&out_path, &bytes)?;

                    // History → iceberg `doc_exports` (inline bytes, dedup by sha256).
                    let workspace = workspace_root
                        .file_name()
                        .and_then(|x| x.to_str())
                        .unwrap_or("_workspace")
                        .to_string();
                    let git_sha =
                        nornir::gitio::head_sha(&root).unwrap_or_else(|_| "unknown".to_string());
                    let wh = IcebergWarehouse::open(&warehouse_root)?;
                    let record = nornir::docs::record_doc_export(
                        &wh, &workspace, &repo_name, "README", &version, ext, &git_sha, &bytes,
                    )?;
                    Ok((out_path, bytes.len(), record))
                })
                .await
                .map_err(internal)?
                .map_err(internal)?;

            let body = serde_json::json!({
                "repo": args.repo,
                "format": args.format.as_deref().unwrap_or("pdf"),
                "bytes": nbytes,
                "out": out_path,
                "sha256": record.sha256,
                "git_sha": record.git_sha,
                "export_id": record.export_id,
            });
            Ok(CallToolResult::success(vec![Content::text(
                serde_json::to_string_pretty(&body).unwrap_or_default(),
            )]))
        }
    }

    #[tool(description = "Release: docs_fresh gate — README.md generated sections must be in sync with latest BenchRun.")]
    async fn release_gate_docs_fresh(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, mcp_auth(bearer));
            let g = c.gate_docs_fresh(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            return pb_gate_result(g);
        }
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let run = mcp_last_run(&root, repo).map_err(internal)?;
        let history = mcp_history(&root, repo);
        let ctx = nornir::docs::Ctx::new(&root, &s.loaded.workspace_root, Some(&run))
            .with_history(&history);
        nornir::docs::render_check_all(&layout, &ctx).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: docs_fresh on {}", root.display()
        ))]))
    }

    #[tool(description = "Release: run every gate enabled in [repo.<name>.gates] for <repo>; returns JSON {passed:[...], failed:[{name,error}]}. Roundtrip invokes `cargo test --test roundtrip_<kind> --release` per configured kind.")]
    async fn release_gate_all(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.gate_all(pb::RepoOnly { repo: args.repo.clone() })
                .await.map_err(internal)?.into_inner();
            let failed: Vec<_> = r.failed.into_iter()
                .map(|f| json!({"name": f.name, "error": f.error})).collect();
            return ok_json(&json!({"repo": r.repo, "passed": r.passed, "failed": failed}));
        }
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let g = &repo.gates;
        let mut passed: Vec<String> = Vec::new();
        let mut failed: Vec<serde_json::Value> = Vec::new();
        macro_rules! push {
            ($n:expr, $r:expr) => {
                match $r {
                    Ok(()) => passed.push($n.into()),
                    Err(e) => failed.push(serde_json::json!({"name": $n, "error": format!("{e:#}")})),
                }
            };
        }
        if g.no_path_patches {
            push!("no_path_patches", release::gate::no_path_patches(&root));
        }
        let last = mcp_last_run(&root, repo);
        if g.nexus_floor {
            push!("nexus_floor", last.as_ref().map_err(|e| anyhow::anyhow!("{e:#}")).and_then(|r| release::gate::nexus_floor(r)));
        }
        if g.no_regression {
            let pct = if g.max_regression_pct > 0.0 { g.max_regression_pct } else { 10.0 };
            let hp = root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
            push!("no_regression",
                last.as_ref().map_err(|e| anyhow::anyhow!("{e:#}")).and_then(|r| release::gate::no_regression(r, &hp, pct)));
        }
        if !g.integration_roundtrip.is_empty() {
            let kinds: Vec<&str> = g.integration_roundtrip.iter().map(|s| s.as_str()).collect();
            push!("integration_roundtrip",
                nornir::release::gate::integration_roundtrip_via_cargo_test(&root, &kinds));
        }
        if g.docs_fresh {
            let r: anyhow::Result<()> = (|| {
                let run = last.as_ref().map_err(|e| anyhow::anyhow!("{e:#}"))?;
                let layout = nornir::docs::RepoLayout::new(&root);
                let history = mcp_history(&root, repo);
                let ctx = nornir::docs::Ctx::new(&root, &s.loaded.workspace_root, Some(run))
                    .with_history(&history);
                nornir::docs::render_check_all(&layout, &ctx)
            })();
            push!("docs_fresh", r);
        }
        if g.guard_intact {
            let r: anyhow::Result<()> = (|| {
                let recorded = guard::read_manifest(&s.loaded.workspace_root)?;
                guard::intact(&s.loaded.workspace_root, &recorded)
            })();
            push!("guard_intact", r);
        }
        let body = serde_json::json!({"repo": args.repo, "passed": passed, "failed": failed});
        Ok(CallToolResult::success(vec![Content::text(serde_json::to_string_pretty(&body).unwrap())]))
    }

    #[tool(description = "Full-text BM25 search over indexed corpora. \
        Run `nornir index build` first. Args: query (Tantivy syntax), \
        optional corpus (docs|code|bench_history|changelog|config), \
        optional repo (top-level workspace dir), optional limit.")]
    async fn search(
        &self,
        Parameters(args): Parameters<SearchArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::search_client::SearchClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c
                .query(pb::SearchRequest {
                    query: args.query.clone(),
                    corpus: args.corpus.clone().unwrap_or_default(),
                    repo: args.repo.clone().unwrap_or_default(),
                    limit: args.limit.unwrap_or(10) as u32,
                })
                .await
                .map_err(internal)?
                .into_inner();
            let hits: Vec<_> = resp
                .hits
                .into_iter()
                .map(|h| {
                    json!({
                        "id": h.id, "corpus": h.corpus, "repo": h.repo, "path": h.path,
                        "score": h.score, "snippet": h.snippet, "title": h.title,
                    })
                })
                .collect();
            return ok_json(&hits);
        }
        let s = self.state.lock().await;
        let idx = index::Index::open(&s.loaded.workspace_root).map_err(internal)?;
        let corpus = match args.corpus.as_deref() {
            None => None,
            Some(name) => Some(
                index::Corpus::parse(name)
                    .ok_or_else(|| McpError::invalid_params(format!("unknown corpus: {name}"), None))?,
            ),
        };
        let hits = idx
            .search(&args.query, corpus, args.repo.as_deref(), args.limit.unwrap_or(10))
            .map_err(internal)?;
        let body = serde_json::to_string_pretty(&hits).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF symbol lookup: extract every function symbol \
        from a built binary and filter by name substring. Returns JSON \
        array of {name, name_demangled, name_mangled, file, line, size_bytes, krate}. \
        `binary` may be relative to workspace root.")]
    async fn symbol_lookup(
        &self,
        Parameters(args): Parameters<SymbolLookupArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::introspect_client::IntrospectClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.symbol_lookup(pb::SymbolLookupRequest {
                binary: args.binary.clone(), pattern: args.pattern.clone(),
                limit: args.limit.unwrap_or(25) as u32,
            }).await.map_err(internal)?.into_inner();
            return ok_json(&pb_symbols_json(resp));
        }
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let syms = introspect::artifact::extract_symbols(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let hits: Vec<_> = introspect::artifact::lookup(&syms, &args.pattern)
            .into_iter()
            .take(args.limit.unwrap_or(25))
            .cloned()
            .collect();
        let body = serde_json::to_string_pretty(&hits).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF defined-in lookup: list every function symbol \
        defined in source files whose path ends with `file`. \
        `binary` may be relative to workspace root.")]
    async fn defined_in(
        &self,
        Parameters(args): Parameters<DefinedInArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::introspect_client::IntrospectClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.defined_in(pb::DefinedInRequest {
                binary: args.binary.clone(), suffix: args.file.clone(),
            }).await.map_err(internal)?.into_inner();
            return ok_json(&pb_symbols_json(resp));
        }
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let syms = introspect::artifact::extract_symbols(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let hits: Vec<_> = introspect::artifact::defined_in(&syms, &args.file)
            .into_iter()
            .take(args.limit.unwrap_or(100))
            .cloned()
            .collect();
        let body = serde_json::to_string_pretty(&hits).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF inline-callgraph: functions that call `name`. \
        Only inlined edges are visible at this layer — indirect calls (trait \
        objects, fn pointers) and non-inlined direct calls are NOT included. \
        Use demangled names with generics stripped (e.g. `nornir::index::Index::build`).")]
    async fn callers_of(
        &self,
        Parameters(args): Parameters<CallQueryArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::introspect_client::IntrospectClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.callers(pb::CallQuery { binary: args.binary.clone(), name: args.name.clone() })
                .await.map_err(internal)?.into_inner();
            return ok_json(&resp.names);
        }
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let edges = introspect::callgraph_dwarf::extract_callgraph(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
        let body = serde_json::to_string_pretty(&cg.callers_of(&args.name)).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF inline-callgraph: functions called by `name`. \
        Inlined edges only (see `callers_of` for caveats).")]
    async fn callees_of(
        &self,
        Parameters(args): Parameters<CallQueryArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::introspect_client::IntrospectClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.callees(pb::CallQuery { binary: args.binary.clone(), name: args.name.clone() })
                .await.map_err(internal)?.into_inner();
            return ok_json(&resp.names);
        }
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let edges = introspect::callgraph_dwarf::extract_callgraph(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
        let body = serde_json::to_string_pretty(&cg.callees_of(&args.name)).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF inline-callgraph: shortest call chain from `from` to `to` \
        (BFS over inlined edges). Returns the list of function names along the path, \
        or `null` when no path exists.")]
    async fn path_between(
        &self,
        Parameters(args): Parameters<PathBetweenArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::introspect_client::IntrospectClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.path_between(pb::PathBetweenRequest {
                binary: args.binary.clone(), from: args.from.clone(), to: args.to.clone(),
            }).await.map_err(internal)?.into_inner();
            // Empty names = no path; mirror the embedded `null`.
            let v = if resp.names.is_empty() { serde_json::Value::Null } else { json!(resp.names) };
            return ok_json(&v);
        }
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let edges = introspect::callgraph_dwarf::extract_callgraph(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
        let path = cg.path_between(&args.from, &args.to);
        let body = serde_json::to_string_pretty(&path).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    // ---------------- knowledge (syn symbol/call graph, no binary) --------

    #[tool(description = "Knowledge symbol lookup over the persisted syn graph: symbols in <repo> \
        whose item name contains `arg` (case-insensitive). Reads the latest `knowledge scan --persist` \
        snapshot from iceberg — no compiled binary needed (unlike DWARF symbol_lookup). Returns a JSON \
        array of {crate_name, module_path, item_kind, item_name, visibility, file, line, doc_lines, \
        signature}. Empty array if the repo has no persisted snapshot.")]
    async fn knowledge_symbol_lookup(
        &self,
        Parameters(args): Parameters<KnowledgeSymbolArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.symbol_lookup(pb::KnowledgeSymbolQuery {
                repo: args.repo.clone(), arg: args.arg.clone(), limit: args.limit.unwrap_or(50) as u32,
            }).await.map_err(internal)?.into_inner();
            return ok_json(&pb_knowledge_symbols_json(resp));
        }
        let limit = args.limit.unwrap_or(50);
        let body = self
            .knowledge_query_json(args.repo, move |view| {
                serde_json::to_string_pretty(&view.symbol_lookup(&args.arg, limit))
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Knowledge defined-in over the persisted syn graph: symbols in <repo> defined \
        in source files whose path ends with `arg`. Reads the latest persisted snapshot from iceberg — \
        no compiled binary needed. Returns the same JSON shape as knowledge_symbol_lookup.")]
    async fn knowledge_defined_in(
        &self,
        Parameters(args): Parameters<KnowledgeSymbolArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.defined_in(pb::KnowledgeSymbolQuery {
                repo: args.repo.clone(), arg: args.arg.clone(), limit: args.limit.unwrap_or(100) as u32,
            }).await.map_err(internal)?.into_inner();
            return ok_json(&pb_knowledge_symbols_json(resp));
        }
        let limit = args.limit.unwrap_or(100);
        let body = self
            .knowledge_query_json(args.repo, move |view| {
                let hits: Vec<_> = view.defined_in(&args.arg).into_iter().take(limit).collect();
                serde_json::to_string_pretty(&hits)
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Knowledge callers over the persisted syn graph: call edges in <repo> that \
        invoke `name` — matches a bare callee or any path-qualified callee whose last segment is \
        `name` (a query of `new` finds `Arc::new`, `Foo::new`). Reads the latest persisted snapshot \
        from iceberg — no compiled binary needed (unlike DWARF callers_of). Returns a JSON array of \
        {crate_name, caller_path, callee_ident, call_kind, file, line}.")]
    async fn knowledge_callers(
        &self,
        Parameters(args): Parameters<KnowledgeCallArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.callers(pb::KnowledgeCallQuery {
                repo: args.repo.clone(), name: args.name.clone(), limit: args.limit.unwrap_or(100) as u32,
            }).await.map_err(internal)?.into_inner();
            return ok_json(&pb_knowledge_calls_json(resp));
        }
        let limit = args.limit.unwrap_or(100);
        let body = self
            .knowledge_query_json(args.repo, move |view| {
                let hits: Vec<_> = view.callers_of(&args.name).into_iter().take(limit).collect();
                serde_json::to_string_pretty(&hits)
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Knowledge callees over the persisted syn graph: call edges in <repo> emitted \
        from a caller whose path ends with `name`. Reads the latest persisted snapshot from iceberg — \
        no compiled binary needed. Returns the same JSON shape as knowledge_callers.")]
    async fn knowledge_callees(
        &self,
        Parameters(args): Parameters<KnowledgeCallArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.callees(pb::KnowledgeCallQuery {
                repo: args.repo.clone(), name: args.name.clone(), limit: args.limit.unwrap_or(100) as u32,
            }).await.map_err(internal)?.into_inner();
            return ok_json(&pb_knowledge_calls_json(resp));
        }
        let limit = args.limit.unwrap_or(100);
        let body = self
            .knowledge_query_json(args.repo, move |view| {
                let hits: Vec<_> = view.callees_of(&args.name).into_iter().take(limit).collect();
                serde_json::to_string_pretty(&hits)
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Knowledge call-path over the persisted syn graph: shortest call chain in \
        <repo> from `from` to `to` (BFS over call edges, following caller→callee). Both ends match by \
        last path segment, so `run_pipeline`→`commit` finds a chain through `Repo::commit`. Reads the \
        latest persisted snapshot from iceberg — no compiled binary needed (unlike DWARF path_between). \
        Returns a JSON array of identifiers along the path, or `null` when unreachable. Approximate: \
        syn callees are idents, not resolved defining paths, so same-named functions collapse.")]
    async fn knowledge_call_path(
        &self,
        Parameters(args): Parameters<KnowledgeCallPathArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, mcp_auth(bearer));
            let resp = c.call_path(pb::KnowledgeCallPathQuery {
                repo: args.repo.clone(), from: args.from.clone(), to: args.to.clone(),
            }).await.map_err(internal)?.into_inner();
            let v = if resp.names.is_empty() { serde_json::Value::Null } else { json!(resp.names) };
            return ok_json(&v);
        }
        let body = self
            .knowledge_query_json(args.repo, move |view| {
                serde_json::to_string_pretty(&view.call_path(&args.from, &args.to))
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF symbol lookup over the PERSISTED warehouse facts (no binary needed): function symbols for <repo> (or `_workspace`) whose demangled name contains `arg`, at the latest dwarf snapshot or the one pinned by `sha` (time-travel). Airgapped read of the historized dwarf_* tables — populate them with `introspect symbols --persist [--repo X]`.")]
    async fn dwarf_symbol_lookup(
        &self,
        Parameters(args): Parameters<DwarfStoredArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::dwarf_client::DwarfClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.symbol_lookup(pb::DwarfQuery {
                repo: args.repo.clone(), arg: args.arg.clone(),
                sha: args.sha.clone().unwrap_or_default(), limit: args.limit.unwrap_or(0) as u32,
            }).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let arg = args.arg.clone();
        let limit = args.limit.unwrap_or(50);
        let body = self
            .dwarf_load_json(args.repo, args.sha, move |facts| {
                let hits: Vec<_> = facts.lookup(&arg).into_iter().take(limit).collect();
                serde_json::to_string_pretty(&hits)
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF defined-in over the PERSISTED warehouse facts (no binary needed): function symbols for <repo> (or `_workspace`) defined in a source file whose path ends with `arg` (e.g. `bar.rs`), at the latest dwarf snapshot or the one pinned by `sha`. Reads the historized dwarf_* tables — populate via `introspect symbols --persist`.")]
    async fn dwarf_defined_in(
        &self,
        Parameters(args): Parameters<DwarfStoredArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::dwarf_client::DwarfClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.defined_in(pb::DwarfQuery {
                repo: args.repo.clone(), arg: args.arg.clone(),
                sha: args.sha.clone().unwrap_or_default(), limit: args.limit.unwrap_or(0) as u32,
            }).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let arg = args.arg.clone();
        let limit = args.limit.unwrap_or(100);
        let body = self
            .dwarf_load_json(args.repo, args.sha, move |facts| {
                let hits: Vec<_> = facts.defined_in(&arg).into_iter().take(limit).collect();
                serde_json::to_string_pretty(&hits)
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF callers over the PERSISTED warehouse facts (no binary needed): functions that call `arg` in <repo>, from the historized inline-call edges at the latest dwarf snapshot or the one pinned by `sha`. Inlined edges only. Populate via `introspect symbols --persist`.")]
    async fn dwarf_callers(
        &self,
        Parameters(args): Parameters<DwarfStoredArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::dwarf_client::DwarfClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.callers(pb::DwarfQuery {
                repo: args.repo.clone(), arg: args.arg.clone(),
                sha: args.sha.clone().unwrap_or_default(), limit: 0,
            }).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let arg = args.arg.clone();
        let body = self
            .dwarf_load_json(args.repo, args.sha, move |facts| {
                serde_json::to_string_pretty(&facts.callers_of(&arg))
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF callees over the PERSISTED warehouse facts (no binary needed): functions called by `arg` in <repo>, from the historized inline-call edges at the latest dwarf snapshot or the one pinned by `sha`. Inlined edges only.")]
    async fn dwarf_callees(
        &self,
        Parameters(args): Parameters<DwarfStoredArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::dwarf_client::DwarfClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.callees(pb::DwarfQuery {
                repo: args.repo.clone(), arg: args.arg.clone(),
                sha: args.sha.clone().unwrap_or_default(), limit: 0,
            }).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let arg = args.arg.clone();
        let body = self
            .dwarf_load_json(args.repo, args.sha, move |facts| {
                serde_json::to_string_pretty(&facts.callees_of(&arg))
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF call-path over the PERSISTED warehouse facts (no binary needed): shortest inline-call chain `from` → `to` in <repo> at the latest dwarf snapshot or the one pinned by `sha`. Returns the function-name path, or null if none.")]
    async fn dwarf_call_path(
        &self,
        Parameters(args): Parameters<DwarfPathArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::dwarf_client::DwarfClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.call_path(pb::DwarfPathQuery {
                repo: args.repo.clone(), from: args.from.clone(), to: args.to.clone(),
                sha: args.sha.clone().unwrap_or_default(),
            }).await.map_err(internal)?.into_inner();
            return mimir_emit(&r.json);
        }
        let from = args.from.clone();
        let to = args.to.clone();
        let body = self
            .dwarf_load_json(args.repo, args.sha, move |facts| {
                serde_json::to_string_pretty(&facts.call_path(&from, &to))
            })
            .await?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    // ---------------- funnel (idea -> plan -> node -> run) ----------------

    #[tool(description = "Submit a new idea into the intake funnel. Returns the assigned idea id (e.g. \"i-007\"). Use this when the user or agent surfaces something worth doing but the work hasn't been planned yet.")]
    async fn funnel_submit_idea(
        &self,
        Parameters(args): Parameters<FunnelSubmitIdeaArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.submit_idea(pb::SubmitIdeaRequest {
                text: args.text.clone(),
                source: args.source.clone().unwrap_or_else(|| "mcp".into()),
            }).await.map_err(internal)?.into_inner();
            return Ok(CallToolResult::success(vec![Content::text(r.id)]));
        }
        let mut s = self.state.lock().await;
        let id = IdeaId::seq(s.funnel.funnel.next_idea);
        let ev = FunnelEvent::IdeaSubmitted {
            id: id.clone(),
            source: args.source.unwrap_or_else(|| "mcp".into()),
            text: args.text,
            refs: Vec::new(),
            ts: Utc::now(),
        };
        s.funnel.record_async(ev).await.map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(id.as_str().to_string())]))
    }

    #[tool(description = "Create a plan that refines an existing idea into executable nodes. Auto-activates the plan. Returns the new plan id (e.g. \"p-003\"). Add nodes with funnel_add_node + funnel_link.")]
    async fn funnel_create_plan(
        &self,
        Parameters(args): Parameters<FunnelCreatePlanArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.create_plan(pb::CreatePlanRequest {
                idea_id: args.idea_id.clone(),
                summary: args.summary.clone(),
            }).await.map_err(internal)?.into_inner();
            return Ok(CallToolResult::success(vec![Content::text(r.id)]));
        }
        let mut s = self.state.lock().await;
        let plan_id = PlanId::seq(s.funnel.funnel.next_plan);
        let now = Utc::now();
        s.funnel.record_async(FunnelEvent::PlanCreated {
                id: plan_id.clone(),
                idea_id: IdeaId::new(args.idea_id),
                summary: args.summary,
                planner: "mcp".into(),
                ts: now,
            }).await.map_err(internal)?;
        s.funnel.record_async(FunnelEvent::PlanStatusChanged {
                plan_id: plan_id.clone(),
                status: PlanStatus::Active,
                why: None,
                ts: Utc::now(),
            }).await.map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(plan_id.as_str().to_string())]))
    }

    #[tool(description = "Add a node to a plan. `kind` is a free verb like \"code:write\", \"test:run\", \"doc:update\". Optionally pass `needs` (other node-ids in the same plan) to wire up dependencies in a single call. Returns the new node id (e.g. \"n-042\").")]
    async fn funnel_add_node(
        &self,
        Parameters(args): Parameters<FunnelAddNodeArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.add_node(pb::AddNodeRequest {
                plan_id: args.plan_id.clone(),
                kind: args.kind.clone(),
                title: args.title.clone().unwrap_or_default(),
                prompt: args.prompt.clone().unwrap_or_default(),
                targets: args.targets.clone(),
                needs: args.needs.clone(),
            }).await.map_err(internal)?.into_inner();
            return Ok(CallToolResult::success(vec![Content::text(r.id)]));
        }
        let mut s = self.state.lock().await;
        let plan_id = PlanId::new(args.plan_id);
        let node_id = NodeId::seq(s.funnel.funnel.next_node);
        let now = Utc::now();
        let mut params = serde_json::Map::new();
        if let Some(t) = args.title {
            params.insert("title".into(), serde_json::Value::String(t));
        }
        s.funnel.record_async(FunnelEvent::NodeAdded {
                plan_id: plan_id.clone(),
                node_id: node_id.clone(),
                kind: args.kind,
                params,
                targets: args.targets,
                prompt_excerpt: args.prompt,
                ts: now,
            }).await.map_err(internal)?;
        for from in &args.needs {
            s.funnel.record_async(FunnelEvent::EdgeAdded {
                    plan_id: plan_id.clone(),
                    from_node: NodeId::new(from.clone()),
                    to_node: node_id.clone(),
                    ts: Utc::now(),
                }).await.map_err(internal)?;
        }
        s.funnel.funnel.promote_ready();
        Ok(CallToolResult::success(vec![Content::text(node_id.as_str().to_string())]))
    }

    #[tool(description = "Add a dependency edge: node `to` will only become ready once node `from` is done. Both must belong to the same plan.")]
    async fn funnel_link(
        &self,
        Parameters(args): Parameters<FunnelLinkArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            c.link(pb::LinkRequest {
                plan_id: args.plan_id.clone(),
                from: args.from.clone(),
                to: args.to.clone(),
            }).await.map_err(internal)?;
            return Ok(CallToolResult::success(vec![Content::text("ok".to_string())]));
        }
        let mut s = self.state.lock().await;
        s.funnel.record_async(FunnelEvent::EdgeAdded {
                plan_id: PlanId::new(args.plan_id),
                from_node: NodeId::new(args.from),
                to_node: NodeId::new(args.to),
                ts: Utc::now(),
            }).await.map_err(internal)?;
        s.funnel.funnel.promote_ready();
        Ok(CallToolResult::success(vec![Content::text("ok".to_string())]))
    }

    #[tool(description = "What should the agent work on next? Returns a JSON array of ready PlanNodes (all deps satisfied) across every active plan, in stable topo order. Empty array = nothing ready (either all done, all blocked, or no active plans). Call this whenever your context resets.")]
    async fn funnel_next(&self) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            let r = c.next(pb::Empty {}).await.map_err(internal)?.into_inner();
            // Re-emit the SAME shape the embedded path produces (topo::NextStep).
            let steps: Vec<_> = r.steps.into_iter().map(|s| json!({
                "plan_id": s.plan_id,
                "node_id": s.node_id,
                "kind": s.kind,
                "targets": s.targets,
                "summary": s.summary,
                "prompt_excerpt": (!s.prompt.is_empty()).then_some(s.prompt),
            })).collect();
            return ok_json(&steps);
        }
        let mut s = self.state.lock().await;
        s.funnel.funnel.promote_ready();
        let next = topo_ready(&mut s.funnel.funnel);
        let body = serde_json::to_string_pretty(&next).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Flip a node's status. `status` is one of: ready, active, blocked, done, abandoned. Pass `why` when blocking or abandoning. Use `done` after the actual work lands; the funnel will unblock dependents automatically on the next funnel_next call.")]
    async fn funnel_status(
        &self,
        Parameters(args): Parameters<FunnelStatusArgs>,
    ) -> Result<CallToolResult, McpError> {
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            c.set_status(pb::SetStatusRequest {
                plan_id: args.plan_id.clone(),
                node_id: args.node_id.clone(),
                status: args.status.clone(),
                why: args.why.clone().unwrap_or_default(),
            }).await.map_err(internal)?;
            return Ok(CallToolResult::success(vec![Content::text("ok".to_string())]));
        }
        let status = match args.status.as_str() {
            "ready" => NodeStatus::Ready,
            "active" | "in_progress" => NodeStatus::InProgress,
            "blocked" => NodeStatus::Blocked,
            "done" => NodeStatus::Done,
            "failed" => NodeStatus::Failed,
            "abandoned" => NodeStatus::Failed, // closest legal status
            other => {
                return Err(McpError::invalid_params(
                    format!("unknown status {other:?}; expected ready|active|blocked|done|failed"),
                    None,
                ));
            }
        };
        let mut s = self.state.lock().await;
        s.funnel.record_async(FunnelEvent::NodeStatusChanged {
                plan_id: PlanId::new(args.plan_id),
                node_id: NodeId::new(args.node_id),
                status,
                why: args.why,
                ts: Utc::now(),
            }).await.map_err(internal)?;
        s.funnel.funnel.promote_ready();
        Ok(CallToolResult::success(vec![Content::text("ok".to_string())]))
    }

    #[tool(description = "Dump the entire funnel: ideas with their plans, each plan's nodes with status, and the dependency edges. Useful for orienting after a context reset before calling funnel_next.")]
    async fn funnel_show(&self) -> Result<CallToolResult, McpError> {
        use std::fmt::Write;
        if server_target().is_some() {
            let (channel, bearer) = mcp_connect().await?;
            let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, mcp_auth(bearer));
            let dump = c.show(pb::Empty {}).await.map_err(internal)?.into_inner();
            let n_plans: usize = dump.ideas.iter().map(|i| i.plans.len()).sum();
            let mut out = String::new();
            let _ = writeln!(out, "ideas: {}, plans: {}", dump.ideas.len(), n_plans);
            for idea in &dump.ideas {
                let _ = writeln!(out, "  {} [{}] {}", idea.id, idea.source, idea.text);
            }
            for idea in &dump.ideas {
                for plan in &idea.plans {
                    let edges: usize = plan.nodes.iter().map(|n| n.deps.len()).sum();
                    let _ = writeln!(
                        out,
                        "  {} (idea {}) [{}] {} — {} nodes, {} edges",
                        plan.id, plan.idea_id, plan.status, plan.summary, plan.nodes.len(), edges,
                    );
                    for n in &plan.nodes {
                        let _ = writeln!(out, "    {} [{}] {} {}", n.id, n.status, n.kind, n.title);
                    }
                }
            }
            return Ok(CallToolResult::success(vec![Content::text(out)]));
        }
        let s = self.state.lock().await;
        let f = &s.funnel.funnel;
        let mut out = String::new();
        let _ = writeln!(out, "ideas: {}, plans: {}", f.ideas.len(), f.plans.len());
        for (iid, idea) in &f.ideas {
            let _ = writeln!(out, "  {} [{}] {}", iid.as_str(), idea.source, idea.text);
        }
        for (pid, plan) in &f.plans {
            let _ = writeln!(
                out,
                "  {} (idea {}) [{:?}] {} — {} nodes, {} edges",
                pid.as_str(),
                plan.idea_id.as_str(),
                plan.status,
                plan.summary,
                plan.nodes.len(),
                plan.edges.len(),
            );
            for (nid, n) in &plan.nodes {
                let title = n.params.get("title").and_then(|v| v.as_str()).unwrap_or("");
                let _ = writeln!(out, "    {} [{:?}] {} {}", nid.as_str(), n.status, n.kind, title);
            }
        }
        Ok(CallToolResult::success(vec![Content::text(out)]))
    }
}

/// Dependency-mimir support (non-tool helpers).
impl NornirServer {
    /// Return the cached dependency Mímir, building it on first use from
    /// the resolved `nornir-workspace.toml`. The graph build runs
    /// cargo-metadata per repo, so it is done once and cached in `State`.
    async fn mimir(&self) -> Result<Arc<MimirCtx>, McpError> {
        let mut s = self.state.lock().await;
        if let Some(o) = &s.mimir {
            return Ok(o.clone());
        }
        let desc_path = resolve_workspace_descriptor(&s.loaded).map_err(internal)?;
        let desc = WorkspaceDescriptor::load(&desc_path).map_err(internal)?;
        let graph = WorkspaceGraph::build(&desc).map_err(internal)?;
        let ctx = Arc::new(MimirCtx {
            graph,
            workspace_name: desc.workspace.name.clone(),
        });
        s.mimir = Some(ctx.clone());
        Ok(ctx)
    }

    #[cfg(any(feature = "embed-tract", feature = "embed-ort"))]
    async fn embedder(&self) -> Result<Arc<dyn nornir::vector::store::Embedder>, McpError> {
        {
            let s = self.state.lock().await;
            if let Some(e) = &s.embedder {
                return Ok(e.clone());
            }
        }
        // Model load is blocking + ~1s; do it off the async lock.
        let e: Arc<dyn nornir::vector::store::Embedder> = tokio::task::spawn_blocking(|| {
            nornir::vector::load_embedder().map(Arc::from)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        let mut s = self.state.lock().await;
        let cached = s.embedder.get_or_insert(e).clone();
        Ok(cached)
    }

    /// Open the warehouse on-demand, load the latest knowledge snapshot for
    /// `repo`, and run `f` to render the result as JSON. All blocking work
    /// (warehouse open + iceberg scan, both of which drive their own runtime)
    /// runs on a blocking thread; the state lock is released before spawning.
    async fn knowledge_query_json<F>(&self, repo: String, f: F) -> Result<String, McpError>
    where
        F: FnOnce(&nornir::knowledge::query::KnowledgeView) -> serde_json::Result<String>
            + Send
            + 'static,
    {
        let warehouse_root = {
            let s = self.state.lock().await;
            s.loaded.warehouse_root()
        };
        tokio::task::spawn_blocking(move || -> Result<String, McpError> {
            let wh = IcebergWarehouse::open(&warehouse_root)
                .with_context(|| format!("open warehouse at {}", warehouse_root.display()))
                .map_err(internal)?;
            let view = nornir::knowledge::query::load_latest(&wh, &repo).map_err(internal)?;
            f(&view).map_err(internal)
        })
        .await
        .map_err(internal)?
    }

    /// Load persisted DWARF facts for `repo` (latest, or pinned to `sha`) from the
    /// warehouse and run `f` over them. Restores into the workspace's
    /// `cache/dwarf/<repo>` materialized view; needs no binary. Mirrors
    /// [`knowledge_query_json`](Self::knowledge_query_json).
    async fn dwarf_load_json<F>(
        &self,
        repo: String,
        sha: Option<String>,
        f: F,
    ) -> Result<String, McpError>
    where
        F: FnOnce(&nornir::introspect::persist::DwarfFacts) -> serde_json::Result<String>
            + Send
            + 'static,
    {
        let warehouse_root = {
            let s = self.state.lock().await;
            s.loaded.warehouse_root()
        };
        tokio::task::spawn_blocking(move || -> Result<String, McpError> {
            let wh = IcebergWarehouse::open(&warehouse_root)
                .with_context(|| format!("open warehouse at {}", warehouse_root.display()))
                .map_err(internal)?;
            let into = warehouse_root
                .parent()
                .unwrap_or(warehouse_root.as_path())
                .join("cache/dwarf")
                .join(&repo);
            let facts = nornir::introspect::persist::load_dwarf(&wh, &repo, sha.as_deref(), &into)
                .map_err(internal)?;
            f(&facts).map_err(internal)
        })
        .await
        .map_err(internal)?
    }
}

#[tool_handler]
impl ServerHandler for NornirServer {
    /// Central tool dispatch — wraps the macro router with per-call telemetry
    /// (tool name, ok/err, latency) fired to the warehouse logger. Providing
    /// `call_tool` here makes `#[tool_handler]` skip generating its own.
    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let tool = request.name.to_string();
        let started = std::time::Instant::now();
        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
        let result = self.tool_router.call(tcc).await;
        if let Some(tx) = &self.log_tx {
            let _ = tx.send(McpCall {
                ts_micros: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_micros() as i64)
                    .unwrap_or(0),
                tool,
                status: if result.is_ok() { "ok" } else { "err" }.to_string(),
                latency_ms: started.elapsed().as_millis() as i64,
            });
        }
        result
    }

    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder().enable_tools().build(),
        )
        .with_server_info(Implementation::from_build_env())
        .with_instructions(
            "nornir — companion to cargo. Tools: repos_list, repo_overview, guard_{status,apply,verify}, \
             deps_of, dependents_of, affected_by_change, build_order, dep_path, \
             external_dep_users, dep_graph_mermaid, changed_since_last_release, \
             bench_history, release_gate_{path_patches,nexus_floor,no_regression,docs_fresh,all}, \
             docs_{init,render,check,history}, \
             search, symbol_lookup, defined_in, callers_of, callees_of, path_between, \
             knowledge_{symbol_lookup,defined_in,callers,callees,call_path}, \
             dwarf_{symbol_lookup,defined_in,callers,callees,call_path}, \
             funnel_{submit_idea,create_plan,add_node,link,next,status,show}. \
             The dependency Mímir (deps_of/dependents_of/affected_by_change/dep_path/\
             build_order/changed_since_last_release) answers cross-repo graph questions — \
             blast radius, build order, re-run set — so a small model needn't reason over the \
             whole graph; it reads a nornir-workspace.toml (set NORNIR_WORKSPACE to override). \
             The funnel is a persistent DAG of ideas → plans → nodes that survives agent \
             context loss; call funnel_show then funnel_next after any restart to find out \
             what to work on. The server reads workspace_holger/release/nornir.toml at start; \
             restart to pick up edits."
                .to_string(),
        )
    }
}

fn format_status(report: &[guard::PathStatus]) -> String {
    let mut s = String::new();
    s.push_str(&format!("{:<8} {:<8} {:<8} path\n", "exists", "writable", "changed"));
    for p in report {
        s.push_str(&format!(
            "{:<8} {:<8} {:<8} {}\n",
            yn(p.exists), yn(p.writable), yn(p.changed), p.path.display()
        ));
    }
    s
}

fn resolve_binary(workspace_root: &std::path::Path, binary: &str) -> std::path::PathBuf {
    let p = std::path::PathBuf::from(binary);
    if p.is_absolute() { p } else { workspace_root.join(p) }
}

fn yn(b: bool) -> &'static str { if b { "yes" } else { "no" } }

fn internal<E: std::fmt::Display>(e: E) -> McpError {
    McpError::internal_error(e.to_string(), None)
}

// ---- client mode (talk to a running nornir-server over gRPC) ---------------
//
// Like the CLI: when `NORNIR_SERVER` is set, every warehouse-touching tool
// routes to the server (which owns the warehouse's write lock, so the MCP can't
// open it embedded). `NORNIR_SERVER_TOKEN` carries the bearer; `NORNIR_WORKSPACE`
// selects the workspace via the `nornir-workspace` header. Unset → embedded.

mod pb {
    tonic::include_proto!("nornir.v1");
}

/// gRPC bearer + workspace interceptor (mirrors the CLI's `auth_interceptor`).
type Bearer = tonic::metadata::MetadataValue<tonic::metadata::Ascii>;

fn server_target() -> Option<String> {
    std::env::var("NORNIR_SERVER").ok().filter(|s| !s.is_empty())
}

/// The active workspace for proxied (`NORNIR_SERVER`) calls — settable at runtime
/// by the `workspace_use` tool so one MCP hops workspaces without a restart.
/// Falls back to `NORNIR_WORKSPACE` when unset.
static ACTIVE_WS: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);

fn set_active_workspace(name: &str) {
    if let Ok(mut g) = ACTIVE_WS.write() {
        *g = (!name.is_empty()).then(|| name.to_string());
    }
}

fn client_workspace() -> Option<String> {
    if let Ok(g) = ACTIVE_WS.read() {
        if let Some(ws) = g.as_ref().filter(|s| !s.is_empty()) {
            return Some(ws.clone());
        }
    }
    std::env::var("NORNIR_WORKSPACE").ok().filter(|s| !s.is_empty())
}

/// Connect to `NORNIR_SERVER` and return a ready channel + bearer. Errors as an
/// `McpError` so callers can `?` inside a tool. Only called when `server_target`
/// is `Some`.
async fn mcp_connect() -> Result<(tonic::transport::Channel, Bearer), McpError> {
    let server = server_target().ok_or_else(|| internal("NORNIR_SERVER is not set"))?;
    let token = std::env::var("NORNIR_SERVER_TOKEN")
        .map_err(|_| internal("NORNIR_SERVER is set; NORNIR_SERVER_TOKEN is required"))?;
    let endpoint = if server.starts_with("http") { server } else { format!("http://{server}") };
    let bearer: Bearer = format!("Bearer {token}").parse().map_err(internal)?;
    let channel = tonic::transport::Channel::from_shared(endpoint.clone())
        .map_err(|e| internal(format!("invalid NORNIR_SERVER url `{endpoint}`: {e}")))?
        .connect()
        .await
        .map_err(|e| internal(format!("connect to nornir-server at {endpoint}: {e}")))?;
    Ok((channel, bearer))
}

/// Build the tonic interceptor that stamps the bearer + workspace headers onto
/// every request (same contract as the CLI's `auth_interceptor`).
fn mcp_auth(
    bearer: Bearer,
) -> impl FnMut(tonic::Request<()>) -> std::result::Result<tonic::Request<()>, tonic::Status> + Clone {
    move |mut req: tonic::Request<()>| {
        req.metadata_mut().insert("authorization", bearer.clone());
        if let Some(ws) = client_workspace() {
            if let Ok(v) = ws.parse() {
                req.metadata_mut().insert("nornir-workspace", v);
            }
        }
        Ok(req)
    }
}

/// Render a server `GuardReport` as the same text table the embedded path emits.
fn pb_guard_text(report: &pb::GuardReport) -> String {
    let mut s = format!("{:<8} {:<8} {:<8} path\n", "exists", "writable", "changed");
    for p in &report.paths {
        s.push_str(&format!(
            "{:<8} {:<8} {:<8} {}\n",
            yn(p.exists), yn(p.writable), yn(p.changed), p.path
        ));
    }
    s
}

/// Re-emit a JSON string returned by a Mimir RPC as a pretty tool result
/// (parses then re-serializes so client output matches the embedded `ok_json`).
fn mimir_emit(json: &str) -> Result<CallToolResult, McpError> {
    let v: serde_json::Value = serde_json::from_str(json).map_err(internal)?;
    ok_json(&v)
}

/// Rebuild a native `bench::BenchRun` from its protobuf form so the client path
/// serializes byte-identically to the embedded `bench_history` (which dumps
/// `Vec<bench::BenchRun>` via serde).
fn pb_bench_run(r: pb::BenchRun) -> bench::BenchRun {
    bench::BenchRun {
        date: r.date,
        timestamp: if r.timestamp.is_empty() { None } else { Some(r.timestamp) },
        version: r.version,
        machine: r.machine,
        cores: r.cores,
        results: r
            .results
            .into_iter()
            .map(|res| {
                let mut metrics = serde_json::Map::new();
                for kv in res.metrics {
                    metrics.insert(kv.key, json!(kv.value));
                }
                bench::BenchResult { name: res.name, metrics }
            })
            .collect(),
        tests: r
            .tests
            .into_iter()
            .map(|t| bench::TestOutcome {
                name: t.name,
                passed: t.passed,
                duration_ms: if t.has_duration { Some(t.duration_ms) } else { None },
                message: if t.message.is_empty() { None } else { Some(t.message) },
            })
            .collect(),
    }
}

/// Map a server `SymbolList` (DWARF/introspect symbols) to the JSON array the
/// embedded introspect tools emit.
fn pb_symbols_json(list: pb::SymbolList) -> Vec<serde_json::Value> {
    list.symbols
        .into_iter()
        .map(|s| {
            json!({
                "name": s.name, "name_demangled": s.name_demangled,
                "name_mangled": s.name_mangled, "file": s.file, "line": s.line,
                "size_bytes": s.size_bytes, "krate": s.krate,
            })
        })
        .collect()
}

/// Map server `KnowledgeSymbols` to a JSON array.
fn pb_knowledge_symbols_json(k: pb::KnowledgeSymbols) -> Vec<serde_json::Value> {
    k.symbols
        .into_iter()
        .map(|s| {
            json!({
                "crate_name": s.crate_name, "module_path": s.module_path,
                "item_kind": s.item_kind, "item_name": s.item_name,
                "visibility": s.visibility, "file": s.file, "line": s.line,
                "doc_lines": s.doc_lines, "signature": s.signature,
            })
        })
        .collect()
}

/// Map server `KnowledgeCalls` to a JSON array.
fn pb_knowledge_calls_json(k: pb::KnowledgeCalls) -> Vec<serde_json::Value> {
    k.calls
        .into_iter()
        .map(|c| {
            json!({
                "crate_name": c.crate_name, "caller_path": c.caller_path,
                "callee_ident": c.callee_ident, "call_kind": c.call_kind,
                "file": c.file, "line": c.line,
            })
        })
        .collect()
}

/// Turn a single-gate `GateResult` into the MCP result the embedded gate emits:
/// `ok: …` text on pass, an `McpError` carrying the gate message on fail.
fn pb_gate_result(g: pb::GateResult) -> Result<CallToolResult, McpError> {
    if g.status == "pass" {
        let mut msg = format!("ok: {}", g.gate);
        if !g.version.is_empty() {
            msg.push_str(&format!(" on v{}", g.version));
        }
        Ok(CallToolResult::success(vec![Content::text(msg)]))
    } else {
        Err(internal(format!(
            "gate {} failed: {}",
            g.gate,
            if g.message.is_empty() { "(no detail)" } else { &g.message }
        )))
    }
}

/// Client-mode `docs_export` / `docs_book`: relay to the server's `Docs.Export`
/// (`book=false`) or `Docs.Book` (`book=true`) RPC and re-emit the same JSON the
/// embedded path produces. The server owns the warehouse + the typst engine; the
/// artifact is written under the server's `<repo>/docs/`.
async fn mcp_docs_export_remote(
    repo: &str,
    format: Option<&str>,
    book: bool,
) -> Result<CallToolResult, McpError> {
    let (channel, bearer) = mcp_connect().await?;
    let mut c = pb::docs_client::DocsClient::with_interceptor(channel, mcp_auth(bearer));
    let req = pb::DocsExportRequest {
        repo: repo.to_string(),
        format: format.unwrap_or("").to_string(),
    };
    let r = if book {
        c.book(req).await
    } else {
        c.export(req).await
    }
    .map_err(internal)?
    .into_inner();
    let mut body = json!({
        "repo": r.repo,
        "format": r.format,
        "bytes": r.bytes,
        "out": r.out,
        "sha256": r.sha256,
        "git_sha": r.git_sha,
        "export_id": r.export_id,
    });
    if book {
        body["sources"] = json!(r.sources);
    }
    ok_json(&body)
}

/// Serialize a value to pretty JSON and wrap it as a successful tool result.
fn ok_json<T: serde::Serialize>(value: &T) -> Result<CallToolResult, McpError> {
    let text = serde_json::to_string_pretty(value).map_err(internal)?;
    Ok(CallToolResult::success(vec![Content::text(text)]))
}


/// Sanitize a repo name into a Mermaid-safe node id.

/// Resolve the `nornir-workspace.toml` describing the repos to graph.
/// Honors `NORNIR_WORKSPACE` (explicit path) first, then searches a few
/// conventional locations relative to the loaded nornir.toml.
fn resolve_workspace_descriptor(loaded: &Loaded) -> Result<PathBuf> {
    if let Some(p) = std::env::var_os("NORNIR_WORKSPACE") {
        let p = PathBuf::from(p);
        if p.exists() {
            return Ok(p);
        }
        anyhow::bail!("NORNIR_WORKSPACE={} does not exist", p.display());
    }
    let mut candidates = vec![
        loaded.workspace_root.join("nornir-workspace.toml"),
        loaded.workspace_root.join("workspace_holger/nornir-workspace.toml"),
    ];
    if let Some(dir) = loaded.config_path.parent() {
        candidates.push(dir.join("nornir-workspace.toml"));
    }
    for c in &candidates {
        if c.exists() {
            return Ok(c.clone());
        }
    }
    anyhow::bail!(
        "no nornir-workspace.toml found (set NORNIR_WORKSPACE or create one); searched: {}",
        candidates
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn repo_ctx<'a>(
    s: &'a tokio::sync::MutexGuard<'a, State>,
    repo_name: &str,
) -> anyhow::Result<(PathBuf, &'a config::Repo)> {
    let repo = s.loaded.nornir.repo.get(repo_name)
        .ok_or_else(|| anyhow::anyhow!("repo `{repo_name}` not in nornir.toml"))?;
    let root = config::Nornir::repo_dir(&s.loaded.workspace_root, repo_name);
    Ok((root, repo))
}

fn mcp_last_run(repo_root: &std::path::Path, repo: &config::Repo) -> anyhow::Result<bench::BenchRun> {
    let path = repo_root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
    let runs = bench::history::read_all(&path)?;
    runs.into_iter().last().ok_or_else(|| anyhow::anyhow!("no bench runs in {}", path.display()))
}

/// All bench runs for `repo` from the on-disk JSONL receipt, for the
/// `bench_history` doc section. Best-effort (empty when absent). Reads the same
/// source as [`mcp_last_run`]; renderers must not open the warehouse themselves.
fn mcp_history(repo_root: &std::path::Path, repo: &config::Repo) -> Vec<bench::BenchRun> {
    let path = repo_root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
    bench::history::read_all(&path).unwrap_or_default()
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "nornir_mcp=info".into()),
        )
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .init();

    let config_path = std::env::var_os("NORNIR_CONFIG").map(PathBuf::from);
    let loaded = match config_path {
        Some(p) => config::load_explicit(&p)?,
        None => config::discover(&std::env::current_dir()?)?,
    };

    eprintln!("starting nornir-mcp; config={}", loaded.config_path.display());
    let server = NornirServer::new(loaded).await?.serve(stdio()).await?;
    server.waiting().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use nornir::config::Nornir;

    #[test]
    fn resolve_descriptor_honors_env_override() {
        let tmp = tempfile::tempdir().unwrap();
        let desc = tmp.path().join("ws.toml");
        std::fs::write(&desc, "[workspace]\nname=\"x\"\n").unwrap();
        let loaded = Loaded {
            nornir: Nornir::default(),
            config_path: tmp.path().join("nornir.toml"),
            workspace_root: tmp.path().to_path_buf(),
        };
        // SAFETY: single-threaded test; restored immediately after.
        unsafe { std::env::set_var("NORNIR_WORKSPACE", &desc) };
        let got = resolve_workspace_descriptor(&loaded).unwrap();
        unsafe { std::env::remove_var("NORNIR_WORKSPACE") };
        assert_eq!(got, desc);
    }

    #[test]
    fn resolve_descriptor_errors_when_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let loaded = Loaded {
            nornir: Nornir::default(),
            config_path: tmp.path().join("nornir.toml"),
            workspace_root: tmp.path().to_path_buf(),
        };
        // Ensure no env override leaks in from another test.
        unsafe { std::env::remove_var("NORNIR_WORKSPACE") };
        assert!(resolve_workspace_descriptor(&loaded).is_err());
    }

    #[test]
    fn agent_tool_surface_excludes_unlock_includes_mimir() {
        let router = NornirServer::tool_router();
        // Lock-down: the unlock (chmod +w) tool must NOT be agent-facing.
        assert!(!router.has_route("guard_release"), "guard_release must not be exposed to agents");
        // Tamper-evidence + Mímir tools must be present.
        for name in [
            "guard_apply",
            "guard_verify",
            "deps_of",
            "dependents_of",
            "affected_by_change",
            "build_order",
            "dep_path",
            "external_dep_users",
            "dep_graph_mermaid",
            "changed_since_last_release",
            "repo_overview",
            "docs_book",
            "docs_export",
            "dwarf_symbol_lookup",
            "dwarf_defined_in",
            "dwarf_callers",
            "dwarf_callees",
            "dwarf_call_path",
        ] {
            assert!(router.has_route(name), "expected MCP tool `{name}` to be registered");
        }
    }
}