nornir 0.4.4

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
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
//! `nornir` — human-facing CLI driver over the nornir library.
//!
//! Reads the consumer's `nornir.toml` (autodiscovered or `--config`)
//! and dispatches to lib APIs. Mirror image of `nornir-mcp`, which
//! exposes the same surface to LLM agents over MCP.

use std::path::{Path, PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use clap::{Args, Parser, Subcommand};

use nornir::bench;
use nornir::config::{self, Loaded};
use nornir::docs;
use nornir::guard;
use nornir::index;
use nornir::introspect;
use nornir::release;
use nornir::warehouse;

#[derive(Parser)]
#[command(name = "nornir", version, about = "Companion to cargo: release, bench, docs, guard.")]
struct Cli {
    /// Path to nornir.toml (default: autodiscover by walking up from cwd).
    #[arg(long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// AI-agent guard rails (chmod -w forbidden paths).
    Guard {
        #[command(subcommand)]
        op: GuardOp,
    },
    /// Benchmark history / runner.
    Bench {
        #[command(subcommand)]
        op: BenchOp,
    },
    /// Release gates and publish.
    Release {
        #[command(subcommand)]
        op: ReleaseOp,
    },
    /// Documentation assembly.
    Docs {
        #[command(subcommand)]
        op: DocsOp,
    },
    /// Code introspection (call graph, dep graph, public API).
    Introspect {
        #[command(subcommand)]
        op: IntrospectOp,
    },
    /// Warehouse (Parquet + SQLite catalog) for bench history.
    Warehouse {
        #[command(subcommand)]
        op: WarehouseOp,
    },
    /// Full-text index (Tantivy/BM25) over docs/code/bench/changelog/config.
    Index {
        #[command(subcommand)]
        op: IndexOp,
    },
    /// Semantic / vector search: embed code+docs into the warehouse and query
    /// by meaning. `search --mode` does lexical (BM25), semantic (vector), or
    /// hybrid (both, RRF-merged). Indexing needs an embedder feature
    /// (`embed-tract` CPU or `embed-ort` GPU).
    /// UI-robot tester: drive a real browser (WebDriver) through declarative
    /// TOML scenarios — a plan-tests-DAG with `needs = []` edges. Feature `robot`.
    #[cfg(feature = "robot")]
    Robot {
        #[command(subcommand)]
        op: RobotOp,
    },
    #[cfg(feature = "vector")]
    Vector {
        #[command(subcommand)]
        op: VectorOp,
    },
    /// Knowledge map producers: scan symbols (syn) + git activity (gix).
    Knowledge {
        #[command(subcommand)]
        op: KnowledgeOp,
    },
    /// Map an appointed workspace member end-to-end: persisted knowledge scan +
    /// build the workspace code index (scoped to members) + snapshot it keyed to
    /// this member's HEAD. One verb for the whole index pipeline.
    Map(RepoArg),
    /// Idea→plan funnel (the planning DAG) — human CLI mirror of the MCP tools.
    Funnel {
        #[command(subcommand)]
        op: FunnelOp,
    },
    /// List configured repos.
    Repos,
    /// Launch the gRPC server (thin wrapper over the `nornir-server` binary).
    Serve(ServeArgs),
    /// Launch the time-travel visualizer (thin wrapper over `urdr-threads`).
    /// Reads `NORNIR_SERVER`/`NORNIR_SERVER_TOKEN`/`NORNIR_WORKSPACE` like the CLI;
    /// with `NORNIR_SERVER` set it views a running server live, else opens a local
    /// warehouse.
    Viz(VizArgs),
    /// Install/package nornir onto a host (a taste of the build-installer;
    /// container/redfish/terraform targets come later).
    Install {
        #[command(subcommand)]
        op: InstallOp,
    },
    /// SSH identity used for git poll/push in server-monitored mode. The keypair
    /// lives in the `nornir` user's `.ssh` dir (created by `install systemd`).
    Key {
        #[command(subcommand)]
        op: KeyOp,
    },
    /// The server's workspace registry — the index of every workspace it tracks
    /// (server-monitored / pushed / external). Stored in `<root>/registry.redb`.
    Workspace {
        #[command(subcommand)]
        op: WorkspaceOp,
    },
}

#[derive(Subcommand)]
enum WorkspaceOp {
    /// List registered workspaces.
    Ls,
    /// Show one workspace's full record.
    Show { name: String },
    /// Register (or update) a workspace in the registry.
    Register {
        name: String,
        /// Local path or git URL to the workspace's `nornir-workspace.toml`.
        #[arg(long)]
        descriptor: String,
        /// Server polls members and republishes (server-user `nornir`).
        #[arg(long)]
        monitored: bool,
        /// Sources live outside; only `builds/` is server-owned (`git/` empty).
        #[arg(long)]
        external: bool,
        /// Poll interval for monitored workspaces, e.g. `60s`.
        #[arg(long)]
        poll: Option<String>,
    },
    /// Remove a workspace from the registry.
    Rm { name: String },
    /// Clone/fetch every git member into `<root>/<name>/git/` and update each
    /// member's sync state. The poll loop's primitive. HTTPS only for now.
    Fetch { name: String },
}

#[derive(Subcommand)]
enum KeyOp {
    /// Print the public key — paste it as a deploy key on each monitored repo.
    Show,
    /// Print the path to the public key.
    Path,
    /// Create the ed25519 keypair if it doesn't exist yet (idempotent).
    Generate,
}

#[derive(Args)]
struct ServeArgs {
    /// `nornir.toml` to serve (else the server uses NORNIR_CONFIG / cwd discovery).
    #[arg(long)]
    config: Option<PathBuf>,
    /// Bind address (default `127.0.0.1:7878`).
    #[arg(long)]
    addr: Option<String>,
    /// Bearer token (≥16 chars). Falls back to `NORNIR_SERVER_TOKEN`.
    #[arg(long)]
    token: Option<String>,
    /// `nornir-server` binary (default: next to this executable).
    #[arg(long)]
    server_bin: Option<PathBuf>,
}

#[derive(Args)]
struct VizArgs {
    /// Workspace to view (else `NORNIR_WORKSPACE`, else the viz default).
    #[arg(long)]
    workspace: Option<String>,
    /// Local warehouse dir (embedded mode; ignored when `NORNIR_SERVER` is set).
    #[arg(long)]
    warehouse: Option<PathBuf>,
    /// `urdr-threads` binary (default: next to this executable / on PATH).
    #[arg(long)]
    viz_bin: Option<PathBuf>,
}

#[derive(Subcommand)]
enum InstallOp {
    /// Install a systemd service running `nornir-server` as a `nornir` system
    /// user. Must run as root (no per-user install yet).
    Systemd(SystemdArgs),
    /// Stop + remove the systemd service (unit + /etc/nornir). Root-only.
    /// Keeps the `nornir` user, its home (`/var/lib/nornir` — warehouses, key)
    /// and the installed binaries unless `--purge`.
    Uninstall(UninstallArgs),
}

#[derive(Args)]
struct UninstallArgs {
    /// Also delete the data home (`/var/lib/nornir`: warehouses, registry, SSH
    /// key), the installed binaries in `/usr/local/bin`, and the `nornir` user.
    #[arg(long)]
    purge: bool,
    /// Service user (default `nornir`).
    #[arg(long, default_value = "nornir")]
    user: String,
}

#[derive(Args)]
struct SystemdArgs {
    /// OPTIONAL release-recipe `nornir.toml` for a *served* (non-monitored)
    /// workspace (gates/bench/publish_order). NOT needed to monitor — pass only
    /// `--monitor` for a pure self-sync server.
    #[arg(long)]
    config: Option<PathBuf>,
    /// Bind address recorded in the unit's env file (default `127.0.0.1:7878`).
    #[arg(long, default_value = "127.0.0.1:7878")]
    addr: String,
    /// System user to create + run as (default `nornir`).
    #[arg(long, default_value = "nornir")]
    user: String,
    /// `nornir-server` binary path (default: next to this executable).
    #[arg(long)]
    server_bin: Option<PathBuf>,
    /// Monitored-workspaces root (`NORNIR_ROOT`). When set, the service runs the
    /// self-sync poll loop. Default `<user home>/workspaces` when --monitor is
    /// given. The dir is created and chowned to the service user.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Auto-register a monitored workspace: `name=descriptor` (a
    /// nornir-workspace.toml path or git URL). Repeatable. Sets `NORNIR_MONITOR`.
    #[arg(long = "monitor")]
    monitor: Vec<String>,
    /// Poll interval for the self-sync loop, e.g. `60s` (`NORNIR_POLL`).
    #[arg(long)]
    poll: Option<String>,
}

#[derive(Subcommand)]
enum FunnelOp {
    /// Submit a krav / prompt / idea into the intake funnel. Prints the new
    /// idea id. The text comes from the positional arg, `--file <path>`, or
    /// stdin (pipe) — so long requirements ingest naturally:
    ///   `nornir funnel submit "<krav>"` · `--file krav.md` · `cat p | nornir funnel submit`
    Submit {
        /// Inline idea text. Omit when using `--file` or piping via stdin.
        text: Option<String>,
        /// Read the idea text from a file (e.g. a krav/prompt markdown).
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        #[arg(long)]
        source: Option<String>,
    },
    /// Create a plan refining IDEA_ID (auto-activated). Prints the plan id.
    Plan { idea_id: String, summary: String },
    /// Add a node to PLAN_ID. KIND is a free verb (e.g. `code:write`).
    Node {
        plan_id: String,
        kind: String,
        #[arg(long)]
        title: Option<String>,
        /// Target artifact (repeatable).
        #[arg(long = "target")]
        targets: Vec<String>,
        /// Node id in the same plan this node depends on (repeatable).
        #[arg(long = "needs")]
        needs: Vec<String>,
        #[arg(long)]
        prompt: Option<String>,
    },
    /// Add a dependency edge: TO becomes ready only after FROM is done.
    Link { plan_id: String, from: String, to: String },
    /// Print the ready PlanNodes across active plans (JSON), topo-ordered.
    Next,
    /// Flip a node's status: ready | active | blocked | done | failed.
    Status {
        plan_id: String,
        node_id: String,
        status: String,
        #[arg(long)]
        why: Option<String>,
    },
    /// Dump the whole funnel (ideas, plans, nodes, edges).
    Show,
}

#[derive(Subcommand)]
enum KnowledgeOp {
    /// Scan <repo>: parse every .rs with syn (symbols/calls/cfg-gates) and
    /// walk HEAD's commits with gix (per-file heat). Persists to the iceberg
    /// tables (symbol_facts / call_edges / feature_gate_facts / git_heat_facts)
    /// by default; pass `--no-save` to only print the summary.
    Scan {
        repo: String,
        /// Don't write to the warehouse (default: persist symbol_facts /
        /// call_edges / git_heat for the repo — nothing computed is discarded).
        #[arg(long = "no-save")]
        no_save: bool,
    },
    /// Query the latest persisted knowledge map for <repo> from iceberg
    /// (no compiled binary needed, unlike `introspect`). `kind` is one of:
    /// `callers` (who calls ARG), `callees` (what ARG calls),
    /// `defined-in` (symbols in files ending with ARG), `lookup`
    /// (symbols whose name contains ARG), `path` (shortest call chain from
    /// ARG to `--to`, BFS over call edges).
    Query {
        repo: String,
        /// callers | callees | defined-in | lookup | path
        kind: String,
        /// function name / file suffix / name substring / path source (per `kind`)
        arg: String,
        /// Target function for `kind = path` (matched by last path segment).
        #[arg(long)]
        to: Option<String>,
        #[arg(long, default_value_t = 50)]
        limit: usize,
    },
}

#[derive(Subcommand)]
enum GuardOp {
    /// Report writable state of each forbidden path.
    Status,
    /// chmod -w every forbidden path, then record the tamper-evidence
    /// manifest (sha256 + mode) and export guard-policy.json.
    Apply,
    /// Verify forbidden paths against the recorded manifest (drift report).
    Verify,
    /// chmod +w every forbidden path (intentional human unlock). Requires
    /// the NORNIR_GUARD_UNLOCK_TOKEN env var to be set — never agent-facing.
    Release,
}

#[derive(Subcommand)]
enum BenchOp {
    /// Show <repo>'s bench history — scalar metrics + test pass/fail per run
    /// (newest first). `--json` prints the raw JSONL instead; `--limit N` caps rows.
    HistoryShow(HistoryShowArgs),
    /// Run <repo>'s examples/nornir-bench.rs (or xtask/examples/nornir-bench.rs),
    /// parse the BenchRun it prints, and append it to the iceberg
    /// `bench_runs` table. This is the single end-to-end command for
    /// "measure now and persist".
    Run(RepoArg),
}

#[derive(Subcommand)]
enum ReleaseOp {
    /// Run the no-path-patches gate against <repo>.
    GatePathPatches(RepoArg),
    /// Audit every Cargo.toml in <repo>: path-deps must carry a version=
    /// or cargo publish rejects them (feature 1).
    GatePathDepVersions(RepoArg),
    /// Verify every publishable [package] in <repo> has readme + license
    /// + repository + description set (feature 4).
    GateCrateMetadata(RepoArg),
    /// Run cargo metadata in <repo> and report any duplicate links=
    /// declarations that would cause linker conflicts (feature 8).
    GateLinksConflicts(RepoArg),
    /// Run the nexus_floor gate against the last bench run for <repo>.
    GateNexusFloor(RepoArg),
    /// Run the no_regression gate against <repo>'s history.
    GateNoRegression(RepoArg),
    /// Run docs_fresh gate (README.md sections in sync) against <repo>.
    GateDocsFresh(RepoArg),
    /// Run integration_roundtrip gate by invoking `cargo test --test roundtrip_<kind> --release` per configured kind.
    GateRoundtrip(RepoArg),
    /// Run every gate enabled in nornir.toml for <repo>; prints a report.
    GateAll(RepoArg),
    /// Run one gate by NAME against <repo> — the unified entry point.
    /// NAME ∈ path_patches | path_dep_versions | crate_metadata |
    /// links_conflicts | nexus_floor | no_regression | docs_fresh | roundtrip |
    /// guard_intact | all.
    Gate {
        /// Gate name (see the variant docs for the list).
        name: String,
        /// Repo as declared under `[repo.<name>]` in nornir.toml.
        repo: String,
    },
    /// Regression time-bisect: for <repo>, find the last green release and the
    /// first red one (the gate's last-good → first-bad boundary) from recorded
    /// release history, and bound the suspect commit range. No rebuild — pure
    /// scan over the warehouse (see `release::regression`).
    Trace {
        repo: String,
        /// Restrict to one workspace name; empty (default) = every workspace.
        #[arg(long, default_value = "")]
        workspace: String,
        /// Emit JSON instead of the human-readable trace.
        #[arg(long)]
        json: bool,
    },
    /// Orchestrate test → bench (persist) → gate-all for every configured repo,
    /// walking in the topological order recorded in the iceberg `dep_graph_edges`
    /// table (dependencies first). Stops on the first failure. No publish.
    Run(ReleaseRunArgs),
    /// Walk the publish order from nornir.toml.
    Publish(PublishArgs),
    /// Poll crates.io until <crate>@<version> shows up as max_version
    /// (feature 3 — replaces fixed `sleep 20` between publish phases).
    WaitForIndex {
        krate: String,
        version: String,
        /// Max wait in seconds (default 300).
        #[arg(long, default_value_t = 300)]
        timeout_secs: u64,
    },
    /// `cargo package` <repo>'s crate then walk the .crate tarball and
    /// report size + entry count + largest file (feature 5).
    TarballStats {
        repo: String,
        krate: String,
    },
    /// Strip every `[patch.crates-io]` block from every Cargo.toml in
    /// <repo>. Use on the release branch right before `publish`
    /// (feature 2). Prints (files, blocks) modified.
    StripPatchBlocks(RepoArg),
    /// Render conventional-commit changelog markdown for <repo> over
    /// the git range (e.g. `v1.2.3..HEAD`). Prints to stdout —
    /// pipe / redirect into `.nornir/changelog.md` (feature 13).
    Changelog {
        repo: String,
        range: String,
    },
    /// Compute the impacted-crate set for <repo> by comparing HEAD
    /// against <base> and walking the latest dep-graph snapshot's
    /// reverse edges. Prints each crate on its own line, ready to
    /// feed to `cargo test -p ...` (feature 11).
    ImpactedCrates {
        repo: String,
        #[arg(long, default_value = "main")]
        base: String,
    },
    /// Yank every `<crate>@<version>` listed in
    /// `<repo>/.nornir/yank-cascade.txt` (one `name version` per line)
    /// in the order given. `--undo` un-yanks, `--dry-run` only prints
    /// (feature 6).
    YankCascade {
        repo: String,
        #[arg(long)]
        undo: bool,
        #[arg(long)]
        dry_run: bool,
    },
    /// Mirror an already-packaged `.crate` tarball from <repo> to the
    /// holger registry at <holger-base-url>. Needs `cargo package -p
    /// <krate>` to have run first (feature 14).
    MirrorToHolger {
        repo: String,
        krate: String,
        version: String,
        #[arg(long)]
        holger_base_url: String,
        /// Bearer token; falls back to $HOLGER_TOKEN if omitted.
        #[arg(long)]
        token: Option<String>,
    },
    /// Coordinated cross-workspace version bump (feature 15, pure
    /// no-shell). Walks every Cargo.toml under <repo>, plans every
    /// edit needed to take <pkg> to <new-version> (own [package],
    /// every dep-table reference, [workspace.dependencies]), and
    /// optionally patch-bumps consumer crates so downstream sees
    /// the change. `--dry-run` prints the plan without writing.
    BumpVersion {
        repo: String,
        pkg: String,
        new_version: String,
        #[arg(long)]
        bump_consumers: bool,
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Subcommand)]
enum DocsOp {
    /// Scaffold `.nornir/` and migrate existing README.md / CHANGELOG.md
    /// into `.nornir/` as source-of-truth.
    Init(RepoArg),
    /// Render every source in `.nornir/` to the repo-root artifact
    /// (atomic write, preserves read-only bit).
    Render(RepoArg),
    /// CI gate: re-render in memory and fail on any drift vs disk.
    Check(RepoArg),
    /// Render the assembled README to PDF / HTML / MD bytes (runs render first).
    #[cfg(feature = "docs-export")]
    Export(DocsExportArgs),
    /// Render the *whole* doc set (every `.nornir/*.md` + non-generated
    /// `<repo>/*.md`) into one PDF / HTML / MD book (runs render first).
    #[cfg(feature = "docs-export")]
    Book(DocsBookArgs),
    /// List document exports historized in the Iceberg `doc_exports` table.
    History(DocsHistoryArgs),
    /// Build the dedicated docs Tantivy index (separate from the code index)
    /// and historize it into the `docs_index_*` Iceberg tables.
    Index(DocsIndexArgs),
    /// BM25 search over the docs index (restores from iceberg on a cold cache).
    Search(DocsSearchArgs),
}

#[derive(Args)]
struct DocsIndexArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// Build the index but skip historizing it into iceberg.
    #[arg(long)]
    skip_snapshot: bool,
}

#[derive(Args)]
struct DocsSearchArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// Query string (Tantivy syntax).
    query: String,
    /// Pin a historical git SHA (time-travel). Defaults to the latest snapshot.
    #[arg(long)]
    sha: Option<String>,
    /// Max hits to return.
    #[arg(long, default_value_t = 10)]
    limit: usize,
}

#[derive(Args)]
struct DocsHistoryArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// Restrict to one document (e.g. README).
    #[arg(long)]
    doc: Option<String>,
    /// Restrict to one version.
    #[arg(long)]
    version: Option<String>,
    /// Restrict to one format (pdf | html | md).
    #[arg(long)]
    format: Option<String>,
    /// Max rows to show (newest first).
    #[arg(long, default_value_t = 20)]
    limit: usize,
}

#[cfg(feature = "docs-export")]
#[derive(Args)]
struct DocsExportArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// Output format: pdf | html | md.
    #[arg(long, default_value = "pdf")]
    format: String,
    /// Extra output file path. Always writes `<repo>/docs/README.<ext>`; this
    /// copies the bytes to an additional path too.
    #[arg(long)]
    out: Option<PathBuf>,
}

#[cfg(feature = "docs-export")]
#[derive(Args)]
struct DocsBookArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// Output format: pdf | html | md. (md + pdf are the primary paths;
    /// html is experimental via typst's HTML target.)
    #[arg(long, default_value = "pdf")]
    format: String,
    /// Additional output file path. Always writes `<repo>/docs/book.<ext>`;
    /// `--out` copies the same bytes to an extra path too.
    #[arg(long)]
    out: Option<PathBuf>,
}

#[derive(Args)]
struct DocsFileArgs {
    #[command(flatten)]
    repo: RepoArg,
}

#[allow(dead_code)] // kept for the docs_fresh gate to reference if needed
type _DocsFileArgsRef = DocsFileArgs;

#[derive(Subcommand)]
enum IntrospectOp {
    /// Print the workspace dependency graph (Mermaid).
    Depgraph(RepoArg),
    /// Extract every function symbol from a built binary (DWARF) as JSON, and
    /// snapshot the symbols + callgraph into the warehouse (`dwarf_*` tables,
    /// git-SHA keyed) so they're queryable without the binary. `--no-save` to skip.
    Symbols(DwarfSymbolsArgs),
    /// Search extracted symbols by name substring.
    SymbolLookup(SymbolLookupArgs),
    /// List symbols defined in a source file (suffix match).
    DefinedIn(DefinedInArgs),
    /// Extract every inline-call edge from a built binary (DWARF) as JSON.
    Callgraph(SymbolsArgs),
    /// Extract direct-call edges from textual LLVM IR (`.ll` files or a dir).
    /// Run `cargo rustc -- --emit=llvm-ir` first to produce the IR.
    CallgraphLlvm(CallgraphLlvmArgs),
    /// List functions that call <name> (inline edges only).
    Callers(CallQueryArgs),
    /// List functions called by <name> (inline edges only).
    Callees(CallQueryArgs),
    /// Shortest call chain from <from> to <to>, if any.
    PathBetween(PathArgs),
}

#[derive(Args)]
struct CallQueryArgs {
    binary: PathBuf,
    name: String,
}

#[derive(Args)]
struct PathArgs {
    binary: PathBuf,
    from: String,
    to: String,
}

#[derive(Args)]
struct HistoryShowArgs {
    repo: String,
    /// Print the raw JSONL (one BenchRun per line) instead of the formatted view.
    #[arg(long)]
    json: bool,
    /// Show only the N most recent runs (0 = all).
    #[arg(long, default_value_t = 0)]
    limit: usize,
}

#[derive(Args)]
struct SymbolsArgs {
    /// Path to a debug-info-bearing binary (e.g. `target/debug/nornir`).
    binary: PathBuf,
}

#[derive(Args)]
struct DwarfSymbolsArgs {
    /// Path to a debug-info-bearing binary (e.g. `target/debug/nornir`).
    binary: PathBuf,
    /// Don't snapshot the extracted symbols + callgraph into the warehouse
    /// `dwarf_*` tables (default: persist, keyed by git SHA, so nothing computed
    /// is discarded and they're queryable later without the binary).
    #[arg(long = "no-save")]
    no_save: bool,
    /// Member repo to key the snapshot to (its HEAD SHA + label). Defaults to
    /// the whole workspace (`_workspace`). Only meaningful when saving (default).
    #[arg(long)]
    repo: Option<String>,
}

#[derive(Args)]
struct CallgraphLlvmArgs {
    /// `.ll` file or a directory to scan recursively for `.ll` files.
    path: PathBuf,
    /// Comma-separated crate roots; edges must touch at least one. Default: keep all.
    #[arg(long)]
    crates: Option<String>,
}

#[derive(Args)]
struct SymbolLookupArgs {
    binary: PathBuf,
    pattern: String,
    #[arg(long, default_value_t = 20)]
    limit: usize,
}

#[derive(Args)]
struct DefinedInArgs {
    binary: PathBuf,
    /// Path suffix to match, e.g. `bench/mod.rs`.
    file: String,
    #[arg(long, default_value_t = 50)]
    limit: usize,
}

#[derive(Subcommand)]
enum WarehouseOp {
    /// Import existing bench_history.jsonl for <repo> into the warehouse.
    ImportJsonl(RepoArg),
    /// Query bench runs for <repo> (Parquet → JSON, last N if --last).
    Query(WarehouseQueryArgs),
}

#[derive(Args)]
struct WarehouseQueryArgs {
    repo: String,
    #[arg(long)]
    machine: Option<String>,
    #[arg(long)]
    last: Option<usize>,
}

#[derive(Subcommand)]
enum IndexOp {
    /// Walk the workspace and bring the index up to date.
    Build(IndexBuildArgs),
    /// BM25 search over the index (optionally filter by --corpus/--repo).
    Search(IndexSearchArgs),
    /// Print per-corpus document counts.
    Stats,
    /// Snapshot the current tantivy index byte-for-byte into iceberg,
    /// keyed by HEAD git SHA. Idempotent per `(repo, sha)`.
    Snapshot(IndexSnapshotArgs),
    /// Restore a tantivy index from iceberg blobs back to disk.
    /// Pass `--sha` to pin a specific release, or omit to pull the
    /// most recent snapshot for `--repo`.
    Restore(IndexRestoreArgs),
    /// Push the locally-built tantivy index *up* to a running nornir-server,
    /// which writes it into its (locked) warehouse — the live-refresh path
    /// for a server's index (it can't open the warehouse a client built).
    /// Requires `NORNIR_SERVER`; embedded mode has no server to push to (use
    /// `index snapshot`). Idempotent server-side per `(repo, sha)`.
    Upload(IndexSnapshotArgs),
}

#[derive(Args)]
struct IndexBuildArgs {
    /// Wipe the index dir first and rebuild from scratch. Use after changing
    /// `[repo.*]` scope or `[storage].local_path` so out-of-scope documents
    /// indexed under the previous config are evicted (incremental builds only
    /// add/update in-scope docs; they never remove stale cross-repo hits).
    #[arg(long)]
    clean: bool,
    /// Don't historize the built index into the warehouse afterwards (default:
    /// snapshot it, so the index reaches the warehouse, not just the local cache).
    #[arg(long = "no-snapshot")]
    no_snapshot: bool,
}

#[derive(Args)]
struct IndexSnapshotArgs {
    /// Repo whose .nornir/cache/index/ to capture. Defaults to the
    /// workspace-wide index at <workspace>/.nornir/cache/index/.
    #[arg(long)]
    repo: Option<String>,
    /// Workspace name recorded in the iceberg row.
    #[arg(long, default_value = "workspace_holger")]
    workspace: String,
}

#[derive(Args)]
struct IndexRestoreArgs {
    /// Repo whose snapshot to restore.
    #[arg(long)]
    repo: Option<String>,
    /// Specific HEAD sha to restore. Defaults to the latest snapshot
    /// for `--repo`.
    #[arg(long)]
    sha: Option<String>,
    /// Destination directory. Defaults to the same `.nornir/cache/index/`
    /// path the index normally lives at.
    #[arg(long)]
    into: Option<PathBuf>,
}

#[derive(Args)]
struct IndexSearchArgs {
    query: String,
    #[arg(long)]
    corpus: Option<String>,
    #[arg(long)]
    repo: Option<String>,
    #[arg(long, default_value_t = 10)]
    limit: usize,
}

#[cfg(feature = "robot")]
#[derive(Subcommand)]
enum RobotOp {
    /// Run a scenario file against a live app via a WebDriver endpoint.
    Run(RobotRunArgs),
}

#[cfg(feature = "robot")]
#[derive(Args)]
struct RobotRunArgs {
    /// Repo under test (for the report's identity; resolved for its git sha).
    repo: String,
    /// Scenario file (plan-tests-DAG TOML).
    #[arg(long, default_value = "robot/scenarios.toml")]
    scenarios: PathBuf,
    /// App base URL (env BASE_URL also honored).
    #[arg(long, default_value = "http://127.0.0.1:3000")]
    base_url: String,
    /// WebDriver endpoint (geckodriver :4444 / chromedriver :9515).
    #[arg(long, default_value = "http://127.0.0.1:9515")]
    webdriver: String,
    /// Parse + print the DAG execution plan without driving a browser.
    #[arg(long)]
    dry_run: bool,
}

#[cfg(feature = "vector")]
#[derive(Subcommand)]
enum VectorOp {
    /// Embed a repo's Rust sources at HEAD into the warehouse (idempotent;
    /// only changed/new chunks are re-embedded). Needs an embedder feature.
    Index(VectorIndexArgs),
    /// Search by meaning. `--mode lexical|semantic|hybrid`.
    Search(VectorSearchArgs),
    /// Count materialized embeddings + index snapshots in the warehouse.
    Stats,
    /// Preflight the embedder + GPU: report NVIDIA driver / CUDA / cuDNN status,
    /// run a test embed, and advise what to fix if the GPU isn't engaged.
    Doctor,
    /// Pin a complete CUDA runtime set into /opt/nornir/cuda by copying the
    /// libs from wherever they exist on this box (pip nvidia wheels, ollama,
    /// a toolkit) — after this the GPU "just works" with no env. Usually sudo.
    SetupCuda(SetupCudaArgs),
}

#[cfg(feature = "vector")]
#[derive(Args)]
struct SetupCudaArgs {
    /// Target dir (a built-in CUDA search dir).
    #[arg(long, default_value = "/opt/nornir/cuda")]
    target: PathBuf,
}

#[cfg(feature = "vector")]
#[derive(Args)]
struct VectorIndexArgs {
    /// Repo to vectorize (must be declared in nornir.toml).
    repo: String,
}

#[cfg(feature = "vector")]
#[derive(Args)]
struct VectorSearchArgs {
    query: String,
    /// Repo to search. Required for semantic/hybrid (embeddings are per-repo);
    /// optional for lexical (defaults to the workspace index).
    #[arg(long)]
    repo: Option<String>,
    /// Pin a historical git SHA (time-travel). Defaults to the latest snapshot.
    #[arg(long)]
    sha: Option<String>,
    /// lexical (BM25) | semantic (vector) | hybrid (both, RRF-merged).
    #[arg(long, default_value = "semantic")]
    mode: String,
    #[arg(long, default_value_t = 10)]
    limit: usize,
}

#[derive(Args)]
struct RepoArg {
    repo: String,
}

#[derive(Args)]
struct PublishArgs {
    repo: String,
    #[arg(long)]
    dry_run: bool,
}

#[derive(Args)]
struct ReleaseRunArgs {
    /// Restrict to a single repo. Default: every repo in nornir.toml,
    /// reordered by the latest iceberg dep-graph snapshot.
    #[arg(long)]
    repo: Option<String>,
    /// Workspace name used to filter dep_graph snapshots
    /// (defaults to "workspace_holger" — matches the existing iceberg rows).
    #[arg(long, default_value = "workspace_holger")]
    workspace: String,
    /// Skip `cargo test --workspace` per repo.
    #[arg(long)]
    skip_tests: bool,
    /// Skip the nornir-bench example invocation per repo.
    #[arg(long)]
    skip_bench: bool,
    /// Skip the gate-all step per repo.
    #[arg(long)]
    skip_gates: bool,
    /// Skip writing the per-repo README.md from the freshly-persisted
    /// iceberg bench row (default: render is ON — set this to keep
    /// READMEs untouched).
    #[arg(long)]
    skip_render_docs: bool,
    /// Skip the per-repo warehouse capture phase. Default: ON — after
    /// gates pass, every source-fact projection at the release's git SHA
    /// is captured to iceberg (fat-client rule: nothing computed is
    /// discarded): (a) the syn knowledge map (symbols/calls + git-heat),
    /// (b) the workspace Tantivy index, byte-for-byte pinned to the SHA
    /// (the Urðr time-machine capture, restorable via
    /// `nornir index restore --sha <sha>`), and (c) semantic vectors
    /// (when this build has an embedder).
    #[arg(long)]
    skip_snapshot: bool,
    /// Skip `git commit` + `git push` of the freshly-rendered README
    /// (and any other staged release artifacts). Default OFF — once
    /// the gates pass, the docs are committed and pushed to `origin`
    /// so the published crates' git_sha lineage matches the public
    /// remote.
    #[arg(long)]
    skip_push: bool,
    /// Skip `cargo publish` for every crate in the repo's
    /// `publish_order`. Default OFF — once tests/gates/push succeed,
    /// the whole publish_order is walked. Crates already on
    /// crates.io are detected and skipped automatically (idempotent).
    #[arg(long)]
    skip_publish: bool,
    /// Pass `--dry-run` to every `cargo publish` invocation. Useful
    /// to validate a release end-to-end without actually shipping.
    #[arg(long)]
    dry_run_publish: bool,
    /// Re-capture the index + DWARF projections even when the warehouse
    /// already has a snapshot for this repo's release SHA. Default OFF:
    /// the capture phase is idempotent per `(repo, git_sha)` — re-running a
    /// release at an unchanged SHA reuses the existing snapshot (and its
    /// lineage pin) instead of re-writing identical blobs, since the
    /// warehouse can't compact them away later.
    #[arg(long)]
    recapture: bool,
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    // Launch/install verbs don't need a discovered workspace config.
    match &cli.cmd {
        Cmd::Serve(a) => return run_serve(a),
        Cmd::Viz(a) => return run_viz(a),
        Cmd::Install { op } => return run_install(op),
        Cmd::Key { op } => return run_key(op),
        Cmd::Workspace { op } => return run_workspace(op),
        _ => {}
    }
    let loaded = load_config(cli.config.as_deref())?;
    match cli.cmd {
        Cmd::Serve(_) | Cmd::Viz(_) | Cmd::Install { .. } | Cmd::Key { .. } | Cmd::Workspace { .. } => {
            unreachable!("handled before load_config")
        }
        Cmd::Repos => {
            // Client mode lists the *server's* repos; embedded lists local config.
            if let Some(server) = server_target() {
                for name in list_repos_remote(&server)? {
                    println!("{name}");
                }
            } else {
                for name in loaded.nornir.repo.keys() {
                    println!("{name}");
                }
            }
        }
        Cmd::Guard { op } => run_guard(op, &loaded)?,
        Cmd::Bench { op } => run_bench(op, &loaded)?,
        Cmd::Release { op } => run_release(op, &loaded)?,
        Cmd::Docs { op } => run_docs(op, &loaded)?,
        Cmd::Introspect { op } => run_introspect(op, &loaded)?,
        Cmd::Warehouse { op } => run_warehouse(op, &loaded)?,
        Cmd::Index { op } => run_index(op, &loaded)?,
        #[cfg(feature = "vector")]
        Cmd::Vector { op } => run_vector(op, &loaded)?,
        #[cfg(feature = "robot")]
        Cmd::Robot { op } => run_robot(op, &loaded)?,
        Cmd::Knowledge { op } => run_knowledge(op, &loaded)?,
        Cmd::Map(a) => run_map(&a.repo, &loaded)?,
        Cmd::Funnel { op } => run_funnel(op, &loaded)?,
    }
    Ok(())
}

/// `nornir funnel …` — human CLI over the idea→plan funnel (`src/funnel/`),
/// mirroring the MCP `funnel_*` tools. Events land in the same Iceberg
/// `funnel_events` table the MCP/server use.
fn run_funnel(op: FunnelOp, loaded: &Loaded) -> Result<()> {
    use chrono::Utc;
    use nornir::funnel::{self, Event, IdeaId, NodeId, NodeStatus, PlanId, PlanStatus};

    let mut store = funnel::Store::open(iceberg_warehouse_root(loaded))?;
    match op {
        FunnelOp::Submit { text, file, source } => {
            // Precedence: --file → positional text → stdin (pipe).
            let text = match (file, text) {
                (Some(path), _) => std::fs::read_to_string(&path)
                    .with_context(|| format!("read krav/prompt file {}", path.display()))?,
                (None, Some(t)) => t,
                (None, None) => {
                    use std::io::Read;
                    let mut buf = String::new();
                    std::io::stdin().read_to_string(&mut buf).context("read idea text from stdin")?;
                    buf
                }
            };
            let text = text.trim().to_string();
            if text.is_empty() {
                anyhow::bail!("empty idea text — pass a krav/prompt as an arg, --file, or via stdin");
            }
            let id = IdeaId::seq(store.funnel.next_idea);
            store.record(Event::IdeaSubmitted {
                id: id.clone(),
                source: source.unwrap_or_else(|| "cli".into()),
                text,
                refs: Vec::new(),
                ts: Utc::now(),
            })?;
            println!("{}", id.as_str());
        }
        FunnelOp::Plan { idea_id, summary } => {
            let plan_id = PlanId::seq(store.funnel.next_plan);
            store.record(Event::PlanCreated {
                id: plan_id.clone(),
                idea_id: IdeaId::new(idea_id),
                summary,
                planner: "cli".into(),
                ts: Utc::now(),
            })?;
            store.record(Event::PlanStatusChanged {
                plan_id: plan_id.clone(),
                status: PlanStatus::Active,
                why: None,
                ts: Utc::now(),
            })?;
            println!("{}", plan_id.as_str());
        }
        FunnelOp::Node { plan_id, kind, title, targets, needs, prompt } => {
            let plan_id = PlanId::new(plan_id);
            let node_id = NodeId::seq(store.funnel.next_node);
            let mut params = serde_json::Map::new();
            if let Some(t) = title {
                params.insert("title".into(), serde_json::Value::String(t));
            }
            store.record(Event::NodeAdded {
                plan_id: plan_id.clone(),
                node_id: node_id.clone(),
                kind,
                params,
                targets,
                prompt_excerpt: prompt,
                ts: Utc::now(),
            })?;
            for from in &needs {
                store.record(Event::EdgeAdded {
                    plan_id: plan_id.clone(),
                    from_node: NodeId::new(from.clone()),
                    to_node: node_id.clone(),
                    ts: Utc::now(),
                })?;
            }
            store.funnel.promote_ready();
            println!("{}", node_id.as_str());
        }
        FunnelOp::Link { plan_id, from, to } => {
            store.record(Event::EdgeAdded {
                plan_id: PlanId::new(plan_id),
                from_node: NodeId::new(from),
                to_node: NodeId::new(to),
                ts: Utc::now(),
            })?;
            store.funnel.promote_ready();
            println!("ok");
        }
        FunnelOp::Next => {
            store.funnel.promote_ready();
            let next = funnel::topo_ready(&mut store.funnel);
            println!("{}", serde_json::to_string_pretty(&next)?);
        }
        FunnelOp::Status { plan_id, node_id, status, why } => {
            let st = match status.as_str() {
                "ready" => NodeStatus::Ready,
                "active" | "in_progress" => NodeStatus::InProgress,
                "blocked" => NodeStatus::Blocked,
                "done" => NodeStatus::Done,
                "failed" | "abandoned" => NodeStatus::Failed,
                other => bail!("unknown status {other:?}; expected ready|active|blocked|done|failed"),
            };
            store.record(Event::NodeStatusChanged {
                plan_id: PlanId::new(plan_id),
                node_id: NodeId::new(node_id),
                status: st,
                why,
                ts: Utc::now(),
            })?;
            store.funnel.promote_ready();
            println!("ok");
        }
        FunnelOp::Show => {
            let f = &store.funnel;
            println!("ideas: {}, plans: {}", f.ideas.len(), f.plans.len());
            for (iid, idea) in &f.ideas {
                println!("  {} [{}] {}", iid.as_str(), idea.source, idea.text);
            }
            for (pid, plan) in &f.plans {
                println!(
                    "  {} (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("");
                    println!("    {} [{:?}] {} {}", nid.as_str(), n.status, n.kind, title);
                }
            }
        }
    }
    Ok(())
}

/// `nornir map <repo>` — run the full index pipeline for one appointed member:
/// 1. knowledge scan (symbols + git-heat) → persist to the warehouse;
/// 2. build the workspace code index, scoped to the appointed `[repo.*]` members;
/// 3. snapshot that index into iceberg, keyed to this member's HEAD SHA;
/// 4. embed + persist semantic vectors (when the build has an embedder).
fn run_map(repo: &str, loaded: &Loaded) -> Result<()> {
    let _ = repo_or_err(loaded, repo)?; // must be an appointed member
    let warehouse_root = iceberg_warehouse_root(loaded);
    let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&warehouse_root)
        .with_context(|| format!("open warehouse at {}", warehouse_root.display()))?;

    // 1. Knowledge scan → persist.
    let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, repo);
    let res = nornir::knowledge::scan_all(&repo_root, repo)?;
    wh.append_symbol_scan(&res.symbols)?;
    wh.append_git_heat_scan(&res.git)?;
    println!(
        "scan: symbols={} calls={} files={} (symbol_snapshot={} git_snapshot={})",
        res.symbols.symbols.len(),
        res.symbols.calls.len(),
        res.git.files.len(),
        res.symbols.snapshot_id,
        res.git.snapshot_id,
    );

    // 2. Build the workspace code index, scoped to the appointed members.
    let index_dir = cache_index_dir(loaded);
    let repos: Vec<String> = loaded.nornir.repo.keys().cloned().collect();
    let idx = index::Index::open_at(&loaded.workspace_root, &index_dir)?.with_repo_scope(repos);
    let stats = idx.build()?;
    println!(
        "index: scanned={} added={} updated={} unchanged={}",
        stats.scanned, stats.added, stats.updated, stats.skipped_unchanged,
    );

    // 3. Snapshot the index into iceberg, keyed to this member's HEAD.
    let (sha, branch) =
        read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
    let workspace = workspace_name(loaded);
    let snap = nornir::index::snapshot::snapshot_to_iceberg(
        &wh, &workspace, repo, &sha, &branch, &index_dir,
    )?;
    println!(
        "✓ mapped {} — snapshot {} ({} blob(s), {} bytes, sha={})",
        repo,
        snap.snapshot_id,
        snap.blob_count,
        snap.total_bytes,
        &snap.git_sha[..snap.git_sha.len().min(12)],
    );

    // 4. Semantic vectors → persist (only when this build has an embedder).
    //    Keeps `map` a full fat-client capture: everything computable from the
    //    source lands in the warehouse in one shot. No-op (with a hint) on a
    //    build without `embed-tract`/`embed-ort`.
    map_vectors(&wh, &workspace, repo, &repo_root, &sha, &branch)?;
    Ok(())
}

/// Vector-embed step of `nornir map` — embeds + persists semantic vectors for
/// the member. Gated: this variant runs when the build has an embedder.
#[cfg(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort")))]
fn map_vectors(
    wh: &nornir::warehouse::iceberg::IcebergWarehouse,
    workspace: &str,
    repo: &str,
    repo_root: &std::path::Path,
    sha: &str,
    branch: &str,
) -> Result<()> {
    use nornir::vector::store;
    let files = store::collect_rust_sources(repo_root);
    if files.is_empty() {
        return Ok(());
    }
    let embedder = load_vector_embedder()?;
    let opts = nornir::vector::chunk::ChunkOptions::default();
    let snap = store::index_repo(
        wh,
        &store::RepoRef { workspace, repo, git_sha: sha, branch, complete: true },
        &files,
        &opts,
        &*embedder,
    )?;
    println!(
        "vectors: snapshot {}{} occurrences, {} new vector(s) embedded ({})",
        snap.snapshot_id, snap.occurrences, snap.new_vectors, vector_backend_name(),
    );
    Ok(())
}

/// No-embedder build: `map` skips vectors with a one-line hint (non-fatal).
#[cfg(not(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort"))))]
fn map_vectors(
    _wh: &nornir::warehouse::iceberg::IcebergWarehouse,
    _workspace: &str,
    _repo: &str,
    _repo_root: &std::path::Path,
    _sha: &str,
    _branch: &str,
) -> Result<()> {
    println!("vectors: skipped (build without embedder; `--features embed-tract` or `embed-ort` to enable)");
    Ok(())
}

/// Discover this repo's built binaries (via cargo metadata) and snapshot each
/// one's DWARF facts (symbols + inline-call edges) into the warehouse, keyed by
/// git SHA. Best-effort: returns the first snapshot id (for the `release_lineage`
/// pin), or `None` when no built binary with debug info is found. Prefers the
/// release artifact, falls back to debug — whatever the test/bench build left in
/// `target/`. Prints one line per binary.
fn capture_dwarf(
    wh: &nornir::warehouse::iceberg::IcebergWarehouse,
    workspace: &str,
    repo: &str,
    repo_root: &std::path::Path,
    sha: &str,
    branch: &str,
    workspace_root: &std::path::Path,
    warehouse_root: &std::path::Path,
) -> Option<String> {
    use cargo_metadata::MetadataCommand;
    let meta = match MetadataCommand::new().current_dir(repo_root).no_deps().exec() {
        Ok(m) => m,
        Err(e) => {
            println!("  🔬 dwarf: ⚠ cargo metadata failed: {e}");
            return None;
        }
    };
    let mut bins: Vec<String> = Vec::new();
    for p in &meta.packages {
        for t in &p.targets {
            if t.is_bin() && !bins.contains(&t.name) {
                bins.push(t.name.clone());
            }
        }
    }
    if bins.is_empty() {
        return None;
    }
    let target_dir = meta.target_directory.as_std_path();
    let mut first: Option<String> = None;
    for bin in &bins {
        let cands = [target_dir.join("release").join(bin), target_dir.join("debug").join(bin)];
        let Some(path) = cands.iter().find(|p| p.is_file()) else {
            continue; // not built in this run — best-effort, skip silently
        };
        let syms = match nornir::introspect::artifact::extract_symbols(path, workspace_root) {
            Ok(s) if !s.is_empty() => s,
            Ok(_) => continue, // stripped / no debug info
            Err(e) => {
                println!("  🔬 dwarf: ⚠ {bin}: {e:#}");
                continue;
            }
        };
        let calls = nornir::introspect::callgraph_dwarf::extract_callgraph(path, workspace_root)
            .unwrap_or_default();
        let facts = nornir::introspect::persist::DwarfFacts { symbols: syms, calls };
        let cache_dir = warehouse_root
            .parent()
            .unwrap_or(warehouse_root)
            .join("cache/dwarf")
            .join(repo)
            .join(bin);
        match nornir::introspect::persist::snapshot_facts(
            wh, workspace, repo, sha, branch, &facts, &cache_dir,
        ) {
            Ok(snap) => {
                println!(
                    "  🔬 dwarf: {bin}{} symbol(s), {} edge(s), snapshot {}",
                    facts.symbols.len(),
                    facts.calls.len(),
                    snap.snapshot_id,
                );
                first.get_or_insert(snap.snapshot_id.to_string());
            }
            Err(e) => println!("  🔬 dwarf: ⚠ {bin}: snapshot failed: {e:#}"),
        }
    }
    first
}

fn run_knowledge(op: KnowledgeOp, loaded: &Loaded) -> Result<()> {
    match op {
        KnowledgeOp::Scan { repo, no_save } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let res = nornir::knowledge::scan_all(&repo_root, &repo)?;
            println!(
                "ok: symbols={} calls={} features={} files={}",
                res.symbols.symbols.len(),
                res.symbols.calls.len(),
                res.symbols.features.len(),
                res.git.files.len(),
            );
            // Top-10 hottest files for at-a-glance feedback.
            let mut top = res.git.files.iter().collect::<Vec<_>>();
            top.sort_by_key(|r| -r.commits_total);
            for r in top.iter().take(10) {
                println!(
                    "  {:60} commits={} 30d={} authors={}",
                    r.file, r.commits_total, r.commits_30d, r.authors_total
                );
            }
            if !no_save {
                let warehouse_root = loaded.warehouse_root();
                let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&warehouse_root)
                    .with_context(|| format!("open warehouse at {}", warehouse_root.display()))?;
                wh.append_symbol_scan(&res.symbols)?;
                wh.append_git_heat_scan(&res.git)?;
                println!("persisted: symbol_snapshot={} git_snapshot={}",
                    res.symbols.snapshot_id, res.git.snapshot_id);
            }
        }
        KnowledgeOp::Query { repo, kind, arg, to, limit } => {
            if let Some(server) = server_target() {
                return knowledge_query_remote(&server, &repo, &kind, &arg, to.as_deref(), limit);
            }
            let warehouse_root = loaded.warehouse_root();
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&warehouse_root)
                .with_context(|| format!("open warehouse at {}", warehouse_root.display()))?;
            let view = nornir::knowledge::query::load_latest(&wh, &repo)?;
            match kind.as_str() {
                "callers" => {
                    let hits = view.callers_of(&arg);
                    println!("callers of `{arg}` ({}):", hits.len());
                    for c in hits.iter().take(limit) {
                        println!("  {}{}  [{}:{}]", c.caller_path, c.callee_ident, c.file, c.line);
                    }
                }
                "callees" => {
                    let hits = view.callees_of(&arg);
                    println!("callees of `{arg}` ({}):", hits.len());
                    for c in hits.iter().take(limit) {
                        println!("  {}{}  [{}:{}]", c.caller_path, c.callee_ident, c.file, c.line);
                    }
                }
                "defined-in" => {
                    let hits = view.defined_in(&arg);
                    println!("symbols defined in `*{arg}` ({}):", hits.len());
                    for s in hits.iter().take(limit) {
                        println!("  {:8} {}::{}  [{}:{}]", s.item_kind, s.module_path, s.item_name, s.file, s.line);
                    }
                }
                "lookup" => {
                    let hits = view.symbol_lookup(&arg, limit);
                    println!("symbols matching `{arg}` ({} shown):", hits.len());
                    for s in &hits {
                        let sig = s.signature.as_deref().unwrap_or("");
                        println!("  {:8} {}  [{}:{}]  {}", s.item_kind, s.item_name, s.file, s.line, sig);
                    }
                }
                "path" => {
                    let to = to.as_deref()
                        .context("`path` query needs a target: pass --to <function>")?;
                    match view.call_path(&arg, to) {
                        Some(p) => {
                            println!("call path `{arg}` → `{to}` ({} hops):", p.len().saturating_sub(1));
                            println!("  {}", p.join(""));
                        }
                        None => println!("no call path from `{arg}` to `{to}`"),
                    }
                }
                other => bail!("unknown query kind `{other}` (want: callers|callees|defined-in|lookup|path)"),
            }
        }
    }
    Ok(())
}

fn load_config(explicit: Option<&Path>) -> Result<Loaded> {
    // Resolution order (matches `nornir-server`): explicit `--config`, then the
    // `NORNIR_CONFIG` env var, then cwd discovery. Previously the CLI honored
    // only `--config`/discovery, so `NORNIR_CONFIG=… nornir …` silently ran
    // against the discovered (wrong) workspace.
    if let Some(p) = explicit {
        return config::load_explicit(p);
    }
    if let Some(p) = std::env::var_os("NORNIR_CONFIG") {
        return config::load_explicit(Path::new(&p));
    }
    let cwd = std::env::current_dir()?;
    config::discover(&cwd)
}

// ───────────────────────── serve + install (launch / deploy) ───────────────

/// Path to a sibling binary next to the current executable.
fn sibling_bin(name: &str) -> Result<PathBuf> {
    let exe = std::env::current_exe().context("locate current executable")?;
    Ok(exe.parent().unwrap_or_else(|| Path::new(".")).join(name))
}

/// Copy a binary onto the system (mode 0755) so a service can exec it
/// independently of the build tree. Writes to a temp path then renames, so
/// replacing a running binary is atomic and never `ETXTBSY`.
#[cfg(unix)]
fn install_binary(src: &Path, dst: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let tmp = dst.with_extension("new");
    std::fs::copy(src, &tmp)
        .with_context(|| format!("copy {} -> {}", src.display(), tmp.display()))?;
    std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
    std::fs::rename(&tmp, dst)
        .with_context(|| format!("install {} -> {}", src.display(), dst.display()))?;
    Ok(())
}

/// `nornir serve` — launch `nornir-server`, replacing this process so a
/// supervisor (systemd, a shell) manages the server directly.
#[cfg(unix)]
fn run_serve(a: &ServeArgs) -> Result<()> {
    use std::os::unix::process::CommandExt;
    let bin = match &a.server_bin {
        Some(p) => p.clone(),
        None => sibling_bin("nornir-server")?,
    };
    if !bin.exists() {
        bail!(
            "nornir-server not found at {} — build it with `cargo build --features server`, \
             or pass --server-bin",
            bin.display()
        );
    }
    let mut cmd = std::process::Command::new(&bin);
    if let Some(c) = &a.config {
        cmd.env("NORNIR_CONFIG", c);
    }
    if let Some(ad) = &a.addr {
        cmd.env("NORNIR_SERVER_ADDR", ad);
    }
    if let Some(t) = &a.token {
        cmd.env("NORNIR_SERVER_TOKEN", t);
    }
    eprintln!("nornir: exec {}", bin.display());
    Err(anyhow!("exec {}: {}", bin.display(), cmd.exec())) // exec only returns on failure
}

#[cfg(not(unix))]
fn run_serve(_a: &ServeArgs) -> Result<()> {
    bail!("`nornir serve` is only supported on unix")
}

/// `nornir viz` — launch the `urdr-threads` visualizer, replacing this process.
/// Inherits `NORNIR_SERVER`/`NORNIR_SERVER_TOKEN`/`NORNIR_WORKSPACE` from the env.
#[cfg(unix)]
fn run_viz(a: &VizArgs) -> Result<()> {
    use std::os::unix::process::CommandExt;
    let bin = match &a.viz_bin {
        Some(p) => p.clone(),
        None => {
            let sib = sibling_bin("urdr-threads")?;
            if sib.exists() {
                sib
            } else {
                PathBuf::from("urdr-threads") // fall back to PATH (e.g. /usr/local/bin)
            }
        }
    };
    let mut cmd = std::process::Command::new(&bin);
    if let Some(w) = &a.workspace {
        cmd.arg("--workspace").arg(w);
    }
    if let Some(wh) = &a.warehouse {
        cmd.arg("--warehouse").arg(wh);
    }
    eprintln!("nornir: exec {}", bin.display());
    Err(anyhow!(
        "exec {}: {} — is the viz built? (`cargo build --features viz`, or \
         `cargo install nornir --features viz`)",
        bin.display(),
        cmd.exec()
    ))
}

#[cfg(not(unix))]
fn run_viz(_a: &VizArgs) -> Result<()> {
    bail!("`nornir viz` is only supported on unix")
}

fn run_install(op: &InstallOp) -> Result<()> {
    match op {
        InstallOp::Systemd(a) => run_install_systemd(a),
        InstallOp::Uninstall(a) => run_uninstall(a),
    }
}

/// `nornir install uninstall` — tear down the systemd service. Root-only.
#[cfg(unix)]
fn run_uninstall(a: &UninstallArgs) -> Result<()> {
    if unsafe { geteuid() } != 0 {
        bail!("`nornir install uninstall` must run as root. Re-run with sudo.");
    }
    // Stop + disable (ignore errors if already stopped / never enabled).
    let _ = std::process::Command::new("systemctl").args(["disable", "--now", "nornir.service"]).status();
    let _ = std::process::Command::new("systemctl").args(["reset-failed", "nornir.service"]).status();

    let removed = |p: &str| {
        let existed = Path::new(p).exists();
        let _ = std::fs::remove_file(p);
        existed
    };
    let unit = removed("/etc/systemd/system/nornir.service");
    let _ = std::fs::remove_dir_all("/etc/nornir");
    systemctl(&["daemon-reload"])?;

    println!("✓ uninstalled nornir systemd service");
    println!("  unit       : {}", if unit { "removed" } else { "absent" });
    println!("  env        : /etc/nornir removed");

    if a.purge {
        for bin in ["nornir-server", "nornir", "urdr-threads"] {
            let _ = std::fs::remove_file(format!("/usr/local/bin/{bin}"));
        }
        let _ = std::fs::remove_dir_all(NORNIR_HOME);
        // Remove the system user (best-effort; deploy tool).
        let _ = std::process::Command::new("userdel").arg(&a.user).status();
        println!("  purged     : /usr/local/bin/{{nornir,nornir-server,urdr-threads}}, {NORNIR_HOME}, user `{}`", a.user);
    } else {
        println!("  kept       : {NORNIR_HOME} (data + key), /usr/local/bin binaries, user `{}`", a.user);
        println!("  (use --purge to remove those too)");
    }
    Ok(())
}

#[cfg(not(unix))]
fn run_uninstall(_a: &UninstallArgs) -> Result<()> {
    bail!("`nornir install uninstall` is linux-only")
}

// ── SSH identity (server-monitored git poll/push) ───────────────────────────
//
// The `nornir` server fetches (and later pushes to) member git URLs over SSH
// using a keypair it owns. Generated in pure Rust — no `ssh-keygen` subprocess.
// On a systemd install the keypair lives in the nornir user's `.ssh` dir under
// its state home; `nornir key show` prints the public half to register as a
// deploy key on each monitored repo.

/// State home for the `nornir` system user (created by `install systemd`).
/// The `nornir` service user's home — the single root for ALL its state
/// (warehouses, registry, the staged config, the SSH key). This is the user's
/// actual home dir, not a `/var/lib` path.
const NORNIR_HOME: &str = "/home/nornir";

/// Resolve the `.ssh` dir holding nornir's git identity. Honors
/// `NORNIR_SSH_DIR`; on a real install uses the system home; otherwise a
/// per-user dev location that never touches the operator's own `~/.ssh`.
fn nornir_ssh_dir() -> PathBuf {
    if let Some(d) = std::env::var_os("NORNIR_SSH_DIR") {
        return PathBuf::from(d);
    }
    #[cfg(unix)]
    {
        let sys = Path::new(NORNIR_HOME).join(".ssh");
        if sys.exists() || unsafe { geteuid() } == 0 {
            return sys;
        }
    }
    if let Some(home) = std::env::var_os("HOME") {
        return Path::new(&home).join(".nornir/ssh");
    }
    PathBuf::from(".nornir/ssh")
}

/// Generate an ed25519 keypair (pure Rust) into `dir` in OpenSSH format.
/// Idempotent: an existing key is preserved. Returns `true` if newly created.
fn generate_keypair(dir: &Path) -> Result<bool> {
    let priv_path = dir.join("id_ed25519");
    let pub_path = dir.join("id_ed25519.pub");
    if priv_path.exists() {
        return Ok(false);
    }
    std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).ok();
    }

    let host = std::fs::read_to_string("/etc/hostname")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "localhost".to_string());

    let mut key = ssh_key::PrivateKey::random(&mut rand_core::OsRng, ssh_key::Algorithm::Ed25519)
        .context("generate ed25519 key")?;
    key.set_comment(format!("nornir@{host}"));

    let openssh = key
        .to_openssh(ssh_key::LineEnding::LF)
        .context("encode private key (OpenSSH)")?;
    std::fs::write(&priv_path, openssh.as_bytes())
        .with_context(|| format!("write {}", priv_path.display()))?;

    let pubtxt = key
        .public_key()
        .to_openssh()
        .context("encode public key (OpenSSH)")?;
    std::fs::write(&pub_path, format!("{pubtxt}\n"))
        .with_context(|| format!("write {}", pub_path.display()))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&priv_path, std::fs::Permissions::from_mode(0o600))?;
        std::fs::set_permissions(&pub_path, std::fs::Permissions::from_mode(0o644))?;
    }
    Ok(true)
}

/// `nornir key {show,path,generate}` — manage the git SSH identity.
fn run_key(op: &KeyOp) -> Result<()> {
    let dir = nornir_ssh_dir();
    let pub_path = dir.join("id_ed25519.pub");
    match op {
        KeyOp::Path => println!("{}", pub_path.display()),
        KeyOp::Generate => {
            let created = generate_keypair(&dir)?;
            println!(
                "{} {}",
                if created { "✓ generated" } else { "• already present:" },
                pub_path.display()
            );
            print!("{}", std::fs::read_to_string(&pub_path)?);
        }
        KeyOp::Show => {
            if !pub_path.exists() {
                bail!(
                    "no public key at {} — run `nornir key generate` (or \
                     `nornir install systemd`, which creates one)",
                    pub_path.display()
                );
            }
            print!("{}", std::fs::read_to_string(&pub_path)?);
        }
    }
    Ok(())
}

/// Server root holding the registry + per-workspace `{git,builds}` dirs.
/// `NORNIR_ROOT` overrides; default matches `[server].root`'s default.
fn server_root() -> PathBuf {
    std::env::var_os("NORNIR_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/var/lib/nornir/workspaces"))
}

/// `nornir workspace {ls,show,register,rm,fetch}` — manage the server's
/// registry. Routes to the server over gRPC when `NORNIR_SERVER` is set
/// (so it works fat/embedded *and* remote, like every other verb), else opens
/// the local registry embedded.
fn run_workspace(op: &WorkspaceOp) -> Result<()> {
    #[cfg(any(feature = "mcp", feature = "server"))]
    if let Some(server) = server_target() {
        return run_workspace_remote(&server, op);
    }

    use nornir::registry::{Mode, Registry, Workspace};

    let reg = Registry::open(&server_root())?;
    match op {
        WorkspaceOp::Ls => {
            let all = reg.list()?;
            if all.is_empty() {
                println!("(no workspaces registered — `nornir workspace register …`)");
                return Ok(());
            }
            println!("{:<20} {:<10} {:>7}  {}", "NAME", "MODE", "MEMBERS", "LAST SYNCED");
            for ws in all {
                let last = ws
                    .members
                    .iter()
                    .map(|m| m.last_synced.as_str())
                    .filter(|s| !s.is_empty())
                    .max()
                    .unwrap_or("never");
                println!(
                    "{:<20} {:<10} {:>7}  {}",
                    ws.name,
                    ws.mode.as_str(),
                    ws.members.len(),
                    last
                );
            }
        }
        WorkspaceOp::Show { name } => {
            let ws = reg
                .get(name)?
                .ok_or_else(|| anyhow!("no workspace `{name}` in the registry"))?;
            println!("{}", serde_json::to_string_pretty(&ws)?);
        }
        WorkspaceOp::Register {
            name,
            descriptor,
            monitored,
            external,
            poll,
        } => {
            if *monitored && *external {
                bail!("--monitored and --external are mutually exclusive");
            }
            let mode = if *monitored {
                Mode::Monitored
            } else if *external {
                Mode::External
            } else {
                Mode::Pushed
            };

            let created_at = reg.get(name)?.map(|w| w.created_at);
            let ws = Workspace::new(
                name.clone(),
                descriptor.clone(),
                mode,
                poll.clone().unwrap_or_default(),
                created_at,
            );
            reg.upsert(&ws)?;
            println!(
                "✓ registered `{}` ({}, {} member(s)) → {}/{}/{{git,builds}}",
                ws.name,
                ws.mode.as_str(),
                ws.members.len(),
                server_root().display(),
                ws.name
            );
        }
        WorkspaceOp::Rm { name } => {
            if reg.remove(name)? {
                println!("✓ removed `{name}`");
            } else {
                bail!("no workspace `{name}` in the registry");
            }
        }
        WorkspaceOp::Fetch { name } => {
            let report = nornir::monitor::fetch_workspace(&reg, &server_root(), name)?;
            // Re-read the row to print each member's resulting SHA/state.
            let ws = reg
                .get(name)?
                .ok_or_else(|| anyhow!("no workspace `{name}` in the registry"))?;
            for m in &ws.members {
                if m.remote.is_empty() {
                    continue;
                }
                let sha = if m.last_seen_sha.is_empty() {
                    "".to_string()
                } else {
                    m.last_seen_sha[..m.last_seen_sha.len().min(12)].to_string()
                };
                let state = if report.changed.contains(&m.name) {
                    "(changed)"
                } else if m.sync_state.starts_with("error") {
                    "(error)"
                } else {
                    "(unchanged)"
                };
                println!("  {:<16} {:<12}  {}", m.name, sha, state);
            }
            for (m, e) in &report.errors {
                eprintln!("    {m}: {e}");
            }
            println!(
                "✓ fetched `{}` — {} of {} member(s) changed",
                ws.name,
                report.changed.len(),
                report.fetched
            );
        }
    }
    Ok(())
}

/// Look up `(uid, gid)` for a user from `/etc/passwd` — pure parse, no subprocess.
#[cfg(unix)]
fn passwd_ids(user: &str) -> Option<(u32, u32)> {
    let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
    for line in passwd.lines() {
        let mut f = line.split(':');
        if f.next() == Some(user) {
            let _ = f.next(); // password placeholder
            let uid = f.next()?.parse().ok()?;
            let gid = f.next()?.parse().ok()?;
            return Some((uid, gid));
        }
    }
    None
}

#[cfg(unix)]
extern "C" {
    fn chown(path: *const std::os::raw::c_char, owner: u32, group: u32) -> i32;
}

/// Recursively `chown` a tree to `(uid, gid)` via libc — no `chown` subprocess.
#[cfg(unix)]
fn chown_recursive(path: &Path, uid: u32, gid: u32) -> Result<()> {
    use std::os::unix::ffi::OsStrExt;
    let c = std::ffi::CString::new(path.as_os_str().as_bytes())
        .with_context(|| format!("path has interior NUL: {}", path.display()))?;
    if unsafe { chown(c.as_ptr(), uid, gid) } != 0 {
        bail!("chown {} failed: {}", path.display(), std::io::Error::last_os_error());
    }
    if path.is_dir() {
        for entry in std::fs::read_dir(path).with_context(|| format!("read {}", path.display()))? {
            chown_recursive(&entry?.path(), uid, gid)?;
        }
    }
    Ok(())
}

#[cfg(unix)]
extern "C" {
    fn geteuid() -> u32;
}

/// `nornir install systemd` — create a `nornir` system user + a systemd unit that
/// runs `nornir-server`. Root-only; the first taste of the build-installer.
#[cfg(unix)]
fn run_install_systemd(a: &SystemdArgs) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    if unsafe { geteuid() } != 0 {
        bail!(
            "`nornir install systemd` must run as root — it creates the `{}` system user \
             and writes /etc/systemd/system. Re-run with sudo.",
            a.user
        );
    }
    let server_src = match &a.server_bin {
        Some(p) => p.clone(),
        None => sibling_bin("nornir-server")?,
    };
    if !server_src.exists() {
        bail!(
            "nornir-server not found at {} — build with `cargo build --features server`, \
             or pass --server-bin",
            server_src.display()
        );
    }

    // Install the binaries ON the system. The service must NOT exec from the
    // build tree (e.g. a removable drive the `nornir` user can't execute from →
    // 203/EXEC). Copy nornir-server (and the `nornir` CLI + `urdr-threads` viz
    // when present) to /usr/local/bin and point the unit there.
    let bindir = Path::new("/usr/local/bin");
    std::fs::create_dir_all(bindir).ok();
    let server_bin = bindir.join("nornir-server");
    install_binary(&server_src, &server_bin)
        .with_context(|| format!("install nornir-server to {}", server_bin.display()))?;
    let mut installed = vec![server_bin.clone()];
    if let Ok(cli) = std::env::current_exe() {
        let dst = bindir.join("nornir");
        if install_binary(&cli, &dst).is_ok() {
            installed.push(dst);
        }
    }
    if let Some(viz) = server_src.parent().map(|p| p.join("urdr-threads")) {
        if viz.exists() {
            let dst = bindir.join("urdr-threads");
            if install_binary(&viz, &dst).is_ok() {
                installed.push(dst);
            }
        }
    }

    let config: Option<PathBuf> = match &a.config {
        Some(p) => Some(
            p.canonicalize()
                .with_context(|| format!("config not found: {}", p.display()))?,
        ),
        None => None,
    };
    if config.is_none() && a.monitor.is_empty() && a.root.is_none() {
        bail!("nothing to serve: pass --monitor <name>=<descriptor> (self-sync) and/or --config <nornir.toml> (served workspace)");
    }

    // Update-vs-fresh: re-running this command overwrites an existing install.
    let unit_path = Path::new("/etc/systemd/system/nornir.service");
    let env_path = Path::new("/etc/nornir/nornir.env");
    let updating = unit_path.exists();

    ensure_system_user(&a.user)?;

    // SSH identity for git poll/push (server-monitored mode). Pure-Rust ed25519,
    // preserved on update exactly like the token below.
    let ssh_dir = Path::new(NORNIR_HOME).join(".ssh");
    std::fs::create_dir_all(NORNIR_HOME).context("create nornir state home")?;
    let key_generated = generate_keypair(&ssh_dir)?;
    let pub_path = ssh_dir.join("id_ed25519.pub");

    // The service runs as the `nornir` system user, whose home is NORNIR_HOME. It
    // cannot read arbitrary paths (e.g. a removable drive mounted 0700 for your
    // login user). So for a MONITORING install we STAGE everything the service
    // reads into nornir's own home — copy the config and any file-based --monitor
    // descriptor under NORNIR_HOME, and pin the default workspace's warehouse
    // there (writable) — and run with WorkingDirectory=NORNIR_HOME. A plain
    // (non-monitoring) install keeps reading the config in place.
    let monitoring = !a.monitor.is_empty() || a.root.is_some();
    let (effective_config, default_warehouse, monitor_entries) = if monitoring {
        // Stage the config (if any) into nornir's home; pin the default warehouse
        // there; stage file descriptors. Pure-monitor installs need no config.
        let staged_config = config.as_ref().map(|c| {
            let dst = Path::new(NORNIR_HOME).join("server.toml");
            let _ = std::fs::copy(c, &dst);
            dst
        });
        let dw = Path::new(NORNIR_HOME).join("default").join("warehouse");
        std::fs::create_dir_all(&dw).ok();
        let desc_dir = Path::new(NORNIR_HOME).join("descriptors");
        std::fs::create_dir_all(&desc_dir).ok();
        let mut entries = Vec::new();
        for entry in &a.monitor {
            let (name, descriptor) = entry
                .split_once('=')
                .ok_or_else(|| anyhow!("--monitor `{entry}` must be name=descriptor"))?;
            let dp = Path::new(descriptor);
            if dp.is_file() {
                let staged = desc_dir.join(format!("{name}.toml"));
                std::fs::copy(dp, &staged).with_context(|| {
                    format!("stage descriptor {} -> {}", dp.display(), staged.display())
                })?;
                entries.push(format!("{name}={}", staged.display()));
            } else {
                entries.push(entry.clone()); // git URL or non-file → pass through
            }
        }
        (staged_config, Some(dw), entries)
    } else {
        (config.clone(), None, Vec::new())
    };

    std::fs::create_dir_all("/etc/nornir").context("create /etc/nornir")?;
    // Preserve the existing token on update (regenerating it would break clients
    // already configured with the old one); generate a fresh one on first install.
    let existing_token = std::fs::read_to_string(env_path).ok().and_then(|s| {
        s.lines()
            .find_map(|l| l.strip_prefix("NORNIR_SERVER_TOKEN="))
            .map(|t| t.trim().to_string())
            .filter(|t| !t.is_empty())
    });
    let token_reused = existing_token.is_some();
    let token = existing_token
        .unwrap_or_else(|| format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()));
    let mut env_body =
        format!("NORNIR_SERVER_TOKEN={token}\nNORNIR_SERVER_ADDR={}\n", a.addr);
    if let Some(cfg) = &effective_config {
        env_body.push_str(&format!("NORNIR_CONFIG={}\n", cfg.display()));
    }
    if let Some(dw) = &default_warehouse {
        // Pin EVERY writable root under the nornir home so nothing is derived
        // from the staged config's (non-writable) workspace_root: warehouse,
        // its index (next to it, handled by the server), and the funnel store.
        env_body.push_str(&format!("NORNIR_WAREHOUSE={}\n", dw.display()));
        let funnel = Path::new(NORNIR_HOME).join("funnel");
        std::fs::create_dir_all(&funnel).ok();
        env_body.push_str(&format!("NORNIR_FUNNEL_ROOT={}\n", funnel.display()));
    }
    // Self-sync (monitored) settings. The root is created + chowned to the service
    // user so the poll loop can write it.
    let monitor_root = if monitoring {
        let root = a
            .root
            .clone()
            .unwrap_or_else(|| Path::new(NORNIR_HOME).join("workspaces"));
        std::fs::create_dir_all(&root).with_context(|| format!("create {}", root.display()))?;
        env_body.push_str(&format!("NORNIR_ROOT={}\n", root.display()));
        if !monitor_entries.is_empty() {
            env_body.push_str(&format!("NORNIR_MONITOR={}\n", monitor_entries.join(",")));
        }
        env_body.push_str(&format!("NORNIR_POLL={}\n", a.poll.as_deref().unwrap_or("60s")));
        Some(root)
    } else {
        None
    };

    // Chown everything we created under the home (ssh key, staged config +
    // descriptors, default warehouse) to the service user, plus an out-of-home
    // --root if used.
    if let Some((uid, gid)) = passwd_ids(&a.user) {
        chown_recursive(Path::new(NORNIR_HOME), uid, gid).context("chown nornir home")?;
        if let Some(root) = &monitor_root {
            if !root.starts_with(NORNIR_HOME) {
                chown_recursive(root, uid, gid).ok();
            }
        }
    }

    std::fs::write(env_path, env_body).context("write /etc/nornir/nornir.env")?;
    // root:root 0600 — systemd reads it as root and passes the env to the service.
    std::fs::set_permissions(env_path, std::fs::Permissions::from_mode(0o600))?;

    let unit = format!(
        "[Unit]\n\
         Description=nornir server\n\
         After=network-online.target\n\
         Wants=network-online.target\n\n\
         [Service]\n\
         Type=simple\n\
         User={user}\n\
         Group={user}\n\
         WorkingDirectory={home}\n\
         Environment=HOME={home}\n\
         EnvironmentFile=/etc/nornir/nornir.env\n\
         ExecStart={bin}\n\
         Restart=on-failure\n\
         RestartSec=2\n\
         NoNewPrivileges=true\n\n\
         [Install]\n\
         WantedBy=multi-user.target\n",
        user = a.user,
        home = NORNIR_HOME,
        bin = server_bin.display(),
    );
    std::fs::write(unit_path, &unit).context("write unit file")?;

    systemctl(&["daemon-reload"])?;
    // Clear any crash-loop start-limit from a prior bad install so the next
    // start/restart isn't refused ("start request repeated too quickly").
    let _ = std::process::Command::new("systemctl")
        .args(["reset-failed", "nornir.service"])
        .status();
    // On update, apply it: try-restart restarts the service only if it's running
    // (a no-op on first install / when stopped), so the new binary/unit/config
    // take effect without forcing a start.
    if updating {
        systemctl(&["try-restart", "nornir.service"])?;
    }

    println!(
        "{} nornir systemd service",
        if updating { "updated" } else { "installed" }
    );
    println!("  user       : {} (system)", a.user);
    println!(
        "  env file   : /etc/nornir/nornir.env (mode 600; token {})",
        if token_reused { "preserved" } else { "generated" }
    );
    println!("  unit       : /etc/systemd/system/nornir.service");
    println!(
        "  binaries   : {}",
        installed
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    );
    println!(
        "  config     : {}",
        config.as_ref().map(|c| c.display().to_string()).unwrap_or_else(|| "(none — monitor-only)".into())
    );
    if let Some(root) = &monitor_root {
        println!("  monitor    : root {} (poll {})", root.display(), a.poll.as_deref().unwrap_or("60s"));
        if !a.monitor.is_empty() {
            println!("               workspaces: {}", a.monitor.join(", "));
        }
    }
    println!(
        "  ssh key    : {} ({})",
        pub_path.display(),
        if key_generated { "generated" } else { "preserved" }
    );
    if let Ok(txt) = std::fs::read_to_string(&pub_path) {
        println!();
        println!("  add this public key as a deploy key on each monitored repo:");
        println!("    {}", txt.trim());
    }
    println!();
    if updating {
        println!("  (running service was restarted to apply the update)");
        println!("  status :  systemctl status nornir   ·   logs: journalctl -u nornir -f");
    } else {
        println!("  enable + start:  systemctl enable --now nornir");
        println!("  follow logs   :  journalctl -u nornir -f");
    }
    Ok(())
}

#[cfg(not(unix))]
fn run_install_systemd(_a: &SystemdArgs) -> Result<()> {
    bail!("`nornir install systemd` is linux-only")
}

/// Create a system user if it doesn't already exist (idempotent).
#[cfg(unix)]
fn ensure_system_user(user: &str) -> Result<()> {
    let passwd = std::fs::read_to_string("/etc/passwd").unwrap_or_default();
    let exists = passwd.lines().any(|l| l.split(':').next() == Some(user));
    if !exists {
        // Annotated deploy subprocess: creating a system user needs the platform
        // tool. Install tooling, not the core library (§4 permits it here). Home
        // is NORNIR_HOME so all the user's state roots there.
        let status = std::process::Command::new("useradd")
            .args([
                "--system",
                "--home-dir",
                NORNIR_HOME,
                "--shell",
                "/usr/sbin/nologin",
                user,
            ])
            .status()
            .context("run `useradd` (deploy command — must be on PATH)")?;
        if !status.success() {
            bail!("useradd failed for `{user}` (exit {:?})", status.code());
        }
        println!("  created system user `{user}` (home {NORNIR_HOME})");
    } else {
        println!("  user `{user}` already exists — keeping it");
    }
    // Ensure the home dir exists + is owned by the user (useradd may not create
    // it; an older install may have used a different home).
    std::fs::create_dir_all(NORNIR_HOME).context("create nornir home")?;
    if let Some((uid, gid)) = passwd_ids(user) {
        chown_recursive(Path::new(NORNIR_HOME), uid, gid).ok();
    }
    Ok(())
}

#[cfg(unix)]
fn systemctl(args: &[&str]) -> Result<()> {
    // Annotated deploy subprocess: systemd interaction is the installer's job.
    let status = std::process::Command::new("systemctl")
        .args(args)
        .status()
        .context("run `systemctl`")?;
    if !status.success() {
        bail!("`systemctl {}` failed (exit {:?})", args.join(" "), status.code());
    }
    Ok(())
}

fn run_guard(op: GuardOp, loaded: &Loaded) -> Result<()> {
    // Client mode: Status/Apply/Release route to the server (which guards its own
    // workspace). Verify has no RPC — it stays a local integrity check.
    if let Some(server) = server_target() {
        match op {
            GuardOp::Status => return guard_remote(&server, "status"),
            GuardOp::Apply => return guard_remote(&server, "apply"),
            GuardOp::Release => return guard_remote(&server, "release"),
            GuardOp::Verify => {}
        }
    }
    let forbidden = &loaded.nornir.guard.forbidden;
    if let GuardOp::Verify = op {
        let recorded = guard::read_manifest(&loaded.workspace_root)?;
        let report = guard::verify(&loaded.workspace_root, &recorded);
        println!("recorded_at: {}", recorded.recorded_at);
        for v in &report {
            if v.ok() {
                println!("{:<8} {}", "ok", v.rel);
            } else {
                println!("{:<8} {}  {:?}", "DRIFT", v.rel, v.drift);
            }
        }
        guard::intact(&loaded.workspace_root, &recorded)?;
        return Ok(());
    }
    let report = match op {
        GuardOp::Status => guard::status(&loaded.workspace_root, forbidden),
        GuardOp::Apply => guard::apply_and_record(&loaded.workspace_root, forbidden)?,
        GuardOp::Verify => unreachable!("handled above"),
        GuardOp::Release => {
            if std::env::var_os("NORNIR_GUARD_UNLOCK_TOKEN").is_none() {
                anyhow::bail!(
                    "guard release (unlock) requires the human-held NORNIR_GUARD_UNLOCK_TOKEN \
                     env var; refusing to chmod +w protected paths"
                );
            }
            guard::release(&loaded.workspace_root, forbidden)?
        }
    };
    println!("{:<10} {:<10} {:<10} path", "exists", "writable", "changed");
    for s in &report {
        println!(
            "{:<10} {:<10} {:<10} {}",
            yn(s.exists), yn(s.writable), yn(s.changed), s.path.display()
        );
    }
    Ok(())
}

/// tonic client bindings (generated when `mcp`/`server` features pull tonic).
// ───────────────────────── CLI → server (tonic client) ─────────────────────
// `NORNIR_SERVER` (host:port or URL) + `NORNIR_SERVER_TOKEN` route a verb to a
// running `nornir-server` instead of the embedded in-process path. Each verb's
// remote fn is a thin wrapper over `on_server` (connect + bearer + run a
// service-client call); the server already implements the matching RPC.

#[cfg(any(feature = "mcp", feature = "server"))]
mod pb_client {
    tonic::include_proto!("nornir.v1");
}

/// Connect to `server`, then run `f` with a ready `Channel` + the bearer
/// metadata the server's interceptor requires. Drives its own tokio runtime
/// (the CLI is otherwise sync). The shared entry point for every CLI→server call.
#[cfg(any(feature = "mcp", feature = "server"))]
fn on_server<T, F, Fut>(server: &str, f: F) -> Result<T>
where
    F: FnOnce(tonic::transport::Channel, tonic::metadata::MetadataValue<tonic::metadata::Ascii>) -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let token = std::env::var("NORNIR_SERVER_TOKEN")
        .context("NORNIR_SERVER is set; NORNIR_SERVER_TOKEN is required for the bearer auth")?;
    let endpoint = if server.starts_with("http") { server.to_string() } else { format!("http://{server}") };
    let bearer: tonic::metadata::MetadataValue<tonic::metadata::Ascii> =
        format!("Bearer {token}").parse().context("build bearer metadata")?;
    let rt = tokio::runtime::Runtime::new().context("tokio runtime for server call")?;
    rt.block_on(async move {
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid NORNIR_SERVER url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        f(channel, bearer).await
    })
}

/// `true` if a `--server`/`NORNIR_SERVER` target is configured (client mode).
fn server_target() -> Option<String> {
    std::env::var("NORNIR_SERVER").ok().filter(|s| !s.is_empty())
}

/// Which workspace the CLI targets in client mode (the `nornir-workspace` header):
/// `NORNIR_WORKSPACE` → else the current dir's workspace (cwd config discovery →
/// `workspace_root` dir name) → else `None` (the server uses its default; it
/// returns NotFound if it doesn't serve the requested one). Memoized.
#[cfg(any(feature = "mcp", feature = "server"))]
fn client_workspace() -> Option<&'static str> {
    use std::sync::OnceLock;
    static WS: OnceLock<Option<String>> = OnceLock::new();
    WS.get_or_init(|| {
        if let Ok(w) = std::env::var("NORNIR_WORKSPACE") {
            if !w.is_empty() {
                return Some(w);
            }
        }
        let cwd = std::env::current_dir().ok()?;
        config::discover(&cwd).ok().and_then(|l| {
            l.workspace_root.file_name().and_then(|s| s.to_str()).map(String::from)
        })
    })
    .as_deref()
}

/// Build the per-request interceptor: bearer auth + the `nornir-workspace` header
/// (when a workspace is resolvable). Shared by every CLI→server call.
#[cfg(any(feature = "mcp", feature = "server"))]
fn auth_interceptor(
    bearer: tonic::metadata::MetadataValue<tonic::metadata::Ascii>,
) -> 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)
    }
}

/// Ship a locally-computed `BenchRun` to the server over `Bench.Submit` (lossless:
/// results + tests). `NORNIR_SERVER_TOKEN` supplies the bearer.
#[cfg(any(feature = "mcp", feature = "server"))]
fn submit_bench_remote(server: &str, repo: &str, run: &bench::BenchRun) -> Result<String> {
    use pb_client::bench_client::BenchClient;
    use pb_client::{BenchResult as PbResult, BenchRun as PbRun, Kvf, SubmitBenchRequest, TestOutcome as PbTest};

    let repo = repo.to_string();
    let pb_run = PbRun {
        date: run.date.clone(),
        timestamp: run.timestamp.clone().unwrap_or_default(),
        version: run.version.clone(),
        machine: run.machine.clone(),
        cores: run.cores,
        results: run.results.iter().map(|r| PbResult {
            name: r.name.clone(),
            metrics: r.metrics.iter()
                .filter_map(|(k, v)| v.as_f64().map(|f| Kvf { key: k.clone(), value: f }))
                .collect(),
        }).collect(),
        tests: run.tests.iter().map(|t| PbTest {
            name: t.name.clone(),
            passed: t.passed,
            duration_ms: t.duration_ms.unwrap_or(0.0),
            has_duration: t.duration_ms.is_some(),
            message: t.message.clone().unwrap_or_default(),
        }).collect(),
    };
    on_server(server, move |channel, bearer| async move {
        let mut client = BenchClient::with_interceptor(channel, auth_interceptor(bearer));
        let resp = client.submit(SubmitBenchRequest { repo, run: Some(pb_run) }).await
            .map_err(|e| anyhow!("Bench.Submit RPC failed: {e}"))?;
        Ok(resp.into_inner().run_id)
    })
}

/// List the server's configured repos over `Repos.List`.
#[cfg(any(feature = "mcp", feature = "server"))]
fn list_repos_remote(server: &str) -> Result<Vec<String>> {
    use pb_client::repos_client::ReposClient;
    use pb_client::Empty;
    on_server(server, move |channel, bearer| async move {
        let mut client = ReposClient::with_interceptor(channel, auth_interceptor(bearer));
        let resp = client.list(Empty {}).await.map_err(|e| anyhow!("Repos.List RPC failed: {e}"))?;
        Ok(resp.into_inner().repos.into_iter().map(|r| r.name).collect())
    })
}

/// `nornir workspace …` against the server over `Workspaces.*`. Output mirrors
/// the embedded path so fat/remote are indistinguishable to the user.
#[cfg(any(feature = "mcp", feature = "server"))]
fn run_workspace_remote(server: &str, op: &WorkspaceOp) -> Result<()> {
    use pb_client::workspaces_client::WorkspacesClient;
    use pb_client::{Empty, RegisterWorkspaceRequest, WorkspaceName};

    match op {
        WorkspaceOp::Ls => {
            let list = on_server(server, |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                let resp = c
                    .list(Empty {})
                    .await
                    .map_err(|e| anyhow!("Workspaces.List RPC failed: {e}"))?;
                Ok(resp.into_inner().workspaces)
            })?;
            if list.is_empty() {
                println!("(no workspaces registered on {server})");
                return Ok(());
            }
            println!("{:<20} {:<10} {:>7}  {}", "NAME", "MODE", "MEMBERS", "LAST SYNCED");
            for ws in list {
                let last = ws
                    .members
                    .iter()
                    .map(|m| m.last_synced.as_str())
                    .filter(|s| !s.is_empty())
                    .max()
                    .unwrap_or("never");
                println!("{:<20} {:<10} {:>7}  {}", ws.name, ws.mode, ws.members.len(), last);
            }
        }
        WorkspaceOp::Show { name } => {
            let name = name.clone();
            let ws = on_server(server, move |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                let resp = c
                    .get(WorkspaceName { name })
                    .await
                    .map_err(|e| anyhow!("Workspaces.Get RPC failed: {e}"))?;
                Ok(resp.into_inner())
            })?;
            println!("name:             {}", ws.name);
            println!("mode:             {}", ws.mode);
            println!("descriptor:       {}", ws.descriptor);
            println!("poll:             {}", ws.poll);
            println!("current_snapshot: {}", ws.current_snapshot);
            println!("created_at:       {}", ws.created_at);
            println!("updated_at:       {}", ws.updated_at);
            for m in ws.members {
                println!(
                    "  - {:<16} remote={} ref={} sha={} synced={} state={}",
                    m.name, m.remote, m.git_ref, m.last_seen_sha, m.last_synced, m.sync_state
                );
            }
        }
        WorkspaceOp::Register { name, descriptor, monitored, external, poll } => {
            if *monitored && *external {
                bail!("--monitored and --external are mutually exclusive");
            }
            let mode = if *monitored {
                "monitored"
            } else if *external {
                "external"
            } else {
                "pushed"
            }
            .to_string();
            let (name, descriptor, poll) =
                (name.clone(), descriptor.clone(), poll.clone().unwrap_or_default());
            let ws = on_server(server, move |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                let resp = c
                    .register(RegisterWorkspaceRequest { name, descriptor, mode, poll })
                    .await
                    .map_err(|e| anyhow!("Workspaces.Register RPC failed: {e}"))?;
                Ok(resp.into_inner())
            })?;
            println!(
                "✓ registered `{}` ({}, {} member(s)) on {server}",
                ws.name,
                ws.mode,
                ws.members.len()
            );
        }
        WorkspaceOp::Rm { name } => {
            let name = name.clone();
            on_server(server, move |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                c.remove(WorkspaceName { name })
                    .await
                    .map_err(|e| anyhow!("Workspaces.Remove RPC failed: {e}"))?;
                Ok(())
            })?;
            println!("✓ removed");
        }
        WorkspaceOp::Fetch { name } => {
            let name = name.clone();
            let rep = on_server(server, move |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                let resp = c
                    .fetch(WorkspaceName { name })
                    .await
                    .map_err(|e| anyhow!("Workspaces.Fetch RPC failed: {e}"))?;
                Ok(resp.into_inner())
            })?;
            for e in &rep.errors {
                eprintln!("    {e}");
            }
            println!(
                "✓ fetched `{}` — {} of {} member(s) changed",
                rep.workspace,
                rep.changed.len(),
                rep.fetched
            );
        }
    }
    Ok(())
}

/// Knowledge-map query over the server (`Knowledge.*`), printing like the
/// embedded path. `kind` ∈ callers | callees | defined-in | lookup | path.
#[cfg(any(feature = "mcp", feature = "server"))]
fn knowledge_query_remote(
    server: &str,
    repo: &str,
    kind: &str,
    arg: &str,
    to: Option<&str>,
    limit: usize,
) -> Result<()> {
    use pb_client::knowledge_client::KnowledgeClient;
    use pb_client::{KnowledgeCallPathQuery, KnowledgeCallQuery, KnowledgeSymbolQuery};
    let (repo, kind, arg) = (repo.to_string(), kind.to_string(), arg.to_string());
    let to = to.map(|s| s.to_string());
    let lim = limit as u32;
    on_server(server, move |channel, bearer| async move {
        let mut c = KnowledgeClient::with_interceptor(channel, auth_interceptor(bearer));
        match kind.as_str() {
            "callers" | "callees" => {
                let q = KnowledgeCallQuery { repo, name: arg.clone(), limit: lim };
                let calls = if kind == "callers" {
                    c.callers(q).await
                } else {
                    c.callees(q).await
                }
                .map_err(|e| anyhow!("Knowledge.{kind} RPC failed: {e}"))?
                .into_inner()
                .calls;
                println!("{kind} of `{arg}` ({}):", calls.len());
                for c in &calls {
                    println!("  {}{}  [{}:{}]", c.caller_path, c.callee_ident, c.file, c.line);
                }
            }
            "defined-in" | "lookup" => {
                let q = KnowledgeSymbolQuery { repo, arg: arg.clone(), limit: lim };
                let syms = if kind == "lookup" {
                    c.symbol_lookup(q).await
                } else {
                    c.defined_in(q).await
                }
                .map_err(|e| anyhow!("Knowledge.{kind} RPC failed: {e}"))?
                .into_inner()
                .symbols;
                println!("symbols ({}) for `{arg}`:", syms.len());
                for s in &syms {
                    println!("  {:8} {}::{}  [{}:{}]", s.item_kind, s.module_path, s.item_name, s.file, s.line);
                }
            }
            "path" => {
                let to = to.ok_or_else(|| anyhow!("`path` query needs a target: pass --to <fn>"))?;
                let names = c
                    .call_path(KnowledgeCallPathQuery { repo, from: arg.clone(), to: to.clone() })
                    .await
                    .map_err(|e| anyhow!("Knowledge.CallPath RPC failed: {e}"))?
                    .into_inner()
                    .names;
                if names.is_empty() {
                    println!("no call path from `{arg}` to `{to}`");
                } else {
                    println!("call path `{arg}` → `{to}` ({} hops):", names.len().saturating_sub(1));
                    println!("  {}", names.join(""));
                }
            }
            other => bail!("unknown knowledge kind `{other}`"),
        }
        Ok(())
    })
}

/// Full-text search over the server (`Search.Query`), printing like the embedded path.
#[cfg(any(feature = "mcp", feature = "server"))]
fn search_remote(
    server: &str,
    query: &str,
    corpus: Option<&str>,
    repo: Option<&str>,
    limit: usize,
) -> Result<()> {
    use pb_client::search_client::SearchClient;
    use pb_client::SearchRequest;
    let req = SearchRequest {
        query: query.to_string(),
        corpus: corpus.unwrap_or("").to_string(),
        repo: repo.unwrap_or("").to_string(),
        limit: limit as u32,
    };
    on_server(server, move |channel, bearer| async move {
        let mut c = SearchClient::with_interceptor(channel, auth_interceptor(bearer));
        let hits = c.query(req).await.map_err(|e| anyhow!("Search.Query RPC failed: {e}"))?.into_inner().hits;
        for h in &hits {
            println!(
                "{:>6.2}  [{}/{}]  {}\n        {}",
                h.score,
                h.corpus,
                if h.repo.is_empty() { "-" } else { &h.repo },
                h.path,
                h.snippet
            );
        }
        Ok(())
    })
}

/// Guard op over the server (`Guard.Status|Apply|Release`), printing the report
/// table like the embedded path. (Verify has no RPC — stays local.)
#[cfg(any(feature = "mcp", feature = "server"))]
fn guard_remote(server: &str, op: &str) -> Result<()> {
    use pb_client::guard_client::GuardClient;
    use pb_client::Empty;
    let op = op.to_string();
    on_server(server, move |channel, bearer| async move {
        let mut c = GuardClient::with_interceptor(channel, auth_interceptor(bearer));
        let report = match op.as_str() {
            "status" => c.status(Empty {}).await,
            "apply" => c.apply(Empty {}).await,
            "release" => c.release(Empty {}).await,
            other => return Err(anyhow!("guard `{other}` is not server-routable")),
        }
        .map_err(|e| anyhow!("Guard.{op} RPC failed: {e}"))?
        .into_inner();
        println!("{:<10} {:<10} {:<10} path", "exists", "writable", "changed");
        for p in &report.paths {
            println!("{:<10} {:<10} {:<10} {}", yn(p.exists), yn(p.writable), yn(p.changed), p.path);
        }
        Ok(())
    })
}

/// Index stats over the server (`Index.Stats`), printing like the embedded path.
#[cfg(any(feature = "mcp", feature = "server"))]
fn index_stats_remote(server: &str) -> Result<()> {
    use pb_client::index_client::IndexClient;
    use pb_client::Empty;
    on_server(server, move |channel, bearer| async move {
        let mut c = IndexClient::with_interceptor(channel, auth_interceptor(bearer));
        let s = c.stats(Empty {}).await.map_err(|e| anyhow!("Index.Stats RPC failed: {e}"))?.into_inner();
        println!("total: {}", s.total);
        for kv in &s.by_corpus {
            println!("  {:<14} {}", kv.key, kv.value);
        }
        Ok(())
    })
}

/// Run a named gate over the server (`Release.Gate*`). Supports the gates the
/// server exposes (path_patches | nexus_floor | no_regression | docs_fresh | all);
/// other CLI gates aren't server-routable.
#[cfg(any(feature = "mcp", feature = "server"))]
fn gate_remote(server: &str, name: &str, repo: &str) -> Result<()> {
    use pb_client::release_client::ReleaseClient;
    use pb_client::RepoOnly;
    let (name, repo) = (name.to_string(), repo.to_string());
    on_server(server, move |channel, bearer| async move {
        let mut c = ReleaseClient::with_interceptor(channel, auth_interceptor(bearer));
        let req = || RepoOnly { repo: repo.clone() };
        if name == "all" {
            let res = c.gate_all(req()).await.map_err(|e| anyhow!("Release.GateAll RPC failed: {e}"))?.into_inner();
            println!("=== gate-all: {} ===", res.repo);
            for p in &res.passed {
                println!("{p}");
            }
            for f in &res.failed {
                println!("{}: {}", f.name, f.error);
            }
            if !res.failed.is_empty() {
                bail!("{} gate(s) failed", res.failed.len());
            }
            println!("{} gate(s) passed", res.passed.len());
            return Ok(());
        }
        let res = match name.as_str() {
            "path_patches" => c.gate_path_patches(req()).await,
            "nexus_floor" => c.gate_nexus_floor(req()).await,
            "no_regression" => c.gate_no_regression(req()).await,
            "docs_fresh" => c.gate_docs_fresh(req()).await,
            other => return Err(anyhow!(
                "gate `{other}` is not exposed by the server (available: \
                 path_patches, nexus_floor, no_regression, docs_fresh, all)"
            )),
        }
        .map_err(|e| anyhow!("Release.{name} RPC failed: {e}"))?
        .into_inner();
        if res.status == "pass" {
            let v = if res.version.is_empty() { String::new() } else { format!(" (v{})", res.version) };
            println!("{} pass{v}", res.gate);
            Ok(())
        } else {
            bail!("✗ {} fail: {}", res.gate, res.message)
        }
    })
}

/// DWARF symbol queries over the server (`Introspect.Symbols|SymbolLookup|
/// DefinedIn`). `binary` is resolved on the **server's** filesystem.
#[cfg(any(feature = "mcp", feature = "server"))]
fn introspect_symbols_remote(server: &str, binary: &str, kind: &str, arg: &str, limit: usize) -> Result<()> {
    use pb_client::introspect_client::IntrospectClient;
    use pb_client::{BinaryOnly, DefinedInRequest, SymbolLookupRequest};
    let (binary, kind, arg) = (binary.to_string(), kind.to_string(), arg.to_string());
    let lim = limit as u32;
    on_server(server, move |channel, bearer| async move {
        let mut c = IntrospectClient::with_interceptor(channel, auth_interceptor(bearer));
        let syms = match kind.as_str() {
            "symbols" => c.symbols(BinaryOnly { binary }).await,
            "lookup" => c.symbol_lookup(SymbolLookupRequest { binary, pattern: arg, limit: lim }).await,
            "defined-in" => c.defined_in(DefinedInRequest { binary, suffix: arg }).await,
            other => return Err(anyhow!("introspect `{other}` unsupported over the server")),
        }
        .map_err(|e| anyhow!("Introspect.{kind} RPC failed: {e}"))?
        .into_inner()
        .symbols;
        for s in &syms {
            if kind == "symbols" {
                println!("{}\t{}:{}\t{}", s.name_demangled, s.file, s.line, s.krate);
            } else {
                println!("{}:{}  {}", s.file, s.line, s.name_demangled);
            }
        }
        eprintln!("# {} symbol(s)", syms.len());
        Ok(())
    })
}

/// DWARF callgraph queries over the server (`Introspect.Callers|Callees|
/// PathBetween`). `binary` is resolved on the server.
#[cfg(any(feature = "mcp", feature = "server"))]
fn introspect_calls_remote(server: &str, binary: &str, kind: &str, name: &str, to: Option<&str>) -> Result<()> {
    use pb_client::introspect_client::IntrospectClient;
    use pb_client::{CallQuery, PathBetweenRequest};
    let (binary, kind, name) = (binary.to_string(), kind.to_string(), name.to_string());
    let to = to.map(|s| s.to_string());
    on_server(server, move |channel, bearer| async move {
        let mut c = IntrospectClient::with_interceptor(channel, auth_interceptor(bearer));
        let names = match kind.as_str() {
            "callers" => c.callers(CallQuery { binary, name: name.clone() }).await,
            "callees" => c.callees(CallQuery { binary, name: name.clone() }).await,
            "path" => {
                let to = to.ok_or_else(|| anyhow!("`path` needs --to <fn>"))?;
                c.path_between(PathBetweenRequest { binary, from: name.clone(), to }).await
            }
            other => return Err(anyhow!("introspect `{other}` unsupported over the server")),
        }
        .map_err(|e| anyhow!("Introspect.{kind} RPC failed: {e}"))?
        .into_inner()
        .names;
        if kind == "path" {
            if names.is_empty() {
                println!("no call path from `{name}`");
            } else {
                println!("{}", names.join(""));
            }
        } else {
            println!("{kind} of `{name}` ({}):", names.len());
            for n in &names {
                println!("  {n}");
            }
        }
        Ok(())
    })
}

/// Docs op over the server (`Docs.Init|Render|Check`).
#[cfg(any(feature = "mcp", feature = "server"))]
fn docs_remote(server: &str, op: &str, repo: &str) -> Result<()> {
    use pb_client::docs_client::DocsClient;
    use pb_client::RepoOnly;
    let (op, repo) = (op.to_string(), repo.to_string());
    on_server(server, move |channel, bearer| async move {
        let mut c = DocsClient::with_interceptor(channel, auth_interceptor(bearer));
        let req = RepoOnly { repo };
        let resp = match op.as_str() {
            "init" => c.init(req).await,
            "render" => c.render(req).await,
            "check" => c.check(req).await,
            other => return Err(anyhow!("docs `{other}` is not server-routable")),
        }
        .map_err(|e| anyhow!("Docs.{op} RPC failed: {e}"))?
        .into_inner();
        println!("{}: {}", resp.status, resp.detail);
        for a in &resp.artifacts {
            println!("  {a}");
        }
        if resp.status == "drift" {
            bail!("docs drift on {}", resp.repo);
        }
        Ok(())
    })
}

/// Doc-export history over the server (`Docs.History`).
#[cfg(any(feature = "mcp", feature = "server"))]
fn docs_history_remote(
    server: &str,
    repo: &str,
    doc: Option<&str>,
    version: Option<&str>,
    format: Option<&str>,
    limit: usize,
) -> Result<()> {
    use pb_client::docs_client::DocsClient;
    use pb_client::DocsHistoryRequest;
    let req = DocsHistoryRequest {
        repo: repo.to_string(),
        doc: doc.unwrap_or("").to_string(),
        version: version.unwrap_or("").to_string(),
        format: format.unwrap_or("").to_string(),
        limit: limit as u32,
    };
    on_server(server, move |channel, bearer| async move {
        let mut c = DocsClient::with_interceptor(channel, auth_interceptor(bearer));
        let entries = c.history(req).await.map_err(|e| anyhow!("Docs.History RPC failed: {e}"))?.into_inner().entries;
        if entries.is_empty() {
            println!("no exports historized");
            return Ok(());
        }
        println!("{:<20}  {:<8}  {:<6}  {:>9}  {}", "exported_at", "doc", "format", "bytes", "path");
        for e in &entries {
            println!("{:<20}  {:<8}  {:<6}  {:>9}  {}", e.exported_at, e.doc, e.format, e.size_bytes, e.path);
        }
        Ok(())
    })
}

/// Ask the server to snapshot *its own* index for `repo`, keyed to the client's
/// HEAD (`Index.Snapshot`). To push a *locally-built* index up instead, see
/// `index_upload_remote` (`Index.UploadSnapshot`, the `index upload` verb).
#[cfg(any(feature = "mcp", feature = "server"))]
fn index_snapshot_remote(server: &str, repo: &str, workspace: &str, git_sha: &str, branch: &str) -> Result<()> {
    use pb_client::index_client::IndexClient;
    use pb_client::SnapshotRequest;
    let req = SnapshotRequest {
        repo: repo.to_string(),
        workspace: workspace.to_string(),
        git_sha: git_sha.to_string(),
        branch: branch.to_string(),
    };
    on_server(server, move |channel, bearer| async move {
        let mut c = IndexClient::with_interceptor(channel, auth_interceptor(bearer));
        let s = c.snapshot(req).await.map_err(|e| anyhow!("Index.Snapshot RPC failed: {e}"))?.into_inner();
        println!(
            "✓ snapshot {} ({}, {} blob(s), {} bytes, sha={})",
            s.snapshot_id, s.repo, s.blob_count, s.total_bytes, &s.git_sha[..s.git_sha.len().min(12)]
        );
        Ok(())
    })
}

/// Stream the local tantivy index dir up to the server via the client-streaming
/// `Index.UploadSnapshot`. Frame order matches the server's reader: one `meta`
/// frame, then per file a `file` frame (rel_path + declared size) followed by
/// `chunk` frames. Files are read eagerly into the frame list (indexes are
/// modest, MBs); chunked at 1 MiB to stay under the gRPC message cap.
#[cfg(any(feature = "mcp", feature = "server"))]
fn index_upload_remote(
    server: &str,
    index_dir: &std::path::Path,
    repo: &str,
    workspace: &str,
    git_sha: &str,
    branch: &str,
) -> Result<()> {
    use pb_client::index_client::IndexClient;
    use pb_client::{index_blob_frame::Body, IndexBlobFile, IndexBlobFrame, IndexBlobMeta};

    const CHUNK: usize = 1024 * 1024;
    if !index_dir.is_dir() {
        bail!("no index at {} — run `nornir index build` first", index_dir.display());
    }

    // Build the frame list eagerly so file-IO errors surface here, not mid-stream.
    let mut frames: Vec<IndexBlobFrame> = vec![IndexBlobFrame {
        body: Some(Body::Meta(IndexBlobMeta {
            workspace: workspace.to_string(),
            repo: repo.to_string(),
            git_sha: git_sha.to_string(),
            branch: branch.to_string(),
        })),
    }];
    let mut file_count = 0u64;
    let mut total_bytes = 0u64;
    for entry in walkdir::WalkDir::new(index_dir).sort_by_file_name() {
        let entry = entry.with_context(|| format!("walk index dir {}", index_dir.display()))?;
        if !entry.file_type().is_file() {
            continue;
        }
        let rel = entry
            .path()
            .strip_prefix(index_dir)
            .map_err(|e| anyhow!("strip_prefix {}: {e}", entry.path().display()))?
            .to_string_lossy()
            .replace('\\', "/"); // server rejects '..'; normalize separators
        let bytes = std::fs::read(entry.path())
            .with_context(|| format!("read {}", entry.path().display()))?;
        frames.push(IndexBlobFrame {
            body: Some(Body::File(IndexBlobFile { rel_path: rel, size_bytes: bytes.len() as u64 })),
        });
        for chunk in bytes.chunks(CHUNK) {
            frames.push(IndexBlobFrame { body: Some(Body::Chunk(chunk.to_vec())) });
        }
        file_count += 1;
        total_bytes += bytes.len() as u64;
    }
    if file_count == 0 {
        bail!("index dir {} has no files to upload", index_dir.display());
    }
    println!(
        "↥ uploading index {} ({} file(s), {} bytes) to {server}",
        index_dir.display(),
        file_count,
        total_bytes,
    );

    on_server(server, move |channel, bearer| async move {
        let mut c = IndexClient::with_interceptor(channel, auth_interceptor(bearer));
        let stream = futures::stream::iter(frames);
        let s = c
            .upload_snapshot(tonic::Request::new(stream))
            .await
            .map_err(|e| anyhow!("Index.UploadSnapshot RPC failed: {e}"))?
            .into_inner();
        println!(
            "✓ uploaded → snapshot {} ({}, {} blob(s), {} bytes, sha={})",
            s.snapshot_id, s.repo, s.blob_count, s.total_bytes, &s.git_sha[..s.git_sha.len().min(12)],
        );
        Ok(())
    })
}

#[cfg(not(any(feature = "mcp", feature = "server")))]
fn no_client() -> anyhow::Error {
    anyhow!(
        "NORNIR_SERVER is set but this `nornir` was built without a client; \
         rebuild with `--features server` (or `mcp`) to talk to a nornir-server"
    )
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn submit_bench_remote(_server: &str, _repo: &str, _run: &bench::BenchRun) -> Result<String> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn list_repos_remote(_server: &str) -> Result<Vec<String>> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn knowledge_query_remote(
    _server: &str, _repo: &str, _kind: &str, _arg: &str, _to: Option<&str>, _limit: usize,
) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn search_remote(
    _server: &str, _query: &str, _corpus: Option<&str>, _repo: Option<&str>, _limit: usize,
) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn guard_remote(_server: &str, _op: &str) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn index_stats_remote(_server: &str) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn gate_remote(_server: &str, _name: &str, _repo: &str) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn introspect_symbols_remote(_s: &str, _b: &str, _k: &str, _a: &str, _l: usize) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn introspect_calls_remote(_s: &str, _b: &str, _k: &str, _n: &str, _t: Option<&str>) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn docs_remote(_s: &str, _op: &str, _repo: &str) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn docs_history_remote(
    _s: &str, _r: &str, _d: Option<&str>, _v: Option<&str>, _f: Option<&str>, _l: usize,
) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn index_snapshot_remote(_s: &str, _r: &str, _w: &str, _sha: &str, _b: &str) -> Result<()> {
    Err(no_client())
}
#[cfg(not(any(feature = "mcp", feature = "server")))]
fn index_upload_remote(
    _s: &str, _dir: &std::path::Path, _r: &str, _w: &str, _sha: &str, _b: &str,
) -> Result<()> {
    Err(no_client())
}

fn run_bench(op: BenchOp, loaded: &Loaded) -> Result<()> {
    match op {
        BenchOp::HistoryShow(a) => {
            let repo = repo_or_err(loaded, &a.repo)?;
            let path = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo)
                .join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
            let mut runs = bench::history::read_all(&path)?;
            if a.json {
                for r in &runs {
                    println!("{}", serde_json::to_string(r)?);
                }
                return Ok(());
            }
            // Newest first; optional cap.
            runs.sort_by(|x, y| {
                let kx = x.timestamp.as_deref().unwrap_or(&x.date);
                let ky = y.timestamp.as_deref().unwrap_or(&y.date);
                ky.cmp(kx)
            });
            if a.limit > 0 {
                runs.truncate(a.limit);
            }
            if runs.is_empty() {
                println!("no bench runs in {}", path.display());
                return Ok(());
            }
            println!("{}{} run(s)  [{}]", a.repo, runs.len(), path.display());
            for r in &runs {
                let date = if r.date.is_empty() { "-" } else { r.date.as_str() };
                let machine = if r.machine.is_empty() { "-" } else { r.machine.as_str() };
                println!("\nv{} · {} · {} cores · {}", r.version, machine, r.cores, date);
                // Scalars: sorted "result.metric=value" across all results.
                let mut scalars: Vec<String> = Vec::new();
                for res in &r.results {
                    for (k, v) in &res.metrics {
                        if let Some(f) = v.as_f64() {
                            scalars.push(format!("{}.{k}={f:.2}", res.name));
                        }
                    }
                }
                scalars.sort();
                if scalars.is_empty() {
                    println!("  metrics: (none)");
                } else {
                    println!("  metrics: {}", scalars.join("  "));
                }
                // Tests: pass/fail side by side.
                if r.tests.is_empty() {
                    println!("  tests:   (none recorded)");
                } else {
                    let passed = r.tests.iter().filter(|t| t.passed).count();
                    let failed = r.tests.len() - passed;
                    println!("  tests:   {passed} passed, {failed} failed");
                    for t in r.tests.iter().filter(|t| !t.passed) {
                        let msg = t.message.as_deref().unwrap_or("");
                        println!("{} {}", t.name, msg);
                    }
                }
            }
        }
        BenchOp::Run(a) => {
            let _repo = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            println!("⚡ running nornir-bench in {}", repo_root.display());
            let mut run = match release::pipeline::run_bench_example(&repo_root)? {
                None => {
                    println!(
                        "skipped: neither {}/examples/nornir-bench.rs nor xtask/examples/nornir-bench.rs exists",
                        repo_root.display(),
                    );
                    return Ok(());
                }
                Some(r) => r,
            };
            if run.machine.trim().is_empty() {
                run.machine = std::env::var("NORNIR_MACHINE").unwrap_or_else(|_| {
                    std::fs::read_to_string("/etc/hostname")
                        .ok()
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .unwrap_or_else(|| "unknown".into())
                });
            }
            // Embedded (default) vs client: if NORNIR_SERVER is set, ship the
            // locally-run BenchRun to the server over the Bench.Submit RPC
            // (protobuf, not the stdout-JSON hop) — the server owns the warehouse
            // lock and persists. Otherwise append in-process. (Per the embedded-
            // XOR-client rule; see proto Bench.Submit + scalable-bench-design.md.)
            let id = if let Some(server) = server_target() {
                submit_bench_remote(&server, &a.repo, &run)?
            } else {
                let wh = warehouse::open(&loaded.nornir.storage, &loaded.workspace_root)?;
                wh.append_bench_run(&a.repo, &run)?.to_string()
            };
            println!(
                "{} result(s), {} test(s) persisted into bench_runs as {}",
                run.results.len(),
                run.tests.len(),
                id,
            );
            for r in &run.results {
                let mut kv: Vec<String> = r
                    .metrics
                    .iter()
                    .filter_map(|(k, v)| v.as_f64().map(|f| format!("{k}={f:.2}")))
                    .collect();
                kv.sort();
                println!("  • {:30} {}", r.name, kv.join(" "));
            }
            for t in run.tests.iter().filter(|t| !t.passed) {
                println!("  ✗ test {}{}", t.name, t.message.as_deref().map(|m| format!(": {m}")).unwrap_or_default());
            }
        }
    }
    Ok(())
}

fn run_release(op: ReleaseOp, loaded: &Loaded) -> Result<()> {
    match op {
        ReleaseOp::GatePathPatches(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            release::gate::no_path_patches(&repo_root)?;
            println!("ok: no [patch.crates-io] znippy entries in {}", repo_root.display());
        }
        ReleaseOp::GatePathDepVersions(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let findings = release::gate::path_dep_audit(&repo_root)?;
            let bad: Vec<_> = findings.iter().filter(|f| !f.ok()).collect();
            for f in &findings {
                let tag = if f.ok() { "ok " } else { "MISS" };
                println!("  {tag} {}{} (path={}, version={})",
                    f.manifest.display(), f.dep_name, f.dep_path,
                    f.version_req.as_deref().unwrap_or("<none>"));
            }
            if !bad.is_empty() {
                return Err(anyhow!("{} path-dep(s) missing version=", bad.len()));
            }
            println!("ok: all {} path-dep(s) carry a version=", findings.len());
        }
        ReleaseOp::GateCrateMetadata(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let checks = release::gate::crate_metadata_check(&repo_root)?;
            let bad: Vec<_> = checks.iter().filter(|c| !c.ok()).collect();
            for c in &checks {
                let tag = if c.ok() { "ok " } else { "MISS" };
                println!("  {tag} {}@{} readme={} license={} repo={} desc={}",
                    c.crate_name, c.version,
                    c.has_readme, c.has_license, c.has_repository, c.has_description);
            }
            if !bad.is_empty() {
                return Err(anyhow!("{} crate(s) missing publish-required metadata", bad.len()));
            }
            println!("ok: all {} crate(s) carry readme+license+repository+description", checks.len());
        }
        ReleaseOp::GateLinksConflicts(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let decls = release::gate::links_declarations_scan(&repo_root)?;
            let conflicts = release::gate::detect_links_conflicts(&decls);
            println!("scanned {} links= declarations", decls.len());
            if !conflicts.is_empty() {
                for c in &conflicts {
                    println!("  CONFLICT links={}: {:?}", c.links_value, c.crates);
                }
                return Err(anyhow!("{} links= conflict(s) detected", conflicts.len()));
            }
            println!("ok: no links= conflicts");
        }
        ReleaseOp::GateNexusFloor(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let run = last_run(loaded, &a.repo)?;
            release::gate::nexus_floor(&run)?;
            println!("ok: nexus_floor on v{}", run.version);
        }
        ReleaseOp::GateNoRegression(a) => {
            let repo = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let history = history_path(&repo_root, repo);
            let run = last_run(loaded, &a.repo)?;
            let pct = if repo.gates.max_regression_pct > 0.0 { repo.gates.max_regression_pct } else { 10.0 };
            release::gate::no_regression(&run, &history, pct)?;
            println!("ok: no_regression ≤{:.1}% on v{}", pct, run.version);
        }
        ReleaseOp::GateDocsFresh(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let run = last_run(loaded, &a.repo).ok();
            let history = bench_history_runs(loaded, &a.repo);
            let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, run.as_ref())
                .with_history(&history);
            let readme = repo_root.join("README.md");
            if readme.exists() {
                let _ = docs::check_file(&readme, &ctx)?;
            }
            docs::assemble_and_check(&repo_root, run.as_ref().ok_or_else(|| anyhow!("no bench runs"))?)?;
            println!("ok: docs_fresh on {}", repo_root.display());
        }
        ReleaseOp::GateRoundtrip(a) => {
            let repo = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            if repo.gates.integration_roundtrip.is_empty() {
                println!("ok: roundtrip not configured for {}", a.repo);
                return Ok(());
            }
            let kinds: Vec<&str> = repo.gates.integration_roundtrip.iter().map(|s| s.as_str()).collect();
            release::gate::integration_roundtrip_via_cargo_test(&repo_root, &kinds)?;
            println!("ok: roundtrip {:?}", kinds);
        }
        ReleaseOp::GateAll(a) => {
            run_gate_all(loaded, &a.repo)?;
        }
        ReleaseOp::Gate { name, repo } => {
            // Client mode: run the gate on the server (it owns the workspace).
            if let Some(server) = server_target() {
                return gate_remote(&server, &name, &repo);
            }
            let a = RepoArg { repo };
            // Reuse the per-gate handlers via re-dispatch — single source of truth.
            let op = match name.as_str() {
                "path_patches" | "no_path_patches" => ReleaseOp::GatePathPatches(a),
                "path_dep_versions" => ReleaseOp::GatePathDepVersions(a),
                "crate_metadata" => ReleaseOp::GateCrateMetadata(a),
                "links_conflicts" => ReleaseOp::GateLinksConflicts(a),
                "nexus_floor" => ReleaseOp::GateNexusFloor(a),
                "no_regression" => ReleaseOp::GateNoRegression(a),
                "docs_fresh" => ReleaseOp::GateDocsFresh(a),
                "roundtrip" | "integration_roundtrip" => ReleaseOp::GateRoundtrip(a),
                "all" => ReleaseOp::GateAll(a),
                "guard_intact" => {
                    let _ = repo_or_err(loaded, &a.repo)?;
                    let recorded = guard::read_manifest(&loaded.workspace_root)?;
                    guard::intact(&loaded.workspace_root, &recorded)?;
                    println!("ok: guard_intact — every [guard].forbidden path matches the manifest");
                    return Ok(());
                }
                other => {
                    bail!(
                        "unknown gate `{other}`; known: path_patches, path_dep_versions, \
                         crate_metadata, links_conflicts, nexus_floor, no_regression, \
                         docs_fresh, roundtrip, guard_intact, all"
                    );
                }
            };
            return run_release(op, loaded);
        }
        ReleaseOp::Run(a) => {
            run_release_run(loaded, &a)?;
        }
        ReleaseOp::Trace { repo, workspace, json } => {
            let warehouse_root = loaded.warehouse_root();
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&warehouse_root)
                .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
            // Best-effort: build a query-only graph from the latest dep-graph
            // snapshot so suspects can be ranked across dependencies. No
            // snapshot ⇒ boundary-only trace (no suspect ranking).
            let graph = wh
                .block_on(nornir::warehouse::dep_graph::query_dep_graph_snapshots(&wh, &repo, None))
                .ok()
                .and_then(|snaps| snaps.into_iter().last())
                .map(|snap| {
                    nornir::warehouse::dep_graph::WorkspaceGraph::from_query_parts(
                        Default::default(),
                        snap.edges,
                    )
                });
            let trace = wh.block_on(nornir::release::regression::trace_gate_async(
                &wh, &workspace, &repo, graph.as_ref(),
            ))?;
            if json {
                println!("{}", serde_json::to_string_pretty(&trace)?);
            } else {
                print_regression_trace(&trace);
            }
        }
        ReleaseOp::Publish(a) => {
            let repo = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let outcomes =
                release::publish::publish_all(&repo_root, &repo.publish_order, a.dry_run)?;
            for (k, o) in &outcomes {
                println!("  {k:40} {o:?}");
            }
        }
        ReleaseOp::WaitForIndex { krate, version, timeout_secs } => {
            let waited_ms = release::publish::wait_for_index(
                &krate, &version,
                std::time::Duration::from_secs(timeout_secs),
            )?;
            println!("ok: {krate}@{version} visible on crates.io after {waited_ms} ms");
        }
        ReleaseOp::TarballStats { repo, krate } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let s = release::publish::tarball_stats(&repo_root, &krate)?;
            let warn = if s.tarball_bytes > release::publish::DEFAULT_TARBALL_BYTES_THRESHOLD {
                " WARN: above 5 MB threshold"
            } else { "" };
            let lf = s.largest_file.as_deref().unwrap_or("(none)");
            let lb = s.largest_file_bytes.unwrap_or(0);
            println!(
                "ok: {}@{} tarball {} bytes, {} files, largest={lf} ({lb} bytes){warn}",
                s.crate_name, s.version, s.tarball_bytes, s.file_count
            );
        }
        ReleaseOp::StripPatchBlocks(a) => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let (files, blocks) = release::cargo::strip_patch_crates_io_recursive(&repo_root)?;
            println!("ok: stripped {blocks} [patch.crates-io] block(s) across {files} Cargo.toml(s)");
        }
        ReleaseOp::Changelog { repo, range } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let md = release::cargo::changelog_markdown(&repo_root, &range)?;
            print!("{md}");
        }
        ReleaseOp::ImpactedCrates { repo, base } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let changed = release::cargo::changed_crates_since(&repo_root, &base)?;
            if changed.is_empty() {
                println!("ok: no changed crates since {base}");
                return Ok(());
            }
            // Resolve the iceberg warehouse the same way run_release_run does.
            let warehouse_root = loaded.warehouse_root();
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&warehouse_root)
                .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
            let snapshots = wh.block_on(
                nornir::warehouse::dep_graph::query_dep_graph_snapshots(&wh, &repo, None),
            )?;
            let mut edges: Vec<(String, String)> = Vec::new();
            if let Some(snap) = snapshots.last() {
                for e in &snap.edges {
                    for via in &e.via {
                        edges.push((e.from.clone(), via.clone()));
                        edges.push((via.clone(), e.to.clone()));
                    }
                }
            }
            let impacted = release::cargo::impacted_crates(&changed, &edges);
            for c in &impacted {
                println!("{c}");
            }
            eprintln!("# {} changed → {} impacted", changed.len(), impacted.len());
        }
        ReleaseOp::YankCascade { repo, undo, dry_run } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let list_path = repo_root.join(".nornir/yank-cascade.txt");
            let txt = std::fs::read_to_string(&list_path)
                .with_context(|| format!("read {}", list_path.display()))?;
            let mut order = Vec::new();
            for line in txt.lines() {
                let l = line.trim();
                if l.is_empty() || l.starts_with('#') { continue; }
                let mut sp = l.split_whitespace();
                let n = sp.next().ok_or_else(|| anyhow::anyhow!("bad line: {l}"))?;
                let v = sp.next().ok_or_else(|| anyhow::anyhow!("missing version: {l}"))?;
                order.push((n.to_string(), v.to_string()));
            }
            let results = release::cargo::yank_cascade(&repo_root, &order, undo, dry_run)?;
            for (k, v, s) in &results {
                println!("  {k:40} {v:12} {s:?}");
            }
        }
        ReleaseOp::MirrorToHolger { repo, krate, version, holger_base_url, token } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let tok = token.or_else(|| std::env::var("HOLGER_TOKEN").ok());
            let bytes = release::cargo::mirror_to_holger(
                &repo_root, &krate, &version, &holger_base_url, tok.as_deref(),
            )?;
            println!("ok: mirrored {krate}@{version} ({bytes} bytes) to {holger_base_url}");
        }
        ReleaseOp::BumpVersion { repo, pkg, new_version, bump_consumers, dry_run } => {
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &repo);
            let plan = release::cargo::plan_version_bump(
                &repo_root, &pkg, &new_version, bump_consumers,
            )?;
            if plan.edits.is_empty() {
                println!("ok: no references to `{pkg}` found under {}", repo_root.display());
                return Ok(());
            }
            for e in &plan.edits {
                let rel = e.cargo_toml.strip_prefix(&repo_root).unwrap_or(&e.cargo_toml);
                println!(
                    "  {:50} {:?} {} {}{}",
                    rel.display(), e.location, e.pkg, e.old_version, e.new_version
                );
            }
            if dry_run {
                println!("dry-run: {} edit(s) across {} file(s)",
                    plan.edits.len(),
                    plan.edits.iter().map(|e| &e.cargo_toml).collect::<std::collections::BTreeSet<_>>().len()
                );
            } else {
                let n = release::cargo::apply_bump_plan(&plan)?;
                println!("ok: applied {} edit(s) across {n} file(s)", plan.edits.len());
            }
        }
    }
    Ok(())
}

fn history_path(repo_root: &Path, repo: &config::Repo) -> PathBuf {
    repo_root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history })
}

/// Full bench-run history for `repo` from iceberg, for the `bench_history` doc
/// section. The render path and the `docs_fresh` gate MUST use the *same* source
/// or the gate false-drifts against the rendered README. Best-effort (empty when
/// iceberg has no rows / can't open).
fn bench_history_runs(loaded: &Loaded, repo_name: &str) -> Vec<bench::BenchRun> {
    warehouse::open(&loaded.nornir.storage, &loaded.workspace_root)
        .ok()
        .and_then(|wh| wh.query_bench_runs(&warehouse::BenchFilter::for_repo(repo_name)).ok())
        .unwrap_or_default()
}

/// Latest [`BenchRun`] for `name`: iceberg first (new world), then
/// `bench_history.jsonl` fallback (legacy). Returns the iceberg row
/// if present even when JSONL is also populated, so newly-written
/// runs become visible to gates and docs immediately.
fn last_run(loaded: &Loaded, name: &str) -> Result<bench::BenchRun> {
    let wh = warehouse::open(&loaded.nornir.storage, &loaded.workspace_root)?;
    let filter = warehouse::BenchFilter::for_repo(name);
    if let Ok(mut runs) = wh.query_bench_runs(&filter) {
        if let Some(latest) = runs.pop() {
            return Ok(latest);
        }
    }
    let repo = repo_or_err(loaded, name)?;
    let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, name);
    let path = history_path(&repo_root, repo);
    let runs = bench::history::read_all(&path)?;
    runs.into_iter()
        .last()
        .ok_or_else(|| anyhow!("no bench runs in iceberg or {}", path.display()))
}

fn run_gate_all(loaded: &Loaded, repo_name: &str) -> Result<()> {
    let repo = repo_or_err(loaded, repo_name)?;
    let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, repo_name);
    let g = &repo.gates;
    let mut passed: Vec<String> = Vec::new();
    let mut failed: Vec<(String, String)> = Vec::new();

    macro_rules! push {
        ($n:expr, $r:expr) => {
            match $r {
                Ok(()) => passed.push($n.into()),
                Err(e) => failed.push(($n.into(), format!("{e:#}"))),
            }
        };
    }

    if g.no_path_patches {
        push!("no_path_patches", release::gate::no_path_patches(&repo_root));
    }
    let last = last_run(loaded, repo_name);
    if g.nexus_floor {
        push!("nexus_floor", last.as_ref().map_err(|e| 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 = history_path(&repo_root, repo);
        push!("no_regression",
            last.as_ref().map_err(|e| 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",
            release::gate::integration_roundtrip_via_cargo_test(&repo_root, &kinds));
    }
    if g.docs_fresh {
        let history = bench_history_runs(loaded, repo_name);
        let r: Result<()> = (|| {
            let run = last.as_ref().map_err(|e| anyhow!("{e:#}"))?;
            let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, Some(run))
                .with_history(&history);
            let readme = repo_root.join("README.md");
            if readme.exists() { docs::check_file(&readme, &ctx)?; }
            docs::assemble_and_check(&repo_root, run)
        })();
        push!("docs_fresh", r);
    }

    println!("=== gate-all: {repo_name} ===");
    for n in &passed { println!("{n}"); }
    for (n, e) in &failed { println!("{n}: {e}"); }
    if !failed.is_empty() {
        bail!("{} gate(s) failed", failed.len());
    }
    println!("{} gate(s) passed", passed.len());
    Ok(())
}

/// Human-readable rendering of a [`nornir::release::regression::Trace`].
fn print_regression_trace(t: &nornir::release::regression::Trace) {
    let short = |s: &str| s.chars().take(12).collect::<String>();
    println!("regression trace · repo `{}`", t.repo);
    if t.frames.is_empty() {
        println!("  (no recorded releases for this repo)");
        return;
    }
    match (&t.last_good, &t.first_bad) {
        (Some(g), None) => {
            println!("  ✓ green — last good {} ({})", short(&g.git_sha), g.gate_status);
        }
        (Some(g), Some(b)) => {
            println!("  ✓ last good : {}  ({})", short(&g.git_sha), g.gate_status);
            println!("  ✗ first bad : {}  ({})", short(&b.git_sha), b.gate_status);
            println!("  ⇒ bisect the commits in  {}..{}", short(&g.git_sha), short(&b.git_sha));
        }
        (None, Some(b)) => {
            println!("  ✗ never green on record; first bad {} ({})", short(&b.git_sha), b.gate_status);
        }
        (None, None) => {}
    }
    if !t.suspect_shas.is_empty() {
        let s: Vec<String> = t.suspect_shas.iter().map(|x| short(x)).collect();
        println!("  suspect release SHA(s): {}", s.join(", "));
    }
    if !t.suspects.is_empty() {
        println!("  ranked suspects (nearest dep first):");
        for s in &t.suspects {
            let tag = if s.dep_distance == 0 {
                "self".to_string()
            } else {
                format!("dep+{}", s.dep_distance)
            };
            let g = s.last_good_sha.as_deref().map(short).unwrap_or_else(|| "".into());
            let b = s.first_bad_sha.as_deref().map(short).unwrap_or_else(|| "".into());
            println!("    [{tag}] {}  {g}{b}", s.repo);
        }
    }
    println!("  timeline (oldest→newest):");
    for f in &t.frames {
        println!("    {} {}  {}", if f.good { "" } else { "" }, short(&f.git_sha), f.gate_status);
    }
}

fn run_release_run(loaded: &Loaded, args: &ReleaseRunArgs) -> Result<()> {
    use nornir::release::progress::{now, ProgressWriter, ReleaseEvent};
    use nornir::warehouse::dep_graph::{query_dep_graph_snapshots, topo_order_from_edges};
    use nornir::warehouse::iceberg::IcebergWarehouse;

    // 0. Open a structured progress sink alongside the existing log
    //    file. Consumers: nornir-server's /release/progress SSE +
    //    egui viz live pane. File is ndjson, append-only.
    let log_dir = loaded.workspace_root.join("workspace_holger/.nornir/logs");
    let run_id = chrono::Utc::now().timestamp().to_string();
    let progress = ProgressWriter::open(&log_dir, &run_id)
        .with_context(|| format!("open progress writer in {}", log_dir.display()))
        .ok();
    if let Some(p) = &progress {
        println!("📡 live events: {}", p.path().display());
        p.emit(&ReleaseEvent::RunStart {
            ts: now(),
            run_id: run_id.clone(),
            workspace: args.workspace.clone(),
        });
    }
    let progress_end = progress.clone();
    let run_id_for_end = run_id.clone();

    // 1. Selected repo set (single --repo, or every configured repo).
    let all_repos: Vec<String> = loaded.nornir.repo.keys().cloned().collect();
    let selected: Vec<String> = if let Some(name) = &args.repo {
        if !loaded.nornir.repo.contains_key(name) {
            bail!("unknown repo `{name}`; configured: {:?}", all_repos);
        }
        vec![name.clone()]
    } else {
        all_repos.clone()
    };

    // 2. Load the latest dep-graph snapshot from iceberg and topo-sort.
    //    `warehouse::open` only hands back a trait object; we need the
    //    concrete IcebergWarehouse for `query_dep_graph_snapshots`, so
    //    resolve the same path the warehouse module would have.
    let storage = &loaded.nornir.storage;
    let warehouse_root = if storage.local_path.is_empty() {
        loaded.workspace_root.join("workspace_holger/.nornir/warehouse")
    } else {
        loaded.workspace_root.join(&storage.local_path).join("warehouse")
    };
    let wh = IcebergWarehouse::open(&warehouse_root)
        .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
    let snapshots = wh
        .block_on(query_dep_graph_snapshots(&wh, &args.workspace, None))
        .with_context(|| format!("query dep_graph_edges for workspace `{}`", args.workspace))?;
    let latest = snapshots.into_iter().last();

    let order: Vec<String> = match (&latest, args.repo.is_some()) {
        (_, true) => selected.clone(), // single repo → order is trivially itself
        (Some(snap), false) => {
            println!(
                "📚 using dep-graph snapshot {} ({}, {} edge(s))",
                snap.snapshot_id,
                snap.timestamp.to_rfc3339(),
                snap.edges.len()
            );
            topo_order_from_edges(&selected, &snap.edges)
        }
        (None, false) => {
            println!(
                "⚠ no dep_graph_edges rows for workspace `{}` — falling back to nornir.toml repo order",
                args.workspace
            );
            selected.clone()
        }
    };
    println!("▶ release run order: {}", order.join(""));

    // Release-lineage scaffolding: one id for the whole run, the dep-graph
    // snapshot it's pinned against, and the per-repo records we accumulate as we
    // go (written to `release_lineage` at the end, with the capture-phase pins).
    let release_id = uuid::Uuid::new_v4();
    let dep_graph_snapshot_id = latest
        .as_ref()
        .map(|s| s.snapshot_id)
        .unwrap_or_else(uuid::Uuid::nil);
    let mut lineage: Vec<release::pipeline::RepoReleaseRecord> = Vec::new();

    // 3. Per-repo: cargo test → bench (persist) → gate-all. Abort on first failure.
    for (idx, name) in order.iter().enumerate() {
        let mut tests_passed = 0u32;
        let mut tests_failed = 0u32;
        let mut tantivy_pin: Option<String> = None;
        let mut dwarf_pin: Option<String> = None;
        let repo_cfg = repo_or_err(loaded, name)?;
        let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, name);
        println!(
            "\n━━━ [{}/{}] {name} @ {} ━━━",
            idx + 1,
            order.len(),
            repo_root.display(),
        );

        if let Some(p) = &progress {
            use nornir::release::progress::{now, ReleaseEvent};
            p.emit(&ReleaseEvent::RepoStart {
                ts: now(),
                repo: name.clone(),
                sha: String::new(),
            });
            p.emit(&ReleaseEvent::PhaseStart {
                ts: now(),
                repo: name.clone(),
                phase: "test".to_string(),
            });
        }

        if !args.skip_tests {
            let t0 = std::time::Instant::now();
            let (passed, failed, ok) =
                release::pipeline::run_cargo_test(&repo_root, Some(name), progress.as_ref())
                    .with_context(|| format!("cargo test for `{name}`"))?;
            tests_passed = passed;
            tests_failed = failed;
            println!("  tests: {passed} passed, {failed} failed");
            if let Some(p) = &progress {
                use nornir::release::progress::{now, ReleaseEvent};
                p.emit(&ReleaseEvent::PhaseEnd {
                    ts: now(),
                    repo: name.clone(),
                    phase: "test".to_string(),
                    ok,
                    duration_ms: t0.elapsed().as_millis() as u64,
                });
                p.emit(&ReleaseEvent::RepoEnd {
                    ts: now(),
                    repo: name.clone(),
                    ok,
                });
            }
            if !ok {
                if let Some(p) = &progress {
                    use nornir::release::progress::{now, ReleaseEvent};
                    p.emit(&ReleaseEvent::RunEnd {
                        ts: now(),
                        run_id: run_id.clone(),
                        ok: false,
                    });
                }
                bail!("`{name}` test phase failed — aborting release run");
            }
        } else {
            println!("  tests: skipped (--skip-tests)");
        }

        if !args.skip_bench {
            println!("  ⚡ running nornir-bench in {}", repo_root.display());
            match release::pipeline::run_bench_example(&repo_root)
                .with_context(|| format!("run nornir-bench for `{name}`"))?
            {
                None => println!("  bench: skipped (no examples/nornir-bench.rs)"),
                Some(mut run) => {
                    if run.machine.trim().is_empty() {
                        run.machine = std::env::var("NORNIR_MACHINE").unwrap_or_else(|_| {
                            std::fs::read_to_string("/etc/hostname")
                                .ok()
                                .map(|s| s.trim().to_string())
                                .filter(|s| !s.is_empty())
                                .unwrap_or_else(|| "unknown".into())
                        });
                    }
                    let n_failed = run.tests.iter().filter(|t| !t.passed).count();
                    let id = wh
                        .block_on(wh.append_bench_run_async(name, &run))
                        .with_context(|| format!("persist bench run for `{name}`"))?;
                    println!(
                        "  bench: {} result(s), {} test fail(s), persisted as {}",
                        run.results.len(),
                        n_failed,
                        id
                    );
                    for r in &run.results {
                        let mut kv: Vec<String> = r
                            .metrics
                            .iter()
                            .filter_map(|(k, v)| v.as_f64().map(|f| format!("{k}={f:.2}")))
                            .collect();
                        kv.sort();
                        println!("    • {:30} {}", r.name, kv.join(" "));
                    }
                    if n_failed > 0 {
                        for t in run.tests.iter().filter(|t| !t.passed) {
                            println!(
                                "    ✗ test {}{}",
                                t.name,
                                t.message
                                    .as_deref()
                                    .map(|m| format!(": {m}"))
                                    .unwrap_or_default()
                            );
                        }
                        bail!("`{name}` bench reported {n_failed} failing test(s) — aborting");
                    }
                }
            }
        } else {
            println!("  bench: skipped (--skip-bench)");
        }

        if !args.skip_render_docs {
            match last_run(loaded, name) {
                Ok(run) => {
                    let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, Some(&run));
                    let readme = repo_root.join("README.md");
                    if readme.exists() {
                        match docs::assemble_file(&readme, &ctx) {
                            Ok(_) => println!(
                                "  docs: rendered README.md from iceberg bench v{}",
                                run.version
                            ),
                            Err(e) => println!("  docs: ⚠ render skipped: {e:#}"),
                        }
                    } else {
                        println!("  docs: README.md absent — skipping render");
                    }
                }
                Err(e) => println!("  docs: ⚠ no bench row to render from: {e:#}"),
            }
        } else {
            println!("  docs: skipped (--skip-render-docs)");
        }

        if !args.skip_gates {
            let _ = repo_cfg; // referenced by run_gate_all via loaded
            run_gate_all(loaded, name)
                .with_context(|| format!("gate-all for `{name}`"))?;
        } else {
            println!("  gates: skipped (--skip-gates)");
        }

        // ---- capture: every source-fact projection this repo computed at
        //      its release SHA lands in the warehouse (fat-client rule:
        //      nothing computed is discarded). Each step is best-effort +
        //      non-fatal — a capture hiccup must never fail a green release.
        if !args.skip_snapshot {
            let (sha, branch) =
                read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));

            // (a) knowledge map — syn symbols/calls + gix git-heat.
            match nornir::knowledge::scan_all(&repo_root, name) {
                Ok(res) => {
                    let s = wh.append_symbol_scan(&res.symbols);
                    let g = wh.append_git_heat_scan(&res.git);
                    match (s, g) {
                        (Ok(_), Ok(_)) => println!(
                            "  📖 knowledge: symbols={} calls={} (symbol_snapshot={} git_snapshot={})",
                            res.symbols.symbols.len(), res.symbols.calls.len(),
                            res.symbols.snapshot_id, res.git.snapshot_id,
                        ),
                        (s, g) => println!("  📖 knowledge: ⚠ partial: {:?} {:?}", s.err(), g.err()),
                    }
                }
                Err(e) => println!("  📖 knowledge: ⚠ scan skipped: {e:#}"),
            }

            // (b) tantivy code index → urðr snapshot. Idempotent per
            //     (repo, sha): reuse an existing capture unless --recapture.
            let existing_index = wh.block_on(wh.index_snapshot_id_for(name, &sha)).ok().flatten();
            let index_dir = loaded.workspace_root.join(".nornir/cache/index");
            if let (Some(id), false) = (&existing_index, args.recapture) {
                println!("  ⏃ urðr: snapshot exists for sha={} → reuse {id} (--recapture to force)",
                    &sha[..sha.len().min(12)]);
                tantivy_pin = Some(id.clone());
            } else if !index_dir.exists() {
                println!("  ⏃ urðr: workspace index absent at {} — skipping snapshot", index_dir.display());
            } else {
                match nornir::index::snapshot::snapshot_to_iceberg(
                    &wh,
                    &args.workspace,
                    name,
                    &sha,
                    &branch,
                    &index_dir,
                ) {
                    Ok(snap) => {
                        println!(
                            "  ⏃ urðr: snapshot {} pinned ({} blob(s), {} bytes, sha={})",
                            snap.snapshot_id,
                            snap.blob_count,
                            snap.total_bytes,
                            &snap.git_sha[..snap.git_sha.len().min(12)],
                        );
                        tantivy_pin = Some(snap.snapshot_id.to_string());
                    }
                    Err(e) => println!("  ⏃ urðr: ⚠ snapshot skipped: {e:#}"),
                }
            }

            // (c) semantic vectors — embeds + persists when this build has an
            //     embedder; a one-line skip-hint otherwise (same as `map`).
            //     Already idempotent per snapshot (only missing vectors embed).
            if let Err(e) = map_vectors(&wh, &args.workspace, name, &repo_root, &sha, &branch) {
                println!("  🧬 vectors: ⚠ skipped: {e:#}");
            }

            // (d) DWARF facts from any binary the test/bench build produced.
            //     Idempotent per (repo, sha) like the index.
            let existing_dwarf = wh.block_on(wh.dwarf_snapshot_id_for(name, &sha)).ok().flatten();
            if let (Some(id), false) = (&existing_dwarf, args.recapture) {
                println!("  🔬 dwarf: snapshot exists for sha → reuse {id} (--recapture to force)");
                dwarf_pin = Some(id.clone());
            } else {
                dwarf_pin = capture_dwarf(
                    &wh, &args.workspace, name, &repo_root, &sha, &branch,
                    &loaded.workspace_root, &warehouse_root,
                );
            }
        }

        // ---- step 3: commit + push regenerated docs ----------------
        if !args.skip_push {
            use nornir::release::progress::{now, ReleaseEvent};
            let t0 = std::time::Instant::now();
            if let Some(p) = &progress {
                p.emit(&ReleaseEvent::PhaseStart {
                    ts: now(),
                    repo: name.clone(),
                    phase: "push".to_string(),
                });
            }
            let msg = format!("release({name}): regenerate docs from bench run");
            let push_ok = match release::publish::commit_release(&repo_root, &msg) {
                Ok(Some(sha)) => {
                    println!("  📝 committed release docs: {}", &sha[..sha.len().min(12)]);
                    match release::publish::push(&repo_root, /* push_tags = */ false) {
                        Ok(true) => { println!("  ⤴  pushed to origin"); true }
                        Ok(false) => true,
                        Err(e) => { println!("  ⚠ push step failed (continuing): {e:#}"); false }
                    }
                }
                Ok(None) => {
                    println!("  📝 docs unchanged — nothing to commit");
                    true
                }
                Err(e) => {
                    println!("  ⚠ commit failed (continuing): {e:#}");
                    false
                }
            };
            if let Some(p) = &progress {
                p.emit(&ReleaseEvent::PhaseEnd {
                    ts: now(),
                    repo: name.clone(),
                    phase: "push".to_string(),
                    ok: push_ok,
                    duration_ms: t0.elapsed().as_millis() as u64,
                });
            }
        } else {
            println!("  push: skipped (--skip-push)");
        }

        // ---- step 4: cargo publish in declared phases --------------
        if !args.skip_publish && !repo_cfg.publish_order.is_empty() {
            use nornir::release::progress::{now, ReleaseEvent};
            let t0 = std::time::Instant::now();
            if let Some(p) = &progress {
                p.emit(&ReleaseEvent::PhaseStart {
                    ts: now(),
                    repo: name.clone(),
                    phase: "publish".to_string(),
                });
            }
            let pub_ok = match release::publish::publish_all(
                &repo_root,
                &repo_cfg.publish_order,
                args.dry_run_publish,
            ) {
                Ok(outcomes) => {
                    for (k, o) in &outcomes {
                        println!("    📦 {k:40} {o:?}");
                    }
                    true
                }
                Err(e) => {
                    println!("  ✗ publish failed: {e:#}");
                    false
                }
            };
            if let Some(p) = &progress {
                p.emit(&ReleaseEvent::PhaseEnd {
                    ts: now(),
                    repo: name.clone(),
                    phase: "publish".to_string(),
                    ok: pub_ok,
                    duration_ms: t0.elapsed().as_millis() as u64,
                });
            }
            if !pub_ok {
                if let Some(p) = &progress_end {
                    p.emit(&ReleaseEvent::RunEnd {
                        ts: now(),
                        run_id: run_id_for_end.clone(),
                        ok: false,
                    });
                }
                bail!("`{name}` publish phase failed — aborting release run");
            }
        } else if repo_cfg.publish_order.is_empty() {
            println!("  publish: no publish_order configured for `{name}` — skipping");
        } else {
            println!("  publish: skipped (--skip-publish)");
        }

        // Reaching here means every gate passed (failures `bail!` above), so
        // record a green lineage row carrying the capture-phase pins. Git state
        // is best-effort; `published_versions` is left empty for now (the
        // publish step's outcomes don't carry resolved versions yet).
        let git = release::pipeline::read_git_state(&repo_root).unwrap_or_else(|_| {
            let (sha, branch) =
                read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
            release::pipeline::RepoGitState { sha, branch, dirty: false }
        });
        lineage.push(release::pipeline::RepoReleaseRecord {
            repo: name.clone(),
            build_order_idx: idx,
            git,
            gate_status: "succeeded".to_string(),
            tests_passed,
            tests_failed,
            published_versions: Vec::new(),
            tantivy_snapshot_id: tantivy_pin,
            dwarf_snapshot_id: dwarf_pin,
        });
    }

    // Write the release_lineage rows (with their Urðr pins) for this run.
    if !lineage.is_empty() {
        match wh.block_on(release::pipeline::persist_lineage(
            &wh,
            release_id,
            &args.workspace,
            &dep_graph_snapshot_id,
            &lineage,
            false,
        )) {
            Ok(()) => println!(
                "📌 release lineage: {} repo row(s) pinned (release {})",
                lineage.len(),
                release_id,
            ),
            Err(e) => println!("⚠ release lineage write failed: {e:#}"),
        }
    }

    println!("\n🎉 all {} repo(s) green: {}", order.len(), order.join(", "));
    if let Some(p) = &progress_end {
        p.emit(&ReleaseEvent::RunEnd {
            ts: now(),
            run_id: run_id_for_end,
            ok: true,
        });
    }
    Ok(())
}

fn run_docs(op: DocsOp, loaded: &Loaded) -> Result<()> {
    // Client mode: init/render/check run on the server (it owns the docs tree).
    if let Some(server) = server_target() {
        match &op {
            DocsOp::Init(a) => return docs_remote(&server, "init", &a.repo),
            DocsOp::Render(a) => return docs_remote(&server, "render", &a.repo),
            DocsOp::Check(a) => return docs_remote(&server, "check", &a.repo),
            DocsOp::History(a) => {
                return docs_history_remote(
                    &server, &a.repo.repo, a.doc.as_deref(), a.version.as_deref(),
                    a.format.as_deref(), a.limit,
                )
            }
            _ => {}
        }
    }
    match op {
        DocsOp::Init(a) => run_docs_init(loaded, &a)?,
        DocsOp::Render(a) => run_docs_render(loaded, &a)?,
        DocsOp::Check(a) => run_docs_check(loaded, &a)?,
        #[cfg(feature = "docs-export")]
        DocsOp::Export(a) => run_docs_export(loaded, a)?,
        #[cfg(feature = "docs-export")]
        DocsOp::Book(a) => run_docs_book(loaded, a)?,
        DocsOp::History(a) => run_docs_history(loaded, &a)?,
        DocsOp::Index(a) => run_docs_index(loaded, &a)?,
        DocsOp::Search(a) => run_docs_search(loaded, &a)?,
    }
    Ok(())
}

fn docs_ctx_for<'a>(
    loaded: &'a Loaded,
    repo_name: &str,
) -> Result<(docs::RepoLayout, PathBuf, Option<nornir::bench::BenchRun>, Vec<nornir::bench::BenchRun>)>
{
    repo_or_err(loaded, repo_name)?; // validate the repo is configured
    let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, repo_name);
    // Iceberg-first run selection (same `last_run` the gates use) so a freshly
    // persisted `nornir bench run` is rendered immediately; `last_run` falls back
    // to bench_history.jsonl when iceberg has no rows. Previously this read the
    // jsonl directly, so docs lagged behind iceberg-written runs.
    let last = last_run(loaded, repo_name).ok();
    // Full bench-run history (iceberg) for the `bench_history` section; best-effort.
    let history = bench_history_runs(loaded, repo_name);
    Ok((docs::RepoLayout::new(&repo_root), repo_root, last, history))
}

fn run_docs_init(loaded: &Loaded, a: &RepoArg) -> Result<()> {
    let (layout, _, _, _) = docs_ctx_for(loaded, &a.repo)?;
    let srcs = docs::init_repo(&layout)?;
    println!("initialised {}", layout.nornir_dir().display());
    for s in &srcs {
        println!("  source: {}", s.display());
    }
    println!("next: `nornir docs render {}`", a.repo);
    Ok(())
}

fn run_docs_render(loaded: &Loaded, a: &RepoArg) -> Result<()> {
    let (layout, repo_root, last, history) = docs_ctx_for(loaded, &a.repo)?;
    let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, last.as_ref())
        .with_history(&history);
    let reports = docs::render_all(&layout, &ctx)?;
    if reports.is_empty() {
        println!(
            "no sources under {} — run `nornir docs init {}` first",
            layout.nornir_dir().display(),
            a.repo
        );
        return Ok(());
    }
    for r in &reports {
        let verb = if r.changed { "wrote" } else { "unchanged" };
        println!(
            "{verb}: {} ({} bytes, {} section{})",
            r.output.display(),
            r.bytes,
            r.sections.len(),
            if r.sections.len() == 1 { "" } else { "s" }
        );
    }
    Ok(())
}

fn run_docs_check(loaded: &Loaded, a: &RepoArg) -> Result<()> {
    let (layout, repo_root, last, history) = docs_ctx_for(loaded, &a.repo)?;
    let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, last.as_ref())
        .with_history(&history);
    docs::render_check_all(&layout, &ctx)?;
    println!("ok: every doc in {} matches its source", a.repo);
    Ok(())
}

#[cfg(feature = "docs-export")]
fn run_docs_export(loaded: &Loaded, a: DocsExportArgs) -> Result<()> {
    let (layout, repo_root, last, history) = docs_ctx_for(loaded, &a.repo.repo)?;
    // Always render first so the exported artifact reflects the latest source.
    let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, last.as_ref())
        .with_history(&history);
    let _ = docs::render_all(&layout, &ctx)?;

    let format = docs::DocFormat::parse(&a.format)?;
    let bytes = docs::export_repo(&repo_root, format)?;

    let cargo = std::fs::read_to_string(repo_root.join("Cargo.toml")).unwrap_or_default();
    let parsed: toml::Value = toml::from_str(&cargo).unwrap_or(toml::Value::Table(Default::default()));
    let pkg = parsed.get("package");
    let version = pkg
        .and_then(|p| p.get("version"))
        .and_then(|v| v.as_str())
        .unwrap_or("0.0.0")
        .to_string();

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

    // History → iceberg `doc_exports` (inline bytes, dedup by sha256).
    let workspace = workspace_name(loaded);
    let (git_sha, _) = read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
    let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
    let record = docs::record_doc_export(
        &wh, &workspace, &a.repo.repo, "README", &version, ext, &git_sha, &bytes,
    )?;

    // Optional user-chosen explicit output (in addition to docs/).
    if let Some(out_path) = a.out {
        if let Some(parent) = out_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&out_path, &bytes)?;
        println!("wrote {} ({} bytes, format={})", out_path.display(), bytes.len(), a.format);
    }

    println!("wrote {} ({} bytes, format={})", out.display(), bytes.len(), a.format);
    println!(
        "historized README {} ({} bytes, sha256 {}…, git {})",
        record.version,
        record.byte_len,
        &record.sha256[..12.min(record.sha256.len())],
        &record.git_sha[..record.git_sha.len().min(12)],
    );
    Ok(())
}

#[cfg(feature = "docs-export")]
fn run_docs_book(loaded: &Loaded, a: DocsBookArgs) -> Result<()> {
    let (layout, repo_root, last, history) = docs_ctx_for(loaded, &a.repo.repo)?;
    // Render managed artifacts first so the book reflects the latest source.
    let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, last.as_ref())
        .with_history(&history);
    let _ = docs::render_all(&layout, &ctx)?;

    let format = docs::DocFormat::parse(&a.format)?;
    let (bytes, sources) = docs::build_book(&repo_root, &ctx, format)?;

    println!("assembled {} source(s) into the book:", sources.len());
    for s in &sources {
        let shown = s.strip_prefix(&repo_root).unwrap_or(s);
        println!("  + {}", shown.display());
    }

    // Same resolution as the book cover (handles virtual workspaces via the
    // modal member version), so the warehouse record + filename agree with it.
    let version = docs::resolve_version(&repo_root);
    let ext = format.extension();

    // Current artifact → always <repo>/docs/book.<ext> (the live, link-target
    // copy); --out is an *additional* destination, never a replacement.
    let out = layout.export_path("book", ext);
    if let Some(parent) = out.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&out, &bytes)?;
    println!("wrote {} ({} bytes, format={})", out.display(), bytes.len(), a.format);
    if let Some(extra) = a.out {
        if let Some(parent) = extra.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&extra, &bytes)?;
        println!("wrote {} ({} bytes, format={})", extra.display(), bytes.len(), a.format);
    }

    // History → iceberg `doc_exports`.
    let workspace = workspace_name(loaded);
    let (git_sha, _) = read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
    let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
    let record = docs::record_doc_export(
        &wh, &workspace, &a.repo.repo, "book", &version, ext, &git_sha, &bytes,
    )?;
    println!(
        "historized book {} ({} bytes, sha256 {}…, git {})",
        record.version,
        record.byte_len,
        &record.sha256[..12.min(record.sha256.len())],
        &record.git_sha[..record.git_sha.len().min(12)],
    );
    Ok(())
}

fn run_docs_history(loaded: &Loaded, a: &DocsHistoryArgs) -> Result<()> {
    let _ = repo_or_err(loaded, &a.repo.repo)?;
    let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
    let filter = docs::ExportFilter {
        doc_name: a.doc.clone(),
        version: a.version.clone(),
        format: a.format.clone(),
        limit: Some(a.limit),
    };
    let rows = docs::list_doc_exports(&wh, &a.repo.repo, &filter)?;
    if rows.is_empty() {
        println!("no exports historized for {}", a.repo.repo);
        return Ok(());
    }
    println!(
        "{:<19}  {:<8}  {:<7}  {:>9}  {:<12}  {:<12}  {}",
        "generated_at", "doc", "format", "bytes", "sha256", "git", "export_id"
    );
    for r in &rows {
        let stamp = r.generated_at.get(0..19).unwrap_or(&r.generated_at);
        println!(
            "{:<19}  {:<8}  {:<7}  {:>9}  {:<12}  {:<12}  {}",
            stamp,
            r.doc_name,
            r.format,
            r.byte_len,
            &r.sha256[..12.min(r.sha256.len())],
            &r.git_sha[..12.min(r.git_sha.len())],
            r.export_id,
        );
    }
    println!("({} row{})", rows.len(), if rows.len() == 1 { "" } else { "s" });
    Ok(())
}

fn run_docs_index(loaded: &Loaded, a: &DocsIndexArgs) -> Result<()> {
    let (layout, repo_root, last, history) = docs_ctx_for(loaded, &a.repo.repo)?;
    // Refresh the generated managed docs (README/CHANGELOG) so the index
    // reflects the current `.nornir/` sources rather than a stale artifact.
    // (The rendered `docs/book.md` is refreshed separately by `docs book`.)
    let ctx = docs::Ctx::new(&repo_root, &loaded.workspace_root, last.as_ref())
        .with_history(&history);
    let _ = docs::render_all(&layout, &ctx)?;

    let (stats, dir) = docs::build_docs_index(&repo_root, &a.repo.repo)?;
    println!(
        "docs-index {} :: scanned={} added={} updated={} unchanged={} too_large={} errors={}",
        dir.display(),
        stats.scanned,
        stats.added,
        stats.updated,
        stats.skipped_unchanged,
        stats.skipped_too_large,
        stats.errors,
    );
    if !a.skip_snapshot {
        let workspace = workspace_name(loaded);
        let (sha, branch) =
            read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
        let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
        match docs::snapshot_docs_index(&wh, &workspace, &a.repo.repo, &sha, &branch, &repo_root) {
            Ok(snap) => println!(
                "✓ historized docs-index {} ({} blob(s), {} bytes, sha={})",
                snap.snapshot_id,
                snap.blob_count,
                snap.total_bytes,
                &snap.git_sha[..snap.git_sha.len().min(12)],
            ),
            Err(e) => eprintln!("docs-index snapshot skipped: {e}"),
        }
    }
    Ok(())
}

fn run_docs_search(loaded: &Loaded, a: &DocsSearchArgs) -> Result<()> {
    let _ = repo_or_err(loaded, &a.repo.repo)?;
    let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo.repo);
    let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
    let hits = docs::search_docs(
        &repo_root,
        &wh,
        &a.repo.repo,
        a.sha.as_deref(),
        &a.query,
        a.limit,
    )?;
    for h in &hits {
        println!("{:>6.2}  {}\n        {}", h.score, h.path, h.snippet);
    }
    if hits.is_empty() {
        eprintln!("# no hits");
    }
    Ok(())
}


fn run_introspect(op: IntrospectOp, loaded: &Loaded) -> Result<()> {
    // Client mode: the symbol/callgraph queries run on the server (the `binary`
    // path is resolved on the server's filesystem). Depgraph/Callgraph/LLVM have
    // no RPC and fall through to the embedded path.
    if let Some(server) = server_target() {
        let bin = |p: &std::path::Path| p.to_string_lossy().to_string();
        match &op {
            IntrospectOp::Symbols(a) => return introspect_symbols_remote(&server, &bin(&a.binary), "symbols", "", 0),
            IntrospectOp::SymbolLookup(a) => return introspect_symbols_remote(&server, &bin(&a.binary), "lookup", &a.pattern, a.limit),
            IntrospectOp::DefinedIn(a) => return introspect_symbols_remote(&server, &bin(&a.binary), "defined-in", &a.file, a.limit),
            IntrospectOp::Callers(a) => return introspect_calls_remote(&server, &bin(&a.binary), "callers", &a.name, None),
            IntrospectOp::Callees(a) => return introspect_calls_remote(&server, &bin(&a.binary), "callees", &a.name, None),
            IntrospectOp::PathBetween(a) => return introspect_calls_remote(&server, &bin(&a.binary), "path", &a.from, Some(&a.to)),
            _ => {}
        }
    }
    match op {
        IntrospectOp::Depgraph(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let g = introspect::depgraph::extract(&repo_root)?;
            print!("{}", g.to_mermaid());
        }
        IntrospectOp::Symbols(a) => {
            let syms = introspect::artifact::extract_symbols(&a.binary, &loaded.workspace_root)?;
            for s in &syms {
                println!("{}", serde_json::to_string(s)?);
            }
            eprintln!("# {} symbols", syms.len());
            if !a.no_save {
                let repo = a.repo.as_deref().unwrap_or("_workspace");
                let git_root = match &a.repo {
                    Some(name) => {
                        let _ = repo_or_err(loaded, name)?; // must be an appointed member
                        config::Nornir::repo_dir(&loaded.workspace_root, name)
                    }
                    None => loaded.workspace_root.clone(),
                };
                let warehouse_root = iceberg_warehouse_root(loaded);
                let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&warehouse_root)
                    .with_context(|| format!("open warehouse at {}", warehouse_root.display()))?;
                let (sha, branch) = read_git_head(&git_root)
                    .unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
                let cache_dir = warehouse_root
                    .parent()
                    .unwrap_or(warehouse_root.as_path())
                    .join("cache/dwarf")
                    .join(repo);
                // Capture the full DWARF facts (symbols + inline-call edges) from
                // the same binary, so the persisted snapshot serves both
                // `dwarf_symbol_lookup` and `dwarf_callers`/`callees`.
                let calls =
                    introspect::callgraph_dwarf::extract_callgraph(&a.binary, &loaded.workspace_root)?;
                let facts = introspect::persist::DwarfFacts { symbols: syms, calls };
                let snap = introspect::persist::snapshot_facts(
                    &wh, &workspace_name(loaded), repo, &sha, &branch, &facts, &cache_dir,
                )?;
                eprintln!(
                    "# persisted {} symbols + {} call edges → dwarf snapshot {} (repo={}, sha={})",
                    facts.symbols.len(),
                    facts.calls.len(),
                    snap.snapshot_id,
                    repo,
                    &snap.git_sha[..snap.git_sha.len().min(12)],
                );
            }
        }
        IntrospectOp::SymbolLookup(a) => {
            let syms = introspect::artifact::extract_symbols(&a.binary, &loaded.workspace_root)?;
            let hits = introspect::artifact::lookup(&syms, &a.pattern);
            for s in hits.iter().take(a.limit) {
                println!(
                    "{}:{}  {}",
                    s.file,
                    s.line.map(|n| n.to_string()).unwrap_or_else(|| "?".into()),
                    s.name_demangled
                );
            }
            eprintln!("# {} matches (showing {})", hits.len(), hits.len().min(a.limit));
        }
        IntrospectOp::DefinedIn(a) => {
            let syms = introspect::artifact::extract_symbols(&a.binary, &loaded.workspace_root)?;
            let hits = introspect::artifact::defined_in(&syms, &a.file);
            for s in hits.iter().take(a.limit) {
                println!(
                    "{}:{}  {}",
                    s.file,
                    s.line.map(|n| n.to_string()).unwrap_or_else(|| "?".into()),
                    s.name_demangled
                );
            }
            eprintln!("# {} matches (showing {})", hits.len(), hits.len().min(a.limit));
        }
        IntrospectOp::Callgraph(a) => {
            let edges = introspect::callgraph_dwarf::extract_callgraph(&a.binary, &loaded.workspace_root)?;
            for e in &edges {
                println!("{}", serde_json::to_string(e)?);
            }
            eprintln!("# {} inline edges", edges.len());
        }
        IntrospectOp::CallgraphLlvm(a) => {
            let crates_owned: Option<Vec<String>> = a.crates
                .as_ref()
                .map(|s| s.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
            let crates_ref: Option<Vec<&str>> = crates_owned.as_ref().map(|v| v.iter().map(|s| s.as_str()).collect());
            let edges = if a.path.is_dir() {
                introspect::callgraph_llvm::extract_from_dir(&a.path, crates_ref.as_deref())?
            } else {
                introspect::callgraph_llvm::extract_from_files(&[a.path.clone()], crates_ref.as_deref())?
            };
            for e in &edges {
                println!("{}", serde_json::to_string(e)?);
            }
            eprintln!("# {} direct edges", edges.len());
        }
        IntrospectOp::Callers(a) => {
            let edges = introspect::callgraph_dwarf::extract_callgraph(&a.binary, &loaded.workspace_root)?;
            let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
            for n in cg.callers_of(&a.name) { println!("{n}"); }
        }
        IntrospectOp::Callees(a) => {
            let edges = introspect::callgraph_dwarf::extract_callgraph(&a.binary, &loaded.workspace_root)?;
            let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
            for n in cg.callees_of(&a.name) { println!("{n}"); }
        }
        IntrospectOp::PathBetween(a) => {
            let edges = introspect::callgraph_dwarf::extract_callgraph(&a.binary, &loaded.workspace_root)?;
            let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
            match cg.path_between(&a.from, &a.to) {
                Some(path) => for n in path { println!("{n}"); },
                None => eprintln!("no path from {} to {}", a.from, a.to),
            }
        }
    }
    Ok(())
}

fn run_warehouse(op: WarehouseOp, loaded: &Loaded) -> Result<()> {
    let wh = warehouse::open(&loaded.nornir.storage, &loaded.workspace_root)?;
    match op {
        WarehouseOp::ImportJsonl(a) => {
            let repo = repo_or_err(loaded, &a.repo)?;
            let path = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo)
                .join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
            let runs = bench::history::read_all(&path)?;
            let mut imported = 0usize;
            for r in &runs {
                if r.machine.trim().is_empty() {
                    eprintln!("skipping run dated {}: no machine", r.date);
                    continue;
                }
                wh.append_bench_run(&a.repo, r)?;
                imported += 1;
            }
            println!("imported {imported}/{} runs from {}", runs.len(), path.display());
        }
        WarehouseOp::Query(args) => {
            let filter = warehouse::BenchFilter {
                repo: Some(args.repo),
                machine: args.machine,
                limit: args.last,
            };
            for r in wh.query_bench_runs(&filter)? {
                println!("{}", serde_json::to_string(&r)?);
            }
        }
    }
    Ok(())
}

fn run_index(op: IndexOp, loaded: &Loaded) -> Result<()> {
    // Lazy index handle: build uses a plain open (writer path);
    // search/stats use open_or_restore so a nuked cache transparently
    // rehydrates from iceberg before we touch it. Snapshot/restore
    // manage their own dirs.
    let open_for_read = || -> Result<index::Index> {
        let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(
            &iceberg_warehouse_root(loaded),
        )?;
        let (idx, _restored) = index::Index::open_or_restore_at(
            &loaded.workspace_root,
            &cache_index_dir(loaded),
            &wh,
            "_workspace",
            None,
        )?;
        Ok(idx)
    };
    match op {
        IndexOp::Build(a) => {
            let index_dir = cache_index_dir(loaded);
            if a.clean && index_dir.exists() {
                std::fs::remove_dir_all(&index_dir)
                    .with_context(|| format!("clean index dir {}", index_dir.display()))?;
                println!("cleaned index dir {} (rebuilding from scratch)", index_dir.display());
            }
            let repos: Vec<String> = loaded.nornir.repo.keys().cloned().collect();
            let idx = index::Index::open_at(&loaded.workspace_root, &index_dir)?
                .with_repo_scope(repos);
            let stats = idx.build()?;
            println!(
                "scanned={} added={} updated={} unchanged={} too_large={} errors={}",
                stats.scanned,
                stats.added,
                stats.updated,
                stats.skipped_unchanged,
                stats.skipped_too_large,
                stats.errors,
            );
            // Historize the built index into the warehouse by default, so it's not
            // stranded in the local cache (the fat-client "save everything" rule).
            if !a.no_snapshot {
                let (snap_dir, repo_label, sha, branch) = resolve_index_target(loaded, None)?;
                let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(
                    &iceberg_warehouse_root(loaded),
                )?;
                match nornir::index::snapshot::snapshot_to_iceberg(
                    &wh, &workspace_name(loaded), &repo_label, &sha, &branch, &snap_dir,
                ) {
                    Ok(snap) => println!(
                        "✓ snapshot {} ({} blob(s), {} bytes, sha={})",
                        snap.snapshot_id,
                        snap.blob_count,
                        snap.total_bytes,
                        &snap.git_sha[..snap.git_sha.len().min(12)],
                    ),
                    Err(e) => eprintln!("⚠ index snapshot skipped: {e:#}"),
                }
            }
        }
        IndexOp::Search(a) => {
            if let Some(server) = server_target() {
                return search_remote(&server, &a.query, a.corpus.as_deref(), a.repo.as_deref(), a.limit);
            }
            let idx = open_for_read()?;
            let corpus = match a.corpus.as_deref() {
                None => None,
                Some(s) => Some(
                    index::Corpus::parse(s)
                        .ok_or_else(|| anyhow!("unknown corpus: {s}"))?,
                ),
            };
            let hits = idx.search(&a.query, corpus, a.repo.as_deref(), a.limit)?;
            for h in &hits {
                println!(
                    "{:>6.2}  [{}/{}]  {}\n        {}",
                    h.score,
                    h.corpus,
                    if h.repo.is_empty() { "-" } else { &h.repo },
                    h.path,
                    h.snippet
                );
            }
        }
        IndexOp::Stats => {
            if let Some(server) = server_target() {
                return index_stats_remote(&server);
            }
            let idx = open_for_read()?;
            let s = idx.stats()?;
            println!("total: {}", s.total);
            for (c, n) in &s.by_corpus {
                println!("  {:<14} {}", c, n);
            }
        }
        IndexOp::Snapshot(a) => {
            let (index_dir, repo_label, sha, branch) = resolve_index_target(loaded, a.repo.as_deref())?;
            if let Some(server) = server_target() {
                return index_snapshot_remote(&server, &repo_label, &a.workspace, &sha, &branch);
            }
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(
                &iceberg_warehouse_root(loaded),
            )?;
            let snap = nornir::index::snapshot::snapshot_to_iceberg(
                &wh,
                &a.workspace,
                &repo_label,
                &sha,
                &branch,
                &index_dir,
            )?;
            println!(
                "✓ snapshot {} ({}, {} blob(s), {} bytes, sha={})",
                snap.snapshot_id,
                snap.repo,
                snap.blob_count,
                snap.total_bytes,
                &snap.git_sha[..snap.git_sha.len().min(12)],
            );
        }
        IndexOp::Restore(a) => {
            let (default_dir, repo_label, _, _) = resolve_index_target(loaded, a.repo.as_deref())?;
            let into = a.into.unwrap_or(default_dir);
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(
                &iceberg_warehouse_root(loaded),
            )?;
            let snap = nornir::index::snapshot::restore_from_iceberg(
                &wh,
                &repo_label,
                a.sha.as_deref(),
                &into,
            )?;
            println!(
                "✓ restored snapshot {} into {} ({} blob(s), {} bytes, sha={})",
                snap.snapshot_id,
                into.display(),
                snap.blob_count,
                snap.total_bytes,
                &snap.git_sha[..snap.git_sha.len().min(12)],
            );
        }
        IndexOp::Upload(a) => {
            let (index_dir, repo_label, sha, branch) = resolve_index_target(loaded, a.repo.as_deref())?;
            let Some(server) = server_target() else {
                bail!(
                    "`index upload` pushes a local index to a running server, but NORNIR_SERVER \
                     is not set. For the embedded warehouse use `nornir index snapshot`."
                );
            };
            return index_upload_remote(&server, &index_dir, &repo_label, &a.workspace, &sha, &branch);
        }
    }
    Ok(())
}

// ----- vector / semantic search ---------------------------------------------

#[cfg(feature = "vector")]
fn run_vector(op: VectorOp, loaded: &Loaded) -> Result<()> {
    use nornir::vector::store;

    let wh = || -> Result<nornir::warehouse::iceberg::IcebergWarehouse> {
        nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))
    };

    match op {
        VectorOp::Index(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let (sha, branch) = read_git_head(&repo_root)
                .unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
            let files = store::collect_rust_sources(&repo_root);
            if files.is_empty() {
                println!("no .rs files under {}", repo_root.display());
                return Ok(());
            }
            let embedder = load_vector_embedder()?;
            println!(
                "vectorizing {} ({} files) @ {} with {}",
                a.repo,
                files.len(),
                &sha[..sha.len().min(12)],
                vector_backend_name(),
            );
            let opts = nornir::vector::chunk::ChunkOptions::default();
            let workspace = workspace_name(loaded);
            let snap = store::index_repo(
                &wh()?,
                &store::RepoRef {
                    workspace: &workspace,
                    repo: &a.repo,
                    git_sha: &sha,
                    branch: &branch,
                    complete: true,
                },
                &files,
                &opts,
                &*embedder,
            )?;
            println!(
                "✓ snapshot {}{} occurrences, {} new vector(s) embedded",
                snap.snapshot_id, snap.occurrences, snap.new_vectors
            );
        }
        VectorOp::Search(a) => run_vector_search(loaded, &a)?,
        VectorOp::Stats => {
            let counts = store::warehouse_stats(&wh()?)?;
            println!("embeddings:          {}", counts.embeddings);
            println!("index snapshots:     {}", counts.snapshots);
            println!("manifest occurrences:{}", counts.occurrences);
        }
        VectorOp::Doctor => run_vector_doctor()?,
        VectorOp::SetupCuda(a) => run_vector_setup_cuda(&a)?,
    }
    Ok(())
}

/// `nornir vector setup-cuda` — see `cuda::setup`. embed-ort builds do the
/// copy; other builds explain what to build instead.
#[cfg(feature = "vector")]
fn run_vector_setup_cuda(a: &SetupCudaArgs) -> Result<()> {
    #[cfg(feature = "embed-ort")]
    {
        let (copied, missing) = nornir::vector::cuda::setup(&a.target)?;
        println!("✓ CUDA runtime pinned into {}", a.target.display());
        println!("  copied : {}", if copied.is_empty() { "(none)".into() } else { copied.join(", ") });
        if !missing.is_empty() {
            println!("  MISSING: {}", missing.join(", "));
            println!(
                "  → no local source found for these. Install them once (e.g. \
                 `pip download nvidia-cudnn-cu12 nvidia-cublas-cu12 nvidia-cuda-runtime-cu12` \
                 into a venv, or the CUDA toolkit) and re-run; downloading from \
                 NVIDIA's redist CDN directly is a planned follow-up. See .nornir/vector.md."
            );
        }
        println!("  verify : nornir vector doctor");
        Ok(())
    }
    #[cfg(not(feature = "embed-ort"))]
    {
        let _ = a;
        bail!(
            "setup-cuda needs an embed-ort build (`cargo install nornir --features cli,embed-ort`); \
             this build has no CUDA path to set up"
        );
    }
}


/// `nornir robot run` — parse the plan-tests-DAG, dry-run the plan or drive the
/// browser, print the summary, and append the Report to robot_history.jsonl
/// next to the scenario file (the bench-history pattern).
#[cfg(feature = "robot")]
fn run_robot(op: RobotOp, loaded: &Loaded) -> Result<()> {
    use nornir::robot;
    match op {
        RobotOp::Run(a) => {
            let scenarios = robot::parse_scenarios(&a.scenarios)?;
            let order = robot::topo_order(&scenarios)?;
            if a.dry_run {
                println!("plan-tests-DAG ({} scenario(s)):", scenarios.len());
                for &i in &order {
                    let s = &scenarios[i];
                    println!(
                        "  {} [{} {}] needs=[{}] · {} step(s)",
                        s.name, s.tier, s.area, s.needs.join(", "), s.steps.len()
                    );
                }
                return Ok(());
            }
            let base = std::env::var("BASE_URL").ok().filter(|s| !s.is_empty()).unwrap_or(a.base_url);
            let repo_root = config::Nornir::repo_dir(&loaded.workspace_root, &a.repo);
            let sha = read_git_head(&repo_root).map(|(s, _)| s).unwrap_or_else(|_| "unknown".into());
            let report = robot::run_scenarios(&scenarios, &a.webdriver, &base, &a.repo, &sha)?;
            println!(
                "robot: {} total · {} passed · {} failed · {} skipped",
                report.total, report.passed, report.failed, report.skipped
            );
            let hist = a.scenarios.parent().unwrap_or(std::path::Path::new(".")).join("robot_history.jsonl");
            robot::append_history(&hist, &report)?;
            println!("report appended to {}", hist.display());
            if report.failed > 0 {
                bail!("{} scenario(s) failed", report.failed);
            }
        }
    }
    Ok(())
}

/// `nornir vector doctor` — preflight the embedder + GPU and advise. With
/// `embed-ort` it reports the CUDA/cuDNN/driver state and runs a real test embed;
/// with `embed-tract` it notes the pure-Rust CPU path; with neither, how to build one.
#[cfg(feature = "vector")]
fn run_vector_doctor() -> Result<()> {
    #[cfg(feature = "embed-ort")]
    {
        use nornir::vector::store::Embedder;
        use std::io::Write;
        let (_ready, report) = nornir::vector::cuda::preflight();
        print!("{report}");
        print!("\n  loading model + test embed … ");
        std::io::stdout().flush().ok();
        match nornir::vector::embed_ort::OrtEmbedder::load() {
            Ok(e) => {
                let t = std::time::Instant::now();
                match e.embed(&["fn main() {}".to_string()]) {
                    Ok(v) => println!(
                        "ok — {} dims in {} ms (cuda_ready={})",
                        v.first().map(|x| x.len()).unwrap_or(0),
                        t.elapsed().as_millis(),
                        e.cuda_ready(),
                    ),
                    Err(err) => println!("embed failed: {err:#}"),
                }
            }
            Err(err) => println!("model load failed: {err:#}"),
        }
        Ok(())
    }
    #[cfg(all(feature = "embed-tract", not(feature = "embed-ort")))]
    {
        println!(
            "This build uses embed-tract (pure-Rust CPU): embeddings run on the CPU, \
             there is no CUDA/GPU path to check."
        );
        Ok(())
    }
    #[cfg(not(any(feature = "embed-ort", feature = "embed-tract")))]
    {
        println!(
            "This build has `vector` but no embedder. Rebuild with --features embed-ort \
             (GPU/CUDA → CPU fallback) or --features embed-tract (pure-Rust CPU)."
        );
        Ok(())
    }
}

#[cfg(feature = "vector")]
fn run_vector_search(loaded: &Loaded, a: &VectorSearchArgs) -> Result<()> {
    let mode = a.mode.to_ascii_lowercase();
    match mode.as_str() {
        "lexical" => {
            // BM25 over the existing tantivy index (no embedder needed).
            let idx = {
                let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(
                    &iceberg_warehouse_root(loaded),
                )?;
                let (i, _) = index::Index::open_or_restore_at(
                    &loaded.workspace_root,
                    &cache_index_dir(loaded),
                    &wh,
                    "_workspace",
                    None,
                )?;
                i
            };
            let hits = idx.search(&a.query, None, a.repo.as_deref(), a.limit)?;
            for h in &hits {
                println!(
                    "{:>6.2}  [{}/{}]  {}",
                    h.score,
                    h.corpus,
                    if h.repo.is_empty() { "-" } else { &h.repo },
                    h.path
                );
            }
        }
        "semantic" | "hybrid" => run_vector_semantic(loaded, a, mode == "hybrid")?,
        other => bail!("unknown --mode `{other}` (expected lexical|semantic|hybrid)"),
    }
    Ok(())
}

#[cfg(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort")))]
fn run_vector_semantic(loaded: &Loaded, a: &VectorSearchArgs, hybrid: bool) -> Result<()> {
    use nornir::vector::store;

    let repo = a
        .repo
        .as_deref()
        .ok_or_else(|| anyhow!("semantic/hybrid search needs --repo (embeddings are per-repo)"))?;
    let wh =
        nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
    let embedder = load_vector_embedder()?;
    let mp = embedder.profile().id();
    let q = embedder.embed(std::slice::from_ref(&a.query))?;
    let sem = store::search(&wh, repo, a.sha.as_deref(), &mp, &q[0], a.limit)?;

    if !hybrid {
        for (score, occ) in &sem {
            println!("{:>6.3}  {}:{}-{}", score, occ.file, occ.start_line, occ.end_line);
        }
        return Ok(());
    }

    // Hybrid: reciprocal-rank-fuse semantic (by file) with BM25 (by path).
    let (i, _) = index::Index::open_or_restore_at(
        &loaded.workspace_root,
        &cache_index_dir(loaded),
        &wh,
        "_workspace",
        None,
    )?;
    let lex = i.search(&a.query, None, Some(repo), a.limit.max(10))?;
    let mut score: std::collections::HashMap<String, f32> = std::collections::HashMap::new();
    const K: f32 = 60.0; // RRF constant
    for (rank, (_s, occ)) in sem.iter().enumerate() {
        *score.entry(occ.file.clone()).or_default() += 1.0 / (K + rank as f32 + 1.0);
    }
    for (rank, h) in lex.iter().enumerate() {
        *score.entry(h.path.clone()).or_default() += 1.0 / (K + rank as f32 + 1.0);
    }
    let mut ranked: Vec<(String, f32)> = score.into_iter().collect();
    ranked.sort_by(|x, y| y.1.total_cmp(&x.1));
    ranked.truncate(a.limit);
    for (path, s) in &ranked {
        println!("{:>6.4}  {}", s, path);
    }
    Ok(())
}

#[cfg(all(feature = "vector", not(any(feature = "embed-tract", feature = "embed-ort"))))]
fn run_vector_semantic(_loaded: &Loaded, _a: &VectorSearchArgs, _hybrid: bool) -> Result<()> {
    bail!(
        "semantic/hybrid search needs an embedder: rebuild nornir with \
         `--features embed-tract` (CPU) or `--features embed-ort` (GPU)"
    )
}

#[cfg(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort")))]
fn vector_backend_name() -> &'static str {
    nornir::vector::embedder_backend()
}

#[cfg(all(feature = "vector", not(any(feature = "embed-tract", feature = "embed-ort"))))]
fn vector_backend_name() -> &'static str {
    "none (no embedder feature)"
}

#[cfg(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort")))]
fn load_vector_embedder() -> Result<Box<dyn nornir::vector::store::Embedder>> {
    nornir::vector::load_embedder()
}

#[cfg(all(feature = "vector", not(any(feature = "embed-tract", feature = "embed-ort"))))]
fn load_vector_embedder() -> Result<Box<dyn nornir::vector::store::Embedder>> {
    bail!(
        "this nornir was built without an embedder: rebuild with \
         `--features embed-tract` (CPU) or `--features embed-ort` (GPU)"
    )
}

/// Resolve which on-disk index directory to snapshot/restore plus
/// the (repo_label, git_sha, branch) tuple recorded in iceberg.
/// If `repo` is None: use the workspace-wide index at
/// `<workspace>/.nornir/cache/index/`, label as `"_workspace"`, SHA
/// taken from workspace_holger HEAD.
fn resolve_index_target(
    loaded: &Loaded,
    repo: Option<&str>,
) -> Result<(PathBuf, String, String, String)> {
    // One workspace index, scoped to the appointed `[repo.*]` members and
    // living where `index build` writes it (`cache_index_dir`, honoring
    // `[storage].local_path`). `--repo` does NOT select a separate physical
    // index — there is only the workspace index; it selects which appointed
    // member's HEAD SHA *keys* the snapshot (the time-travel cursor) and the
    // label recorded in iceberg. No-repo = key by the workspace root.
    let dir = cache_index_dir(loaded);
    let (label, git_root) = match repo {
        Some(name) => {
            // Validate it's an appointed member before keying a snapshot to it.
            let _ = repo_or_err(loaded, name)?;
            (
                name.to_string(),
                config::Nornir::repo_dir(&loaded.workspace_root, name),
            )
        }
        None => (
            "_workspace".to_string(),
            loaded.workspace_root.join("workspace_holger"),
        ),
    };
    let (sha, branch) = read_git_head(&git_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
    Ok((dir, label, sha, branch))
}

fn iceberg_warehouse_root(loaded: &Loaded) -> PathBuf {
    let storage = &loaded.nornir.storage;
    if storage.local_path.is_empty() {
        loaded.workspace_root.join("workspace_holger/.nornir/warehouse")
    } else {
        loaded.workspace_root.join(&storage.local_path).join("warehouse")
    }
}

/// Tantivy index dir, honoring `[storage].local_path` so two workspaces under
/// one root don't share `.nornir/cache/index`. Empty `local_path` keeps the
/// historical `<root>/.nornir/cache/index` convention.
fn cache_index_dir(loaded: &Loaded) -> PathBuf {
    let storage = &loaded.nornir.storage;
    if storage.local_path.is_empty() {
        loaded.workspace_root.join(".nornir/cache/index")
    } else {
        loaded.workspace_root.join(&storage.local_path).join("cache/index")
    }
}

/// Best-effort workspace label for warehouse rows: the workspace-root dir name.
#[allow(dead_code)]
fn workspace_name(loaded: &Loaded) -> String {
    loaded
        .workspace_root
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("_workspace")
        .to_string()
}

fn read_git_head(repo_root: &Path) -> Result<(String, String)> {
    nornir::gitio::head_sha_and_branch(repo_root)
        .with_context(|| format!("read git HEAD in {}", repo_root.display()))
}

fn repo_or_err<'a>(loaded: &'a Loaded, name: &str) -> Result<&'a config::Repo> {
    loaded
        .nornir
        .repo
        .get(name)
        .with_context(|| format!("no [repo.{name}] in {}", loaded.config_path.display()))
}

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