nornir 0.4.34

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
//! `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.

// Multicore-friendly global allocator (fat-mode deep-scan parity with the
// server): per-thread heaps so 32-worker columnization doesn't serialize on the
// glibc arena lock. The path is still zero-alloc/zero-copy where we can get it —
// this just stops the allocs we DO make from contending.
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

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

use anyhow::{anyhow, bail, Context, Result};
use clap::{Args, CommandFactory, 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>,

    /// Skip heavy tests (#[ignore]'d container/corpus/matrix tests). Heavy tests
    /// run by DEFAULT — this opts out for a fast local smoke. Sets
    /// NORNIR_SKIP_HEAVY for the spawned `cargo test`.
    #[arg(long, global = true)]
    skip_heavy: bool,

    /// Thin-client target: connect to this nornir-server, e.g. `http://oden:7878`
    /// (a bare `host:port` gets `http://` prepended). Works on EVERY subcommand —
    /// sets `NORNIR_SERVER` for the whole invocation so the command routes to the
    /// server instead of the local warehouse. Falls back to `$NORNIR_SERVER`.
    #[arg(long, global = true)]
    server: Option<String>,

    /// Bearer token for `--server`. Falls back to `$NORNIR_SERVER_TOKEN`, then the
    /// user-readable `<home>/.nornir/token`.
    #[arg(long, global = true)]
    token: Option<String>,

    /// Target workspace by name (the `workspace_<name>` suffix, e.g. `nordisk`),
    /// for when you are NOT standing in a `workspace_<name>/` dir. Sets
    /// `NORNIR_WORKSPACE` for the whole invocation. In thin-client mode the name
    /// must be one the `--server` serves (the client lists the served names if
    /// not). Falls back to `$NORNIR_WORKSPACE`, then the cwd's `workspace_<name>`.
    #[arg(long, global = true)]
    workspace: Option<String>,

    #[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,
    },
    /// Standardized test-matrix (C6): run a repo's native `cargo test` /
    /// `cargo nextest run`, parse per-test pass/fail + duration, and persist
    /// each run to the warehouse `test_results` table. The viz Test pane reads
    /// it back as a per-repo green/red matrix.
    Test {
        #[command(subcommand)]
        op: TestOp,
    },
    /// 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),
    /// Architecture-wiring generator (EPIC ARCH): coarsen the knowledge facts
    /// (symbol_facts + call_edges + warehouse_access_edges) into ONE
    /// component/gRPC/core/table wiring graph, render it skade circuit-board
    /// style, and historize it in the warehouse keyed by git sha.
    Arch {
        #[command(subcommand)]
        op: ArchOp,
    },
    /// Skíðblaðnir airgap: pack a lake into a signed bundle, verify-on-receipt,
    /// unfold a target (Redfish/Terraform/KVM), install + start in dep order —
    /// zero network on the target. (EPIC AIRGAP; crate `nornir-airgap`.)
    Airgap {
        #[command(subcommand)]
        op: AirgapOp,
    },
    /// Idea→plan funnel (the planning DAG) — human CLI mirror of the MCP tools.
    Funnel {
        #[command(subcommand)]
        op: FunnelOp,
    },
    /// List configured repos.
    Repos,
    /// Print the resolved nornir data root (`<home>/.nornir`) for the running
    /// user — "where does nornir keep its data?". ONE rule for everyone, derived
    /// from `$HOME`; no path env-vars. The server (user `nornir`) prints
    /// `/home/nornir/.nornir`.
    Root,
    /// 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,
    },
    /// SBOM + vulnerability + license scan (CycloneDX 1.5; `cargo metadata` + OSV).
    Security {
        #[command(subcommand)]
        cmd: SecurityCmd,
    },
    /// Cross-repo dependency-graph queries (the `Mimir` surface). Mirrors the
    /// server's `Mimir` RPCs + the MCP tools: deps-of / dependents-of / affected
    /// / build-order / dep-path / external-users / svg / overview / changed.
    /// Routes to the server over gRPC when `NORNIR_SERVER` is set (warehouse-
    /// cached), else builds the graph locally (drives `cargo metadata`).
    Mimir {
        #[command(subcommand)]
        op: MimirOp,
    },
    /// Render the viz `Timeline` model as headless diagrams (static SVG /
    /// Markdown tables) — the data-only `src/viz/diagram.rs` renderers the egui app draws,
    /// reachable from the CLI. Reads a local warehouse, or the server's
    /// `Viz.Timeline` when `NORNIR_SERVER` is set.
    Diagram {
        #[command(subcommand)]
        op: DiagramOp,
    },
    /// Agent × model **bake-off MATRIX** (H5): run one task across a
    /// cross-product of **agents** (claude / kilo / a local-LLM driver) ×
    /// **models**, recording one `agent_model_runs` row per `(task, agent,
    /// model)` cell (score, wall_ms, tokens/s, cost, mcp_tool_calls) to the
    /// warehouse, then read the leaderboard / matrix back. The viz 🏆 Leaderboard
    /// pane shows the same agent×model grid with the winner highlighted.
    Bakeoff {
        #[command(subcommand)]
        op: BakeoffOp,
    },
}

#[derive(Subcommand)]
enum BakeoffOp {
    /// Run `--task` across the `--agents × --models` cross-product and persist one
    /// row per `(task, agent, model)` cell. With no `--agents`, a single
    /// local-LLM agent is used (a model-only bake-off, as before); with no
    /// `--models`, the embedding-model registry's ids. By default the models are
    /// called via ollama (`$OLLAMA_HOST` or http://localhost:11434); pass `--mock`
    /// to record canned offline rows (no LLM needed).
    Run(BakeoffRunArgs),
    /// Show a bake-off's leaderboard — `(agent, model)` cells ranked by score then
    /// tokens/s. REF is matched first as a `run_id`; if no rows carry it, as a
    /// model name (per-model history). With no REF, the most recent run.
    /// `--json` prints the raw rows; `--matrix` prints the agent × model grid.
    Leaderboard(BakeoffLeaderboardArgs),
    /// **Demo:** write a realistic mock agent × model matrix to the warehouse
    /// (3 agents × 3 models over one task, with one failed cell) so a fresh viz
    /// shows a populated 🏆 Leaderboard. Mirrors `funnel demo`; no LLM needed.
    /// Idempotent-ish: each invocation writes a fresh `run_id`.
    Demo,
}

#[derive(Args)]
struct BakeoffRunArgs {
    /// The task/prompt to pit the agent×model cells against.
    #[arg(long, visible_alias = "prompt")]
    task: String,
    /// Stable handle for the task (so two runs of the same task compare).
    #[arg(long, default_value = "default", visible_alias = "prompt-id")]
    task_id: String,
    /// Comma-separated agent ids (claude,kilo,local-llm,…). Empty ⇒ a single
    /// local-LLM agent (a model-only bake-off).
    #[arg(long, value_delimiter = ',')]
    agents: Vec<String>,
    /// Comma-separated model ids/tags. Empty ⇒ the embedding-model registry's ids.
    #[arg(long, value_delimiter = ',')]
    models: Vec<String>,
    /// ollama host base URL (else `$OLLAMA_HOST`, else http://localhost:11434).
    #[arg(long)]
    host: Option<String>,
    /// Record canned offline rows instead of calling ollama (no live LLM needed).
    #[arg(long)]
    mock: bool,
    /// Generative-LLM backend spec for the model call (EPIC #39): one of
    /// `candle:<m>` | `mistralrs:<m>` | `onnx:<m>` | `ollama:<m>` | `mock`. Each
    /// real backend is feature-gated (`gen-candle`/`gen-mistralrs`/`gen-onnx`,
    /// `gen-ollama`); an absent backend gives a clear "rebuild with --features"
    /// error. Falls back to `$NORNIR_GEN_BACKEND`, then to `--mock`/ollama. The
    /// `generator(spec)` factory drives the same model across every cell.
    #[arg(long, value_name = "SPEC")]
    gen: Option<String>,
    /// Emit the persisted rows as JSON after the run.
    #[arg(long)]
    json: bool,
    /// Print the agent × model grid (not just the flat leaderboard) after the run.
    #[arg(long)]
    matrix: bool,
    /// **Codegen judge:** path to the target crate each cell's answer is scored
    /// against (compile-and-test). Set it to score answers by build+test outcome
    /// instead of leaving the quality score at 0.0. The answer is dropped into a
    /// scratch copy of this crate, `cargo build` + the accept command run, and
    /// the row's `score` becomes the verdict (0.0 = won't compile, fraction of
    /// acceptance tests passing, 1.0 = build+all-tests green).
    #[arg(long, value_name = "PATH")]
    judge_crate: Option<std::path::PathBuf>,
    /// Where the judged answer goes inside `--judge-crate` (relative path), e.g.
    /// `src/lib.rs` — the answer is a full file body that overwrites it. Mutually
    /// exclusive with `--judge-patch`. Required with `--judge-crate` unless
    /// `--judge-patch` is set.
    #[arg(long, value_name = "REL_PATH")]
    judge_file: Option<String>,
    /// Treat each answer as a unified diff and `git apply` it to `--judge-crate`
    /// instead of overwriting a file. Mutually exclusive with `--judge-file`.
    #[arg(long)]
    judge_patch: bool,
    /// The acceptance command the judge gates on (default `cargo test`). Quote it,
    /// e.g. `--judge-cmd "cargo test --test integration"`.
    #[arg(long, value_name = "CMD")]
    judge_cmd: Option<String>,
}

#[derive(Args)]
struct BakeoffLeaderboardArgs {
    /// run_id (or model) to read. Empty ⇒ the most recent run.
    #[arg(default_value = "")]
    reference: String,
    /// Emit the raw `agent_model_runs` rows as JSON instead of the leaderboard.
    #[arg(long)]
    json: bool,
    /// Print the agent × model grid instead of the flat ranked leaderboard.
    #[arg(long)]
    matrix: bool,
}

#[derive(Subcommand)]
enum MimirOp {
    /// Repos that REPO depends on (`--transitive` for the full forward closure).
    DepsOf {
        repo: String,
        #[arg(long)]
        transitive: bool,
    },
    /// Repos that depend ON REPO — the blast radius (`--transitive` for closure).
    DependentsOf {
        repo: String,
        #[arg(long)]
        transitive: bool,
    },
    /// Changed repos + everything that transitively depends on them, in build order.
    Affected {
        /// One or more changed repos.
        repos: Vec<String>,
    },
    /// Full workspace build order (dependencies before dependents).
    BuildOrder,
    /// Shortest dependency path FROM→TO, annotated with the justifying crates.
    DepPath { from: String, to: String },
    /// Workspace repos that consume the external crate KRATE.
    ExternalUsers { krate: String },
    /// Render the cross-repo dependency graph as a static SVG flowchart.
    Svg,
    /// One-shot orientation for REPO: internal deps + dependents, build-order
    /// index, and a knowledge digest (symbol/call counts) from the warehouse.
    Overview { repo: String },
    /// Repos changed since their last recorded release (server-only; needs the
    /// warehouse's release lineage). Requires `NORNIR_SERVER`.
    Changed,
}

#[derive(Subcommand)]
enum DiagramOp {
    /// Static SVG timeline of every release node per lane.
    Timeline(DiagramArgs),
    /// Markdown table: one row per lane (repo) with its release count + latest sha.
    LaneSummary(DiagramArgs),
    /// Static SVG flowchart of the latest snapshot's cross-repo dep edges.
    Depgraph(DiagramArgs),
    /// Plain edge list (`from -> to`) of the latest snapshot.
    SnapshotEdges(DiagramArgs),
    /// Markdown gate-status matrix (release × repo).
    GateMatrix(DiagramArgs),
    /// Markdown table of published crate versions per release.
    ReleaseVersions(DiagramArgs),
    /// Markdown bench-history table (`--limit N` caps rows; newest first).
    BenchHistory {
        #[command(flatten)]
        args: DiagramArgs,
        #[arg(long)]
        limit: Option<usize>,
    },
    /// Markdown bench first-vs-last comparison table per metric.
    BenchCompare(DiagramArgs),
}

#[derive(Args)]
struct DiagramArgs {
    // Workspace comes from the global `--workspace` flag / `$NORNIR_WORKSPACE`
    // (see `env_workspace_or`); no per-op flag needed.
}

#[derive(Subcommand)]
enum SecurityCmd {
    /// Deep dependency scan: vulnerabilities (OSV.dev) + licenses; optionally
    /// write a CycloneDX 1.5 SBOM. Exit code = vulnerable-crate count (CI gate).
    Scan {
        /// Repo directory (default: current dir).
        #[arg(default_value = ".")]
        repo: std::path::PathBuf,
        /// Write the CycloneDX SBOM to this path.
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Clone/update the local rustsec advisory-db mirror for **offline (airgap)**
    /// vuln matching. `NORNIR_ADVISORY_DB` = path (default /opt/nornir/advisory-db),
    /// `NORNIR_ADVISORY_DB_URL` = source (e.g. holger; default github rustsec).
    UpdateDb,
}

#[derive(Subcommand)]
enum WorkspaceOp {
    /// List registered workspaces.
    Ls,
    /// Show one workspace's full record.
    Show { name: String },
    /// Register a workspace — **EAGER by default**: record it AND immediately
    /// fetch (clone members) + build the warehouse inline, so members + the
    /// snapshot are populated NOW (the same pipeline the poll loop runs on a
    /// change). The poll loop then handles UPDATES. Pass `--lazy` for the old
    /// record-only behaviour (defer population to the poll loop — scripted/daemon
    /// flows). (`add` is the explicit eager alias, kept for habit.)
    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>,
        /// Record-only: skip the eager fetch+build, leaving population to the
        /// poll loop. The opt-out from the default eager behaviour.
        #[arg(long)]
        lazy: bool,
    },
    /// **Eager add** — register + fetch (clone members) + build the warehouse, all
    /// inline, so the workspace is **populated now** (no waiting for a poll tick).
    /// The SAME thing the server's poll loop does on a change — so a fat user and
    /// the server do the same thing; `add` is the manual button, the poll loop is
    /// the automated one. Identical flags to `register`.
    Add {
        name: String,
        /// Local path or git URL to the workspace's `nornir-workspace.toml`.
        #[arg(long)]
        descriptor: String,
        /// Server polls members + 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,
        /// Force a FULL rebuild even when no member changed — re-runs the
        /// knowledge scan + (deep-scan, if the workspace opts in), saturating all
        /// cores. Maps to the `force` field of the Fetch RPC.
        #[arg(long)]
        force: bool,
    },
    /// **Populate now**: clone the members and return immediately — the server's
    /// poll loop then builds the warehouse (dep graph + knowledge + index + snapshot
    /// + deep-scan) in the **background** (single writer, no CAS contention). Instant
    /// clone, async build; watch progress with `nornir workspace status <name>`.
    Populate { 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>,
    /// `nornir-server` binary (default: next to this executable).
    #[arg(long)]
    server_bin: Option<PathBuf>,
}

#[derive(Args)]
struct VizArgs {
    // Workspace + thin-client target come from the global `--server`/`--token`/
    // `--workspace` flags (placed in the env by `main`); the execed `urdr-threads`
    // inherits that env.
    /// Local warehouse dir (embedded mode; ignored when `--server`/`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>,
    /// **LAW4b** — take a self-screenshot once the viz starts and write it to
    /// this path as a PNG.  The viz also appends the screenshot to the warehouse
    /// `robot_test_results` blob store so it is durable and queryable.
    /// CLI parity with the Ctrl+Shift+S keyboard shortcut and `VizCommand::Screenshot`.
    #[arg(long)]
    screenshot: Option<String>,
}

/// `nornir airgap …` — the Skíðblaðnir pipeline verbs (EPIC AIRGAP / AIRGAP9).
/// CLI parity with the `nornir-airgap` crate API + the MCP tools.
#[derive(Subcommand)]
enum AirgapOp {
    /// AIRGAP1/2 — pack a staging tree into a signed `tar.zst` bundle + a sidecar
    /// manifest (per-entry SHA-256), and a `VERSION` file beside it.
    Pack(AirgapPackArgs),
    /// AIRGAP3 — verify a received bundle against its manifest (zero network).
    Fetch(AirgapBundleArgs),
    /// AIRGAP7 — show the unfold backend's provisioning plan for a target
    /// (kvm qemu argv | terraform HCL | redfish reset body).
    Unfold(AirgapUnfoldArgs),
    /// AIRGAP6 — install one component from a bundle (root-only on Linux).
    Install(AirgapInstallArgs),
    /// AIRGAP8 — dependency-ordered start waves for a lake spec; emits
    /// `airgap_events` to the warehouse.
    Start(AirgapStartArgs),
    /// Read back the `airgap_events` DAG (from the warehouse JSONL sink).
    Events(AirgapEventsArgs),
}

#[derive(Args)]
struct AirgapPackArgs {
    /// Staging tree to pack (artifacts laid out as they appear in the bundle).
    staging: PathBuf,
    /// Output bundle path (`*.tar.zst`).
    #[arg(long)]
    out: PathBuf,
    /// Airgap generation stamp (default: today, YYYYMMDD).
    #[arg(long)]
    version: Option<String>,
}

#[derive(Args)]
struct AirgapBundleArgs {
    /// The received bundle (its sidecar `<bundle>.manifest.json` must be present).
    bundle: PathBuf,
    /// Optional out-of-band whole-file SHA-256 to also confirm.
    #[arg(long)]
    sha256: Option<String>,
}

#[derive(Args)]
struct AirgapUnfoldArgs {
    /// Backend: `kvm` | `terraform` | `redfish`.
    backend: String,
    /// Target name / workspace / BMC url (backend-specific).
    target: String,
    /// KVM only: disk image to boot.
    #[arg(long)]
    disk: Option<String>,
}

#[derive(Args)]
struct AirgapInstallArgs {
    /// The verified bundle to install from.
    bundle: PathBuf,
    /// Component manifest (`manifests/<name>.json`) path INSIDE the bundle, or a
    /// local `ComponentSpec` JSON file.
    #[arg(long)]
    spec: PathBuf,
    /// Software root (version-dated dirs created under here).
    #[arg(long, default_value = "/opt/lake")]
    software_dir: PathBuf,
    /// Fast-moving data root.
    #[arg(long, default_value = "/var/lib")]
    data_dir: PathBuf,
}

#[derive(Args)]
struct AirgapStartArgs {
    /// Lake spec JSON (`LakeSpec`: version + products + pki).
    spec: PathBuf,
    /// Override the warehouse root the `airgap_events.jsonl` sink writes under
    /// (default: the resolved workspace warehouse root).
    #[arg(long)]
    warehouse: Option<PathBuf>,
}

#[derive(Args)]
struct AirgapEventsArgs {
    /// Warehouse root holding `airgap_events.jsonl` (default: resolved root).
    #[arg(long)]
    warehouse: 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 (`/home/nornir` — its `.nornir` data
    /// root + SSH key) and the installed binaries unless `--purge`.
    Uninstall(UninstallArgs),
}

#[derive(Args)]
struct UninstallArgs {
    /// Also delete the data home (`/home/nornir`: the `.nornir` data root —
    /// warehouses, registry, funnel — and the 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>,
    /// Run the self-sync poll loop (monitored role). DEPRECATED as a path: the
    /// registry root is home-derived (`<home>/.nornir/workspaces`) and `--root`'s
    /// value is ignored — set the service user's `$HOME` to relocate. Passing it
    /// (or any `--monitor`) just turns the monitored role on.
    #[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>,
    },
    /// FI1 — paste an **idea** (feature/krav/prompt) into the funnel. Alias of
    /// `submit` with `item_kind=idea`. Text from the arg, `--file`, or stdin.
    ///   `nornir funnel idea "<idea>"` · `--file krav.md` · `cat p | nornir funnel idea`
    Idea {
        /// Inline idea text. Omit when using `--file` or piping via stdin.
        text: Option<String>,
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        #[arg(long)]
        source: Option<String>,
    },
    /// FI1 — paste an **error report** into the funnel (a first-class funnel
    /// item, kind `error`, triageable to a plan like any idea). Text from the
    /// arg, `--file`, or stdin (the natural way to ingest a captured report):
    ///   `nornir funnel error - < report.txt` · `nornir funnel error "<msg>"`
    Error {
        /// Inline error text, or `-` to read the report from stdin. Omit when
        /// using `--file` or piping (stdin is the default with no arg).
        text: Option<String>,
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        #[arg(long)]
        source: Option<String>,
    },
    /// FI-extension — paste a **test-idea** (a desired/missing test) into the
    /// funnel (a first-class funnel item, kind `test`, planned into `test:write`
    /// node(s) on the affected component(s) like any idea). Text from the arg,
    /// `--file`, or stdin:
    ///   `nornir funnel test "cover the retry path in util"` · `--file t.md`
    Test {
        /// Inline test-idea text, or `-` to read from stdin. Omit when using
        /// `--file` or piping.
        text: Option<String>,
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        #[arg(long)]
        source: Option<String>,
    },
    /// **Plan without big AI** — auto-derive a plan for IDEA_ID from the
    /// component dependency graph. Classifies the item text → component(s) (local
    /// LLM → embedder → pick-list), computes the topological affected set (blast
    /// radius in build order), and creates a plan with one node per affected
    /// component. Prints the proposal + affected set + new plan id.
    ///   `nornir funnel plan-from i-003` · `--component util` (skip classify)
    #[command(name = "plan-from")]
    PlanFrom {
        /// The funnel item id (idea / error / test) to plan.
        idea_id: String,
        /// Force the touched component(s), skipping classification (repeatable).
        /// Use this to act on the pick-list when no LLM/embedder is confident.
        #[arg(long = "component")]
        components: Vec<String>,
        /// Only classify + print the proposal & affected set; do NOT create the
        /// plan (a dry-run preview).
        #[arg(long)]
        dry_run: bool,
    },
    /// FI2 — browse submitted errors/ideas newest-first (the intake history),
    /// optionally filtered by kind/status. JSON unless `--table`.
    ///   `nornir funnel history` · `--kind error` · `--status untriaged --table`
    History {
        /// Filter by kind: `idea` | `error` | `test` (default: all).
        #[arg(long)]
        kind: Option<String>,
        /// Filter by derived status: untriaged | accepted | dropped | planned.
        #[arg(long)]
        status: Option<String>,
        /// Max items (newest-first). 0 = all.
        #[arg(long, default_value_t = 0)]
        limit: usize,
        /// Render a compact human table instead of JSON.
        #[arg(long)]
        table: bool,
    },
    /// 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,
    /// **Decompose (EPIC #45):** break a task into ≤N atomic, testable subtasks
    /// (RAG-anchored to real files/fns via the code index), then run each through
    /// a local-LLM generate → CodegenJudge oracle → retry loop and print the
    /// subtask DAG + per-subtask verdicts. 100% local — `--gen mock` (default)
    /// needs no model and no network; the compiler is the accept/reject oracle.
    ///
    ///   `nornir funnel decompose "make add() correct" --fixture`
    ///   `nornir funnel decompose i-003 --gen candle:qwen2-0.5b --store`
    Decompose(DecomposeArgs),
    /// **Demo:** materialise `--size N` fake git repos near the git root (each a
    /// `Cargo.toml` + `src/lib.rs` wired into a layered path-dep graph) AND
    /// inject the matching funnel DAG into the warehouse. Idempotent — a rerun
    /// detects the existing `funnel:demo` idea and skips the warehouse half.
    /// A manifest `git/.nornir-funnel-demo.json` records exactly what was made
    /// so `nuke` deletes only demo paths.
    Demo {
        /// Number of fake repos to create.
        #[arg(long, default_value_t = 1)]
        size: usize,
    },
    /// **Nuke (disk-only):** delete the fake repos the demo created on disk,
    /// reading the manifest so only demo paths are removed (never a heuristic
    /// `rm`). The warehouse funnel data is PRESERVED — the plan still shows in
    /// `funnel show` / the viz Funnel tab. Refuses without `--yes`.
    Nuke {
        /// Confirm the disk deletion (required). Without it, prints what it
        /// would delete and exits.
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Args)]
struct DecomposeArgs {
    /// The task: either a funnel item id (`i-003`/`p-…` — its text is used) or a
    /// raw task string. With `--store`, an id is required (the subtasks hang
    /// under it); a raw string is fine for a stateless `--fixture` dry-run.
    task: String,
    /// Run the OFFLINE simulation against a self-contained tiny fixture crate
    /// (created in a temp dir, no repo touched): the code index IS the fixture,
    /// the judge builds+tests the fixture. The fully model-free, network-free
    /// demo. Mutually exclusive with `--repo`.
    #[arg(long)]
    fixture: bool,
    /// Judge against this on-disk crate dir (RAG over its scanned symbols, the
    /// CodegenJudge builds+tests a scratch copy). Defaults to the fixture when
    /// neither this nor `--fixture` is given on a dry run.
    #[arg(long)]
    repo: Option<String>,
    /// Generator spec (`mock` | `candle:<m>` | `mistralrs:<m>` | `onnx:<m>` |
    /// `ollama:<m>`). Default `mock` — offline, no model. Falls back to
    /// `$NORNIR_GEN_BACKEND`.
    #[arg(long)]
    gen: Option<String>,
    /// Max atomic subtasks (hard cap 20).
    #[arg(long, default_value_t = 8)]
    max_subtasks: usize,
    /// Bounded generate→judge retry rounds per subtask.
    #[arg(long, default_value_t = 3)]
    rounds: usize,
    /// Top-k RAG anchors retrieved for the task.
    #[arg(long, default_value_t = 5)]
    top_k: usize,
    /// Persist the subtasks as child funnel DAG nodes under the task item +
    /// write the per-subtask verdicts back (requires `task` to be an item id).
    #[arg(long)]
    store: bool,
    /// Emit the whole report as JSON (`state_json`) instead of the DAG view.
    #[arg(long)]
    json: bool,
}

#[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 TestOp {
    /// Run <repo>'s **multi-aspect** matrix (EPIC L) and append every row to
    /// `test_results` under one run id. Default aspects: build,unit,doctest,
    /// clippy,fmt,audit (slow/optional ones — coverage,feature-powerset,msrv,
    /// bench-smoke,examples — only with `--aspects`). The unit aspect wraps the
    /// repo's native `cargo nextest run` / `cargo test`; a missing tool
    /// (clippy/audit/…) is a neutral `skip`, never a hard fail. The stall
    /// watchdog (`NORNIR_TEST_STALL_SECS`, default 120) records a red `stalled`
    /// row if the test subprocess goes silent.
    Run(TestRunArgs),
    /// Run the FULL aspect matrix across EVERY repo in nornir.toml, persist every
    /// row, print a per-repo×aspect grid, and exit red if any red.
    /// `--aspects build,unit,clippy,…` overrides the default set.
    All(TestAllArgs),
    /// List the BUILD-FREE test matrix for <repo>: every discovered `#[test]`
    /// (from the syn knowledge scan — NO `cargo build`) with its tri-state verdict
    /// `ok | fail | X` (X = discovered but not run) and a `heavy` tag for
    /// `#[ignore]`'d tests. This is the CLI twin of the viz 🧪 Test pane — the
    /// matrix is the `test_inventory` ⟕ `test_results` join. `--json` prints the
    /// raw rows; `--heavy-only` shows just the heavy tests; `--not-run` shows just
    /// the X (not-run) tests.
    List(TestListArgs),
    /// Show <repo>'s recorded test history — per-run green/red counts (newest
    /// first) with red cases listed. `--json` prints the raw rows; `--limit N`
    /// caps the number of runs shown (0 = all).
    History(TestHistoryArgs),
    /// autonom COMPLETENESS GATE (n-005): discover the testable surface
    /// (viz tabs × {thin,fat}, CLI subcommands, MCP tools, and the unreached-fn
    /// set from `symbol_facts − test-reachable(call_edges)`), difference it
    /// against the covered set + the checked-in `.nornir/autonom-allow.toml`,
    /// persist the verdict to `surface_coverage`, and FAIL (exit 1) if any
    /// surface is uncovered+un-allowlisted OR an allowlist entry is stale.
    /// Green ⟺ every surface is wired. `--seed-allowlist` rewrites the allowlist
    /// with every currently-uncovered surface (green now, burn down by deleting).
    Coverage(TestCoverageArgs),
}

#[derive(Args)]
struct TestCoverageArgs {
    /// Repo whose knowledge map (symbol_facts/call_edges) drives the function
    /// surface. Defaults to the workspace's primary repo (the workspace name).
    #[arg(long)]
    repo: Option<String>,
    /// Seed `.nornir/autonom-allow.toml` with every currently-uncovered surface
    /// node (green now; burn down by deleting entries as tests land). Does NOT
    /// fail the gate — it WRITES the allowlist.
    #[arg(long)]
    seed_allowlist: bool,
    /// Emit the persisted per-node coverage rows as JSON instead of the summary.
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct TestRunArgs {
    /// Repo to run the matrix for (must be in nornir.toml).
    repo: String,
    /// Comma-separated aspect list (e.g. `build,unit,clippy,coverage`). Empty =
    /// the default set (build,unit,doctest,clippy,fmt,audit). Aspects:
    /// build · unit · doctest · clippy · fmt · audit · bench-smoke · coverage ·
    /// feature-powerset · msrv · examples.
    #[arg(long)]
    aspects: Option<String>,
}

#[derive(Args)]
struct TestAllArgs {
    /// Comma-separated aspect list applied to every repo. Empty = the default set.
    #[arg(long)]
    aspects: Option<String>,
}

#[derive(Args)]
struct TestListArgs {
    /// Repo whose discovered tests to list (must be in nornir.toml). Omit to list
    /// every repo configured in nornir.toml.
    repo: Option<String>,
    /// Emit the raw matrix rows as JSON instead of the human table.
    #[arg(long)]
    json: bool,
    /// Show only the heavy (`#[ignore]`'d) tests.
    #[arg(long)]
    heavy_only: bool,
    /// Show only the X (not-run) tests.
    #[arg(long)]
    not_run: bool,
}

#[derive(Args)]
struct TestHistoryArgs {
    /// Repo (or run id) to read. Matched first as a repo name; if no rows carry
    /// it, treated as an exact run_id.
    repo: String,
    /// Emit the raw `test_results` rows as JSON instead of the matrix view.
    #[arg(long)]
    json: bool,
    /// Show only the N most recent runs (0 = all).
    #[arg(long, default_value_t = 0)]
    limit: usize,
}

#[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,
        /// Emit JSON instead of the human-readable trace.
        /// (Restrict to a workspace with the global `--workspace`; default = all.)
        #[arg(long)]
        json: bool,
    },
    /// Print the recorded release-op DAG (the `release_events` table) for a
    /// repo or a specific run id. <selector> is matched first as an exact
    /// run_id; if no events carry it, it's treated as a repo name. `--json`
    /// emits the raw rows; otherwise a human topological view (per-run
    /// timeline + `depends_on` edges) is printed. Pure warehouse scan, no
    /// rebuild — lock-tolerant so it coexists with a live server.
    Events {
        /// A run_id (groups one release run) or a repo name (all its runs).
        selector: String,
        /// Emit the raw event rows as JSON instead of the topo view.
        #[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 for the holger registry; falls back to $HOLGER_TOKEN if
        /// omitted. (Named `--holger-token` to leave the global `--token` for the
        /// nornir-server bearer.)
        #[arg(long = "holger-token")]
        holger_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 ArchOp {
    /// Generate the wiring graph for a repo (scans symbols + call edges +
    /// warehouse-access facts fresh, builds the coarsened graph, renders the
    /// SVG, and historizes it in the warehouse keyed by git sha).
    Generate(ArchGenerateArgs),
    /// Print the rendered wiring SVG to stdout (or write it with `--out`).
    Svg(ArchGenerateArgs),
    /// Trace one entrypoint (UI pane / gRPC verb / module ident) to the focused
    /// sub-board of everything it reaches downstream (the visual twin of
    /// `knowledge_call_path`). Renders the SVG to stdout or `--out`.
    Trace(ArchTraceArgs),
    /// List historized wiring snapshots for a repo (newest first).
    History(RepoArg),
}

#[derive(Args)]
struct ArchTraceArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// The entrypoint to trace from — matched against node labels/ids by
    /// case-insensitive substring (`TestTab`, `Viz.Timeline`, a module bucket).
    entrypoint: String,
    /// Write the rendered SVG to this path instead of stdout.
    #[arg(long)]
    out: Option<PathBuf>,
}

#[derive(Args)]
struct ArchGenerateArgs {
    #[command(flatten)]
    repo: RepoArg,
    /// Also write the rendered SVG to this path.
    #[arg(long)]
    out: Option<PathBuf>,
    /// Build the graph but skip historizing it into the warehouse.
    #[arg(long)]
    skip_snapshot: 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 (static SVG).
    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 comes from the global
    // `--workspace` / `$NORNIR_WORKSPACE` (default `workspace_holger`).
}

#[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,
    /// Benchmark the CPU cosine kernels (G2): scalar vs runtime SIMD vs int8
    /// VNNI on a synthetic corpus. Prints per-kernel timing, throughput, the
    /// SIMD/int8 speedup over scalar, and the int8 quantization error.
    Bench(VectorBenchArgs),
    /// 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 VectorBenchArgs {
    /// Number of vectors in the synthetic corpus.
    #[arg(long, default_value_t = 100_000)]
    n: usize,
    /// Vector dimensionality (default = jina-v2 768).
    #[arg(long, default_value_t = 768)]
    dim: usize,
    /// Timed iterations to average over.
    #[arg(long, default_value_t = 20)]
    iters: usize,
}

#[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 comes from the global
    // `--workspace` / `$NORNIR_WORKSPACE` (default "workspace_holger" — matches
    // the existing iceberg rows).
    /// 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();
    // `--skip-heavy` → the env the release/test pipeline reads (heavy is default-on).
    if cli.skip_heavy {
        // SAFETY: single-threaded, before any worker spawns.
        unsafe { std::env::set_var("NORNIR_SKIP_HEAVY", "1") };
    }
    // Global thin-client flags → env, so every `server_target()` / `client_workspace()`
    // path lights up uniformly for ALL subcommands (not just viz/serve). A bare
    // `host:port` gets `http://`; the token falls back to env then the user-readable
    // `<home>/.nornir/token`. SAFETY: single-threaded, before any worker spawns.
    if let Some(s) = &cli.server {
        let url = if s.starts_with("http://") || s.starts_with("https://") {
            s.clone()
        } else {
            format!("http://{s}")
        };
        unsafe { std::env::set_var("NORNIR_SERVER", &url) };
    }
    if let Some(t) = &cli.token {
        unsafe { std::env::set_var("NORNIR_SERVER_TOKEN", t) };
    } else if cli.server.is_some() && std::env::var_os("NORNIR_SERVER_TOKEN").is_none() {
        if let Ok(tok) = std::fs::read_to_string(nornir::config::nornir_home().join("token")) {
            let tok = tok.trim();
            if !tok.is_empty() {
                unsafe { std::env::set_var("NORNIR_SERVER_TOKEN", tok) };
            }
        }
    }
    if let Some(w) = &cli.workspace {
        unsafe { std::env::set_var("NORNIR_WORKSPACE", w) };
    }
    // 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, cli.config.as_deref()),
        Cmd::Install { op } => return run_install(op),
        Cmd::Key { op } => return run_key(op),
        Cmd::Workspace { op } => return run_workspace(op),
        Cmd::Security { cmd } => return run_security(cmd),
        // Pure environment query — no config discovery needed.
        Cmd::Root => {
            println!("{}", nornir::config::nornir_home().display());
            return Ok(());
        }
        _ => {}
    }
    // Thin-client commands target a workspace. If none is resolvable (no
    // --workspace, no $NORNIR_WORKSPACE, not in a workspace_<name>/ dir), pick one
    // interactively (TTY) or error with the served list — never send a bogus name.
    #[cfg(any(feature = "mcp", feature = "server"))]
    {
        if let Some(server) = server_target() {
            let have_ws = std::env::var("NORNIR_WORKSPACE").ok().filter(|s| !s.is_empty()).is_some()
                || std::env::current_dir().ok().and_then(|d| cwd_workspace_name(&d)).is_some();
            if !have_ws {
                let chosen = pick_workspace_or_explain(&server)?;
                // SAFETY: single-threaded, before any worker spawns / first client call.
                unsafe { std::env::set_var("NORNIR_WORKSPACE", &chosen) };
            }
        }
    }
    let loaded = load_config(cli.config.as_deref())?;
    match cli.cmd {
        Cmd::Serve(_)
        | Cmd::Viz(_)
        | Cmd::Install { .. }
        | Cmd::Key { .. }
        | Cmd::Workspace { .. }
        | Cmd::Security { .. }
        | Cmd::Root => {
            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::Test { op } => run_test(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::Arch { op } => run_arch(op, &loaded)?,
        Cmd::Airgap { op } => run_airgap(op, &loaded)?,
        Cmd::Funnel { op } => run_funnel(op, &loaded)?,
        Cmd::Mimir { op } => run_mimir(op, &loaded)?,
        Cmd::Diagram { op } => run_diagram(op, &loaded)?,
        Cmd::Bakeoff { op } => run_bakeoff_cmd(op, &loaded)?,
    }
    Ok(())
}

/// `nornir bakeoff …` (H5) — run a prompt across a set of local models and
/// persist one `agent_model_runs` row per model, then read the leaderboard
/// back. The model-call layer is mockable (`--mock`) so this never needs a
/// running LLM; the viz Leaderboard pane ranks the same rows.
fn run_bakeoff_cmd(op: BakeoffOp, loaded: &Loaded) -> Result<()> {
    use nornir::warehouse::agent_model_runs::{
        default_agents, default_models, demo_matrix_rows, new_run_id,
        query_agent_model_runs, render_leaderboard, render_matrix, rows_to_json,
        run_bakeoff_matrix, score_rows_with_judge, short_run, BakeoffSelector, MockCaller,
        ModelAnswer, ModelCaller, OllamaCaller,
    };
    use nornir::warehouse::codegen_judge::{CodegenJudge, CodegenSpec};
    use nornir::warehouse::iceberg::IcebergWarehouse;

    match op {
        BakeoffOp::Run(a) => {
            let agents = if a.agents.is_empty() { default_agents() } else { a.agents.clone() };
            let models = if a.models.is_empty() { default_models() } else { a.models.clone() };
            if models.is_empty() {
                bail!("no models to run — pass --models a,b,c or configure the registry");
            }
            let run_id = new_run_id();
            let ts_micros = chrono::Utc::now().timestamp_micros();

            // The bake-off backend, chosen in priority order:
            //   1. `--gen <spec>` / `$NORNIR_GEN_BACKEND` → the EPIC #39
            //      generative-LLM factory (candle / mistralrs / onnx / ollama /
            //      mock), driving the SAME selected model across every cell.
            //   2. `--mock` → a canned offline matrix (deterministic economics).
            //   3. otherwise → the prior-art ollama HTTP caller.
            let gen_spec = a.gen.clone().or_else(nornir::warehouse::generator::spec_from_env);
            let caller: Box<dyn ModelCaller> = if let Some(spec) = gen_spec {
                use nornir::warehouse::generator::{generator, BoxGeneratorCaller};
                let g = generator(&spec)?;
                println!(
                    "▶ generator backend `{}` (available: {})",
                    g.id(),
                    g.available()
                );
                Box::new(BoxGeneratorCaller::new(g))
            } else if a.mock {
                let mut mock = MockCaller::new();
                for (ai, agent) in agents.iter().enumerate() {
                    let hosted = agent != "local-llm" && agent != "-" && agent != "local";
                    for (mi, m) in models.iter().enumerate() {
                        let tout = 16 + (mi as i64) + (ai as i64) * 2;
                        let lat = 100.0 + (mi as f64) * 50.0 + (ai as f64) * 30.0;
                        mock = mock.with_cell(
                            agent.clone(),
                            m.clone(),
                            ModelAnswer {
                                output: format!("[mock answer from {agent}/{m}]"),
                                latency_ms: lat,
                                tokens_in: 12,
                                tokens_out: tout,
                                tokens_per_s: tout as f64 / (lat / 1000.0),
                                score: (1.0 - (mi as f64) * 0.1 + if hosted { 0.05 } else { 0.0 })
                                    .min(1.0),
                                cost_usd: if hosted { 0.01 * (mi as f64 + 1.0) } else { 0.0 },
                                mcp_tool_calls: if hosted { 3 + mi as i64 } else { 0 },
                            },
                        );
                    }
                }
                Box::new(mock)
            } else {
                Box::new(OllamaCaller::new(a.host.clone()))
            };

            println!(
                "▶ bake-off `{}` matrix: {} agent(s) [{}] × {} model(s) [{}] = {} cells",
                a.task_id,
                agents.len(),
                agents.join(", "),
                models.len(),
                models.join(", "),
                agents.len() * models.len(),
            );
            let mut rows = run_bakeoff_matrix(
                caller.as_ref(),
                &run_id,
                ts_micros,
                &a.task_id,
                &a.task,
                &agents,
                &models,
            );

            // Optional compile-and-test scoring: if a codegen spec was given,
            // score each cell's answer by building+testing it, replacing the
            // (otherwise 0.0) quality score with the verdict.
            if let Some(crate_dir) = a.judge_crate.clone() {
                if a.judge_patch && a.judge_file.is_some() {
                    bail!("--judge-patch and --judge-file are mutually exclusive");
                }
                let spec = if a.judge_patch {
                    CodegenSpec::apply_patch(crate_dir)
                } else {
                    let rel = a.judge_file.clone().ok_or_else(|| {
                        anyhow::anyhow!(
                            "--judge-crate needs --judge-file <rel-path> (or --judge-patch)"
                        )
                    })?;
                    CodegenSpec::write_file(crate_dir, rel)
                };
                let spec = match a.judge_cmd.clone() {
                    Some(cmd) => spec.with_accept_cmd(
                        cmd.split_whitespace().map(|s| s.to_string()).collect(),
                    ),
                    None => spec,
                };
                println!(
                    "⚖ judging {} cell(s) by compile-and-test against `{}` ({})",
                    rows.iter().filter(|r| r.ok).count(),
                    spec.crate_dir.display(),
                    spec.accept_cmd.join(" "),
                );
                let judge = CodegenJudge::new(spec);
                let reports = score_rows_with_judge(&mut rows, &judge);
                for rep in &reports {
                    let detail = match (&rep.verdict, &rep.error) {
                        (Some(v), _) => v.message.clone(),
                        (None, Some(e)) => format!("judge error: {e}"),
                        (None, None) => String::new(),
                    };
                    println!("  {}/{}: score {:.3}{}", rep.agent, rep.model, rep.score, detail);
                }
            }

            persist_bakeoff(&loaded, &rows)?;

            println!("✓ recorded run {} ({} rows)\n", short_run(&run_id), rows.len());
            if a.json {
                println!("{}", rows_to_json(&rows));
            } else if a.matrix {
                print!("{}", render_matrix(&rows));
            } else {
                print!("{}", render_leaderboard(&rows));
            }
        }
        BakeoffOp::Demo => {
            let run_id = new_run_id();
            let ts_micros = chrono::Utc::now().timestamp_micros();
            let rows = demo_matrix_rows(&run_id, ts_micros);
            persist_bakeoff(&loaded, &rows)?;
            println!(
                "✓ seeded demo bake-off matrix: run {} ({} cells, 3 agents × 3 models)\n",
                short_run(&run_id),
                rows.len()
            );
            print!("{}", render_matrix(&rows));
            println!(
                "\nopen the 🏆 Leaderboard tab in `nornir viz`, or: nornir bakeoff leaderboard --matrix"
            );
        }
        BakeoffOp::Leaderboard(a) => {
            let warehouse_root = loaded.warehouse_root();
            // Read-only + lock-tolerant (coexist with a live server), like
            // `release events` / `test history`.
            let wh = IcebergWarehouse::open_read_only(&warehouse_root).with_context(|| {
                format!("open iceberg warehouse at {}", warehouse_root.display())
            })?;

            let rows = if a.reference.is_empty() {
                // Most recent run: read everything, keep the newest run_id.
                let all = wh.block_on(query_agent_model_runs(&wh, &BakeoffSelector::All))?;
                match all.iter().max_by_key(|r| r.ts_micros).map(|r| r.run_id.clone()) {
                    Some(run_id) => all.into_iter().filter(|r| r.run_id == run_id).collect(),
                    None => Vec::new(),
                }
            } else {
                // Try as a run_id first; if empty, treat as a model name.
                let by_run = wh.block_on(query_agent_model_runs(
                    &wh,
                    &BakeoffSelector::Run(a.reference.clone()),
                ))?;
                if by_run.is_empty() {
                    wh.block_on(query_agent_model_runs(
                        &wh,
                        &BakeoffSelector::Model(a.reference.clone()),
                    ))?
                } else {
                    by_run
                }
            };

            if a.json {
                println!("{}", rows_to_json(&rows));
            } else if rows.is_empty() {
                println!("no bake-off runs recorded yet — run `nornir bakeoff run --task …` or `nornir bakeoff demo` first");
            } else if a.matrix {
                print!("{}", render_matrix(&rows));
            } else {
                print!("{}", render_leaderboard(&rows));
            }
        }
    }
    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, ItemKind, NodeId, NodeStatus, PlanId, PlanStatus,
    };

    // Resolve the funnel root through the SAME precedence the server/MCP use
    // (`Store::resolve_root`): explicit override > config `[storage].local_path`
    // > the home-derived `<home>/.nornir/funnel`. The home rule is the E4 fix —
    // the CLI (as you) and the server (as the `nornir` user) each resolve their
    // own home, so a CLI-created funnel appears in the viz Funnel tab whenever
    // both run as the same user.
    let root = funnel_root(loaded);
    // `Show` is a pure read: open lock-tolerantly so it never deadlocks against
    // a running `nornir-server` that holds the exclusive `catalog.redb` lock on
    // the same funnel root (it falls back to a copied-aside snapshot). Every
    // mutating verb needs the real exclusive lock, so it opens read-write; if
    // the server holds the lock, that surfaces as a clear lock error rather than
    // silently writing to the wrong place.
    // `Demo` opens its own store inside `run_demo` (it must materialise repos
    // first, then inject), and `Nuke` is disk-only (never opens the store), so
    // handle both before the shared open — opening the exclusive lock here would
    // collide with `run_demo`'s own open.
    match &op {
        FunnelOp::Demo { size } => {
            let manifest = funnel::demo::run_demo(&root, *size)?;
            println!(
                "funnel demo: created {} fake repo(s) under {}",
                manifest.repos.len(),
                manifest
                    .container
                    .as_ref()
                    .map(|c| c.display().to_string())
                    .unwrap_or_default(),
            );
            for r in &manifest.repos {
                println!("  {}", r.display());
            }
            println!("warehouse funnel DAG injected at {}", root.display());
            return Ok(());
        }
        FunnelOp::Nuke { yes } => {
            let plan = funnel::demo::nuke_plan(&root);
            let Some(manifest) = plan else {
                println!("funnel nuke: no demo manifest found — nothing to delete");
                return Ok(());
            };
            if !*yes {
                println!("funnel nuke would delete (disk only — warehouse funnel data preserved):");
                for r in &manifest.repos {
                    println!("  {}", r.display());
                }
                if let Some(c) = &manifest.container {
                    println!("  {} (container, if empty)", c.display());
                }
                println!("re-run with --yes to confirm");
                return Ok(());
            }
            let removed = funnel::demo::nuke_disk(&root)?;
            println!("funnel nuke: removed {} fake repo(s) on disk", removed.len());
            for r in &removed {
                println!("  {}", r.display());
            }
            println!("warehouse funnel data preserved (plan still visible in `funnel show`)");
            return Ok(());
        }
        FunnelOp::Decompose(args) => {
            run_funnel_decompose(&root, args)?;
            return Ok(());
        }
        _ => {}
    }

    let mut store = if matches!(op, FunnelOp::Show | FunnelOp::History { .. }) {
        funnel::Store::open_read_only(&root)?
    } else {
        funnel::Store::open(&root)?
    };
    match op {
        FunnelOp::Submit { text, file, source } => {
            funnel_intake(&mut store, ItemKind::Idea, text, file, source)?;
        }
        // FI1 — `idea`/`error` are intake aliases differing only in item_kind.
        FunnelOp::Idea { text, file, source } => {
            funnel_intake(&mut store, ItemKind::Idea, text, file, source)?;
        }
        FunnelOp::Error { text, file, source } => {
            funnel_intake(&mut store, ItemKind::Error, text, file, source)?;
        }
        FunnelOp::Test { text, file, source } => {
            funnel_intake(&mut store, ItemKind::Test, text, file, source)?;
        }
        FunnelOp::PlanFrom { idea_id, components, dry_run } => {
            run_funnel_plan_from(&mut store, loaded, &idea_id, components, dry_run)?;
        }
        FunnelOp::History { kind, status, limit, table } => {
            let kind = kind.as_deref().map(ItemKind::parse);
            let status = status.as_deref().and_then(funnel::HistoryStatus::parse);
            let mut items = funnel::history(&store.funnel, kind, status);
            if limit > 0 {
                items.truncate(limit);
            }
            if table {
                if items.is_empty() {
                    println!("(no funnel items)");
                } else {
                    println!("  {:<7} {:<6} {:<10} {:<12} text", "id", "kind", "status", "plans");
                    for it in &items {
                        let plans = if it.plan_ids.is_empty() {
                            "-".to_string()
                        } else {
                            it.plan_ids.join(",")
                        };
                        println!(
                            "  {:<7} {:<6} {:<10} {:<12} {}",
                            it.id,
                            it.item_kind.as_str(),
                            it.status.as_str(),
                            plans,
                            truncate_one_line(&it.text, 60),
                        );
                    }
                }
            } else {
                println!("{}", funnel::history_to_json(&items));
            }
        }
        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);
                }
            }
        }
        // Handled (and returned) before the shared store open above.
        FunnelOp::Demo { .. } | FunnelOp::Nuke { .. } | FunnelOp::Decompose(_) => unreachable!(),
    }
    Ok(())
}

/// FI1 shared intake: read the item text (precedence `--file` → positional arg
/// (`-` = stdin) → stdin pipe), then record one `IdeaSubmitted` event carrying
/// `item_kind` (idea | error). Prints the new item id. The single path behind
/// `funnel submit`/`funnel idea`/`funnel error`, so all three agree on parsing
/// and only differ in the kind they stamp.
fn funnel_intake(
    store: &mut nornir::funnel::Store,
    item_kind: nornir::funnel::ItemKind,
    text: Option<String>,
    file: Option<std::path::PathBuf>,
    source: Option<String>,
) -> Result<()> {
    use nornir::funnel::{Event, IdeaId};
    let text = match (file, text) {
        (Some(path), _) => std::fs::read_to_string(&path)
            .with_context(|| format!("read intake file {}", path.display()))?,
        // `-` is the conventional "read stdin" sentinel (`funnel error - < f`).
        (None, Some(t)) if t != "-" => t,
        _ => {
            use std::io::Read;
            let mut buf = String::new();
            std::io::stdin().read_to_string(&mut buf).context("read intake text from stdin")?;
            buf
        }
    };
    let text = text.trim().to_string();
    if text.is_empty() {
        anyhow::bail!(
            "empty {} text — pass it as an arg, --file <path>, or via stdin",
            item_kind.as_str()
        );
    }
    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(),
        item_kind,
        ts: chrono::Utc::now(),
    })?;
    println!("{}", id.as_str());
    Ok(())
}

/// `nornir funnel plan-from <idea-id>` — **plan without big AI.** Build the
/// component dep graph, classify the item text → component(s) (LLM → embedder →
/// pick-list), compute the topological affected set, and (unless `--dry-run`)
/// weave a plan with one node per affected component. CLI parity with the viz
/// Funnel tab's "generate plan" action.
fn run_funnel_plan_from(
    store: &mut nornir::funnel::Store,
    loaded: &Loaded,
    idea_id: &str,
    components: Vec<String>,
    dry_run: bool,
) -> Result<()> {
    use nornir::funnel::{self, IdeaId};

    let id = IdeaId::new(idea_id);
    let idea = store
        .funnel
        .ideas
        .get(&id)
        .cloned()
        .ok_or_else(|| anyhow::anyhow!("unknown funnel item `{idea_id}` (see `nornir funnel history`)"))?;

    // The dep graph is the planner's spine (heavy — drives `cargo metadata`).
    let (graph, _ws) = nornir::mimir::build_graph(loaded)?;

    // Determine the touched component(s): an explicit `--component` wins (the
    // pick-list path); otherwise classify via the LLM → embedder → pick-list.
    let proposal;
    let touched: Vec<String> = if !components.is_empty() {
        proposal = None;
        components
    } else {
        // The local LLM (ollama) is always offered; if it's not running, the
        // call errors and the proposer falls through to the embedder/pick-list.
        let llm = nornir::warehouse::agent_model_runs::OllamaCaller::new(None);
        // The embedder is only available with the vector+embed features built in.
        #[cfg(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort")))]
        let embedder = load_vector_embedder().ok();
        #[cfg(not(all(feature = "vector", any(feature = "embed-tract", feature = "embed-ort"))))]
        let embedder: Option<Box<dyn nornir::funnel::planner::ProposerEmbedder>> = None;

        let p = funnel::propose_components(
            &idea.text,
            &graph,
            Some(&llm),
            embedder.as_deref(),
        );
        let picks = p.picks.clone();
        proposal = Some(p);
        picks
    };

    let derived = if touched.is_empty() {
        None
    } else {
        Some(funnel::derive_plan(&graph, &touched, idea.item_kind))
    };

    // When nothing was confidently picked, print the pick-list and stop — the
    // user re-runs with `--component <name>`.
    if touched.is_empty() {
        let all = funnel::component_list(&graph);
        let out = serde_json::json!({
            "idea_id": idea_id,
            "item_kind": idea.item_kind.as_str(),
            "proposal": proposal.as_ref().map(|p| p.to_json()),
            "pick_list": all,
            "hint": "no component confidently matched — re-run with --component <name>",
        });
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(());
    }

    let derived = derived.unwrap();
    if dry_run {
        let out = serde_json::json!({
            "idea_id": idea_id,
            "item_kind": idea.item_kind.as_str(),
            "proposal": proposal.as_ref().map(|p| p.to_json()),
            "derived": derived.to_json(),
            "dry_run": true,
        });
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(());
    }

    let plan_id = funnel::plan_from_component(store, &id, &touched, &graph)?;
    let out = serde_json::json!({
        "idea_id": idea_id,
        "item_kind": idea.item_kind.as_str(),
        "proposal": proposal.as_ref().map(|p| p.to_json()),
        "derived": derived.to_json(),
        "plan_id": plan_id.as_str(),
    });
    println!("{}", serde_json::to_string_pretty(&out)?);
    Ok(())
}

/// EPIC #45 — `nornir funnel decompose <task>`: decompose a task into atomic
/// subtasks (RAG-anchored to a code index), run each through the local-LLM
/// generate → CodegenJudge oracle → retry loop, print the subtask DAG + verdicts,
/// and (with `--store`) persist the subtasks as child funnel DAG nodes + their
/// verdicts. 100% local: `--gen mock` (the default) needs no model and no
/// network — the compiler is the accept/reject oracle.
fn run_funnel_decompose(root: &std::path::Path, args: &DecomposeArgs) -> Result<()> {
    use nornir::funnel::{self, decompose, IdeaId};
    use nornir::knowledge::query::KnowledgeView;
    use nornir::warehouse::codegen_judge::{CodegenJudge, CodegenSpec};
    use nornir::warehouse::generator::{generator, spec_from_env};

    // 1. Resolve the task text. An item id (`i-…`/`p-…` in the funnel) resolves
    //    to its stored text; anything else is treated as a raw task string.
    //    `--store` requires an id so the subtasks have a parent to hang under.
    let mut maybe_idea: Option<IdeaId> = None;
    let task_text: String = {
        let looks_like_id = args.task.starts_with("i-") || args.task.starts_with("p-");
        if looks_like_id {
            let store = funnel::Store::open_read_only(root)?;
            let id = IdeaId::new(&args.task);
            match store.funnel.ideas.get(&id) {
                Some(idea) => {
                    maybe_idea = Some(id);
                    idea.text.clone()
                }
                None => args.task.clone(), // not a known id → treat as raw text
            }
        } else {
            args.task.clone()
        }
    };
    if args.store && maybe_idea.is_none() {
        anyhow::bail!(
            "--store needs `task` to be a known funnel item id (got `{}`); \
             submit it first with `nornir funnel idea \"\"`",
            args.task
        );
    }

    // 2. Build the code index (RAG anchor) + the CodegenJudge target crate.
    //    --fixture (or the default for a dry run): a self-contained tiny crate in
    //    a temp dir — the model-free, network-free demo. --repo <dir>: scan that
    //    crate. The temp dir must outlive the judge, so keep it bound.
    let _fixture_guard;
    let crate_dir: std::path::PathBuf;
    let view: KnowledgeView;
    if let Some(repo) = &args.repo {
        crate_dir = std::path::PathBuf::from(repo);
        let scan = nornir::knowledge::symbols::scan_repo(
            &crate_dir,
            repo,
            uuid::Uuid::new_v4(),
            chrono::Utc::now(),
        )?;
        view = KnowledgeView { symbols: scan.symbols, calls: scan.calls };
    } else {
        // Default + `--fixture`: a tiny throwaway crate whose `add` is wrong, so
        // the loop has something real to fix and the judge has tests to gate on.
        let (dir, dir_view) = build_decompose_fixture()?;
        crate_dir = dir.path().to_path_buf();
        view = dir_view;
        _fixture_guard = dir; // keep the temp dir alive for the judge
    }

    // 3. The generator: `--gen` > $NORNIR_GEN_BACKEND > `mock` (offline default).
    let gen_spec = args
        .gen
        .clone()
        .or_else(spec_from_env)
        .unwrap_or_else(|| "mock".to_string());
    let gen = generator(&gen_spec)?;
    if !gen.available() {
        eprintln!(
            "warning: generator `{}` reports available()=false (model/lib not present) — \
             expect rejects; use `--gen mock` for the offline demo",
            gen.id()
        );
    }

    // 4. The oracle: a REAL CodegenJudge that overwrites the crate's lib.rs with
    //    each generated body, builds + runs `cargo test`. The compiler decides.
    let judge = CodegenJudge::new(CodegenSpec::write_file(crate_dir.clone(), "src/lib.rs"));

    // 5. Run the whole loop.
    let report = funnel::simulate(
        &task_text,
        &view,
        gen.as_ref(),
        &judge,
        args.top_k,
        args.max_subtasks.min(decompose::MAX_SUBTASKS),
        args.rounds,
    )?;

    // 6. Optionally persist the subtasks as child funnel DAG nodes + verdicts.
    let mut stored_plan: Option<String> = None;
    if let (true, Some(idea)) = (args.store, maybe_idea.as_ref()) {
        let mut store = funnel::Store::open(root)?;
        let (plan_id, node_ids) = funnel::store_subtasks(&mut store, idea, &report.decomposition)?;
        funnel::apply_verdicts(&mut store, &plan_id, &node_ids, &report.verdicts)?;
        stored_plan = Some(plan_id.as_str().to_string());
    }

    // 7. Output: JSON state_json or the human subtask-DAG view.
    if args.json {
        let mut out = report.to_json();
        out["generator"] = serde_json::Value::String(gen.id().to_string());
        out["judge_crate"] = serde_json::Value::String(crate_dir.display().to_string());
        if let Some(p) = &stored_plan {
            out["stored_plan"] = serde_json::Value::String(p.clone());
        }
        println!("{}", serde_json::to_string_pretty(&out)?);
    } else {
        println!("funnel decompose (gen={}, oracle=CodegenJudge)", gen.id());
        print!("{}", report.render());
        if let Some(p) = &stored_plan {
            println!("stored as child plan {p} (subtask nodes + verdicts persisted)");
        }
        println!(
            "{}/{} subtasks accepted by the compiler-oracle",
            report.accepted, report.total
        );
    }
    Ok(())
}

/// Build the self-contained decompose fixture: a tiny temp crate whose `add` is
/// deliberately wrong (returns 0) with a baked-in acceptance test asserting
/// `add(2,2)==4`, plus the matching in-memory [`KnowledgeView`] (the RAG index).
/// The CodegenJudge overwrites `src/lib.rs` with each generated body and runs the
/// test — so a correct generator passes, the `mock` echo fails. No network.
fn build_decompose_fixture(
) -> Result<(tempfile::TempDir, nornir::knowledge::query::KnowledgeView)> {
    use nornir::knowledge::query::KnowledgeView;
    use nornir::knowledge::symbols::SymbolRow;

    let dir = tempfile::tempdir()?;
    let root = dir.path();
    std::fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = \"decompose_fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n[lib]\npath = \"src/lib.rs\"\n",
    )?;
    std::fs::create_dir_all(root.join("src"))?;
    // The starting (wrong) body — and the acceptance test the judge gates on.
    std::fs::write(
        root.join("src/lib.rs"),
        "//! decompose fixture crate\npub fn add(_a: i32, _b: i32) -> i32 { 0 }\n\
         \n#[cfg(test)]\nmod t { use super::*; #[test] fn add_works() { assert_eq!(add(2, 2), 4); } }\n",
    )?;
    let view = KnowledgeView {
        symbols: vec![SymbolRow {
            crate_name: "decompose_fixture".into(),
            module_path: "decompose_fixture".into(),
            item_kind: "fn".into(),
            item_name: "add".into(),
            visibility: "pub".into(),
            file: "src/lib.rs".into(),
            line: 2,
            doc_lines: 0,
            signature: Some("pub fn add(a: i32, b: i32) -> i32".into()),
        }],
        calls: vec![],
    };
    Ok((dir, view))
}

/// One-line, length-capped preview of free text (newlines → spaces) for the
/// `funnel history --table` rows.
fn truncate_one_line(s: &str, max: usize) -> String {
    let flat: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
    if flat.chars().count() <= max {
        flat
    } else {
        let head: String = flat.chars().take(max.saturating_sub(1)).collect();
        format!("{head}")
    }
}

/// `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::repo_dir_resolved(&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_and_model(),
    );
    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(())
}

/// `nornir airgap …` (EPIC AIRGAP / AIRGAP9) — the Skíðblaðnir pipeline, in CLI
/// parity with the `nornir-airgap` crate + the MCP tools. pack/fetch/unfold are
/// pure (no warehouse); install is root-only on Linux; start emits the
/// `airgap_events` DAG into the warehouse (JSONL sink + Iceberg ingest).
fn run_airgap(op: AirgapOp, loaded: &Loaded) -> Result<()> {
    use nornir_airgap::archive::{Archive, TarZstd};
    match op {
        AirgapOp::Pack(a) => {
            let version = a
                .version
                .unwrap_or_else(|| chrono::Utc::now().format("%Y%m%d").to_string());
            let manifest = TarZstd::new().pack(&a.staging, &version, &a.out)?;
            nornir_airgap::pack::write_version_file(&a.out, &version)?;
            println!(
                "✓ packed {} entries → {} (root sha256 {}, VERSION beside)",
                manifest.entries.len(),
                a.out.display(),
                &manifest.root_sha256[..16]
            );
            Ok(())
        }
        AirgapOp::Fetch(a) => {
            let report = nornir_airgap::fetch::verify_on_receipt(
                &a.bundle,
                &TarZstd::new(),
                a.sha256.as_deref(),
            )?;
            if report.is_ok() {
                println!("✓ bundle verified: manifest+contents intact (zero network)");
                Ok(())
            } else {
                anyhow::bail!(
                    "✗ bundle verify FAILED (manifest_root_ok={}, bundle_hash_ok={}, bad={:?})",
                    report.manifest_root_ok,
                    report.bundle_hash_ok,
                    report.bad_entries
                )
            }
        }
        AirgapOp::Unfold(a) => {
            use nornir_airgap::unfold::{kvm::KvmTarget, redfish, terraform};
            match a.backend.as_str() {
                "kvm" => {
                    let t = KvmTarget::new(&a.target, a.disk.unwrap_or_default());
                    println!("kvm qemu argv (accel=kvm:tcg, kvm_available={}):", KvmTarget::kvm_available());
                    println!("  qemu-system-x86_64 {}", t.qemu_argv().join(" "));
                    Ok(())
                }
                "terraform" => {
                    let t = terraform::TerraformTarget { workspace: a.target.clone(), product: a.target };
                    print!("{}", terraform::render_resource(&t));
                    Ok(())
                }
                "redfish" => {
                    println!("redfish reset body: {}", redfish::reset_body());
                    println!("(provisioning is a seam — enable the `redfish` feature)");
                    Ok(())
                }
                other => anyhow::bail!("unknown unfold backend `{other}` (kvm|terraform|redfish)"),
            }
        }
        AirgapOp::Install(a) => {
            use nornir_airgap::layout::Layout;
            use nornir_airgap::product::{ComponentSpec, Installer, SystemdInstaller};
            let spec: ComponentSpec = serde_json::from_slice(
                &std::fs::read(&a.spec).with_context(|| format!("read spec {}", a.spec.display()))?,
            )
            .context("parse ComponentSpec JSON")?;
            let layout = Layout::dated(&a.data_dir, &a.software_dir);
            SystemdInstaller
                .install(&spec, &layout, &a.bundle, &TarZstd::new())
                .with_context(|| format!("install `{}`", spec.name))?;
            println!("✓ installed `{}` from {}", spec.name, a.bundle.display());
            Ok(())
        }
        AirgapOp::Start(a) => {
            use nornir_airgap::config::LakeSpec;
            use nornir_airgap::events::{op as evop, phase, status, EventEmitter, JsonlSink};
            let lake: LakeSpec = serde_json::from_slice(
                &std::fs::read(&a.spec).with_context(|| format!("read lake spec {}", a.spec.display()))?,
            )
            .context("parse LakeSpec JSON")?;
            let waves = lake.start_waves()?;

            let wh_root = a.warehouse.unwrap_or_else(|| iceberg_warehouse_root(loaded));
            let sink = JsonlSink::under_warehouse(&wh_root)?;
            let run_id = format!("airgap-{}", chrono::Utc::now().format("%Y%m%dT%H%M%S"));
            let em = EventEmitter::new(&run_id, &sink);
            let by_name: std::collections::HashMap<_, _> =
                lake.products.iter().map(|p| (p.name.clone(), p)).collect();

            println!("dependency-ordered start ({} waves):", waves.len());
            for (i, wave) in waves.iter().enumerate() {
                println!("  wave {}: {}", i + 1, wave.join(", "));
                for name in wave {
                    let deps = by_name.get(name).map(|c| c.after.clone()).unwrap_or_default();
                    // start order computed; the actual systemctl start happens via
                    // `airgap install` per node — here we record the bring-up DAG.
                    em.emit(name, evop::START, phase::END, status::OK, "ordered", &deps);
                }
            }
            println!("✓ airgap_events written → {}", sink.path().display());

            // Ingest the JSONL into the Iceberg `airgap_events` table when the
            // warehouse opens (durable, historized). Non-fatal if it can't.
            match nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded)) {
                Ok(wh) => {
                    let rows = nornir::warehouse::airgap_events::read_jsonl(sink.path())?;
                    if let Err(e) = wh.block_on(
                        nornir::warehouse::airgap_events::append_airgap_events(&wh, &rows),
                    ) {
                        eprintln!("   ⚠ airgap_events Iceberg ingest (non-fatal): {e:#}");
                    } else {
                        println!("✓ ingested {} airgap_events rows into the warehouse", rows.len());
                    }
                }
                Err(e) => eprintln!("   ⚠ warehouse not opened (events stay in JSONL): {e:#}"),
            }
            Ok(())
        }
        AirgapOp::Events(a) => {
            let wh_root = a.warehouse.unwrap_or_else(|| iceberg_warehouse_root(loaded));
            let path = wh_root.join("airgap_events.jsonl");
            if !path.exists() {
                println!("no airgap_events at {} (run `nornir airgap start`)", path.display());
                return Ok(());
            }
            for ev in nornir_airgap::events::read_jsonl(&path)? {
                println!(
                    "  [{}] {:>3} {:<14} {:<8} {:<5} {:<7} {} {}",
                    ev.run_id, ev.seq, ev.product, ev.op, ev.phase, ev.status, ev.detail,
                    if ev.depends_on.is_empty() { String::new() } else { format!("{}", ev.depends_on.join(",")) }
                );
            }
            Ok(())
        }
    }
}

/// `nornir arch …` (EPIC ARCH n-006) — the architecture-wiring generator. Scans
/// the repo's symbols + call edges + warehouse-access facts, coarsens them into
/// the component/gRPC/core/table wiring graph, renders the skade circuit-board
/// SVG, and (for `generate`) historizes it in the warehouse keyed by git sha.
fn run_arch(op: ArchOp, loaded: &Loaded) -> Result<()> {
    match op {
        ArchOp::Generate(a) => arch_generate(loaded, &a, /*print_svg*/ false),
        ArchOp::Svg(a) => arch_generate(loaded, &a, /*print_svg*/ true),
        ArchOp::Trace(a) => arch_trace(loaded, &a),
        ArchOp::History(a) => {
            let repo = repo_or_err(loaded, &a.repo)?.clone();
            let _ = repo;
            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 rows = nornir::arch::warehouse::list_arch_wiring(&wh, &a.repo)?;
            if rows.is_empty() {
                println!("no historized wiring for `{}` (run `nornir arch generate {}`)", a.repo, a.repo);
            }
            for r in &rows {
                println!(
                    "  {} nodes={} edges={} git={} at {} (id {})",
                    r.repo,
                    r.node_count,
                    r.edge_count,
                    &r.git_sha[..r.git_sha.len().min(12)],
                    r.generated_at,
                    &r.wiring_id[..r.wiring_id.len().min(8)],
                );
            }
            Ok(())
        }
    }
}

fn arch_generate(loaded: &Loaded, a: &ArchGenerateArgs, print_svg: bool) -> Result<()> {
    let _ = repo_or_err(loaded, &a.repo.repo)?; // must be an appointed member
    let repo_root = config::repo_dir_resolved(&loaded.workspace_root, &a.repo.repo);

    // 1. Scan the facts fresh from the working tree (the always-fresh source).
    let scan = nornir::knowledge::scan_all(&repo_root, &a.repo.repo)?;
    let access = nornir::warehouse::access_scan::scan_repo(&repo_root)?;

    // 2. Coarsen → the wiring graph; render the circuit-board SVG.
    let graph = nornir::arch::generate(&scan.symbols.symbols, &scan.symbols.calls, &access);
    let svg = graph.to_svg();

    let comps = graph.nodes.iter().filter(|n| n.kind == nornir::arch::NodeKind::Component).count();
    let grpc = graph.nodes.iter().filter(|n| n.kind == nornir::arch::NodeKind::Grpc).count();
    let tables = graph.nodes.iter().filter(|n| n.kind == nornir::arch::NodeKind::Table).count();
    let core = graph.nodes.iter().filter(|n| n.kind == nornir::arch::NodeKind::CoreFn).count();

    if print_svg {
        if let Some(out) = &a.out {
            if let Some(parent) = out.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(out, svg.as_bytes())?;
            eprintln!("wrote {} ({} bytes)", out.display(), svg.len());
        } else {
            print!("{svg}");
        }
        return Ok(());
    }

    println!(
        "arch: nodes={} (component={} grpc={} core={} table={}) edges={}",
        graph.nodes.len(),
        comps,
        grpc,
        core,
        tables,
        graph.edges.len(),
    );

    // Optional: write the SVG to a file too.
    if let Some(out) = &a.out {
        if let Some(parent) = out.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(out, svg.as_bytes())?;
        println!("wrote {} ({} bytes)", out.display(), svg.len());
    }

    // 3. Historize in the warehouse, keyed by git sha.
    if !a.skip_snapshot {
        let (git_sha, _) =
            read_git_head(&repo_root).unwrap_or_else(|_| ("unknown".into(), "unknown".into()));
        let workspace = workspace_name(loaded);
        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 rec = nornir::arch::warehouse::record_arch_wiring(
            &wh, &workspace, &a.repo.repo, &git_sha, &graph, &svg,
        )?;
        println!(
            "historized wiring {} (nodes={} edges={}, git {}, sha256 {}…)",
            &rec.wiring_id[..rec.wiring_id.len().min(8)],
            rec.node_count,
            rec.edge_count,
            &rec.git_sha[..rec.git_sha.len().min(12)],
            &rec.graph_sha256[..12.min(rec.graph_sha256.len())],
        );
    }
    Ok(())
}

/// `nornir arch trace <entrypoint>` — scan the repo fresh, coarsen, then trace
/// the focused sub-board reachable from `entrypoint`, rendering its SVG.
fn arch_trace(loaded: &Loaded, a: &ArchTraceArgs) -> Result<()> {
    let _ = repo_or_err(loaded, &a.repo.repo)?;
    let repo_root = config::repo_dir_resolved(&loaded.workspace_root, &a.repo.repo);
    let scan = nornir::knowledge::scan_all(&repo_root, &a.repo.repo)?;
    let access = nornir::warehouse::access_scan::scan_repo(&repo_root)?;
    let graph = nornir::arch::generate(&scan.symbols.symbols, &scan.symbols.calls, &access);
    let sub = nornir::arch::trace_from(&graph, &a.entrypoint);
    if sub.nodes.is_empty() {
        eprintln!(
            "arch trace: no node matched entrypoint `{}` in `{}`",
            a.entrypoint, a.repo.repo
        );
    } else {
        eprintln!(
            "arch trace `{}`: {} nodes, {} edges reachable",
            a.entrypoint,
            sub.nodes.len(),
            sub.edges.len()
        );
    }
    let svg = sub.to_svg();
    if let Some(out) = &a.out {
        if let Some(parent) = out.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(out, svg.as_bytes())?;
        eprintln!("wrote {} ({} bytes)", out.display(), svg.len());
    } else {
        print!("{svg}");
    }
    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::repo_dir_resolved(&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()?;
    match config::discover(&cwd) {
        Ok(loaded) => Ok(loaded),
        // Thin-client mode (`--server`/`NORNIR_SERVER` set) needs NO local config:
        // every thin command routes to the server via `server_target()`. Discovery
        // only fails here when there's no `nornir.toml` up the tree, so when a server
        // is targeted we hand back an empty `Loaded` rather than erroring — the same
        // contract the discovery error message advertises. The fat (no-server) path
        // still surfaces the original "no nornir.toml found" error.
        Err(e) => {
            if server_target().is_some() {
                Ok(Loaded::default())
            } else {
                Err(e)
            }
        }
    }
}

// ───────────────────────── 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);
    }
    // The bearer token comes from the global `--token` flag (≥16 chars), which
    // `main()` has already placed in `NORNIR_SERVER_TOKEN`; the execed
    // `nornir-server` inherits it from the environment.
    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)]
/// How `nornir viz` resolves where data comes from. See `.nornir/viz-modes.md`.
#[derive(Debug, PartialEq, Eq)]
enum VizMode {
    /// Thin client — a remote call to the server.
    Thin,
    /// Fat / embedded — read the local `~/.nornir` warehouse.
    Fat,
    /// No config AND no server — open an empty local view (with a hint).
    EmptyLocal,
}

/// PURE mode resolution — every start permutation × config-present/absent.
/// `NORNIR_SERVER` set → THIN (explicit). `--warehouse` → FAT (explicit).
/// A reachable server → THIN (takes priority over a discovered config, since
/// running from the mono-repo root should connect to the live server, not fall
/// back to a stale `/tmp` warehouse). Only when no server is reachable and a
/// workspace config is found → FAT. No config AND no server → empty local.
/// Tested in `viz_mode_tests`.
fn viz_mode(
    server_env_set: bool,
    warehouse_set: bool,
    has_config: bool,
    server_reachable: bool,
) -> VizMode {
    if server_env_set {
        VizMode::Thin
    } else if warehouse_set {
        VizMode::Fat
    } else if server_reachable {
        // Server up → THIN (preferred over a discovered config so that
        // running from the mono-repo root connects to the live server rather
        // than the default /tmp warehouse).
        VizMode::Thin
    } else if has_config {
        VizMode::Fat
    } else {
        VizMode::EmptyLocal
    }
}

/// Is a local nornir-server listening on `127.0.0.1:7878`? (300 ms TCP probe.)
#[cfg(unix)]
fn viz_local_server_reachable() -> bool {
    let addr: std::net::SocketAddr = "127.0.0.1:7878".parse().unwrap();
    std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300)).is_ok()
}

#[cfg(test)]
mod viz_mode_tests {
    use super::{viz_mode, VizMode};

    // Every way to start `nornir viz`, crossed with whether a config exists.
    #[test]
    fn viz_mode_covers_all_start_permutations() {
        // NORNIR_SERVER set → THIN, regardless of everything else.
        assert_eq!(viz_mode(true, false, false, false), VizMode::Thin);
        assert_eq!(viz_mode(true, true, true, true), VizMode::Thin);
        // --warehouse given explicitly → FAT (explicit overrides everything except NORNIR_SERVER).
        assert_eq!(viz_mode(false, true, false, true), VizMode::Fat);
        assert_eq!(viz_mode(false, true, true, true), VizMode::Fat);
        // Server reachable → THIN, even when a config was discovered in a subdirectory.
        // Running from the mono-repo root (workspace_*/release/nornir.toml present) with
        // the server up should connect to the server, not fall back to /tmp.
        assert_eq!(viz_mode(false, false, true, true), VizMode::Thin);
        assert_eq!(viz_mode(false, false, false, true), VizMode::Thin);
        // No server + config found → FAT (offline / workspace-specific local inspection).
        assert_eq!(viz_mode(false, false, true, false), VizMode::Fat);
        // NO config + NO server → empty local view.
        assert_eq!(viz_mode(false, false, false, false), VizMode::EmptyLocal);
    }
}

#[cfg(test)]
mod global_thin_client_flag_tests {
    //! Guards the thin-client UX: `--server`/`--token` are GLOBAL, so
    //! `nornir <any-subcommand> --server <url> --token <tok>` routes that command
    //! to the server. Inject argv → assert the parsed values (no network).
    use super::{Cli, Cmd, TestOp};
    use clap::Parser;

    #[test]
    fn server_and_token_parse_after_a_subcommand() {
        let cli = Cli::try_parse_from([
            "nornir", "test", "run", "nornir",
            "--server", "oden:7878",
            "--token", "deadbeefcafef00d",
        ])
        .expect("global --server/--token must parse AFTER the `test run` subcommand");
        assert_eq!(cli.server.as_deref(), Some("oden:7878"));
        assert_eq!(cli.token.as_deref(), Some("deadbeefcafef00d"));
        assert!(matches!(cli.cmd, Cmd::Test { op: TestOp::Run(_) }));
    }

    #[test]
    fn server_also_parses_before_a_subcommand() {
        let cli = Cli::try_parse_from(["nornir", "--server", "http://oden:7878", "repos"])
            .expect("global --server must parse BEFORE the subcommand too");
        assert_eq!(cli.server.as_deref(), Some("http://oden:7878"));
        assert!(matches!(cli.cmd, Cmd::Repos));
    }

    #[test]
    fn mirror_to_holger_token_renamed_so_it_does_not_eat_the_global_token() {
        // The holger registry token now lives under `--holger-token`; the global
        // `--token` (server bearer) is independently accepted on the same command.
        let cli = Cli::try_parse_from([
            "nornir", "release", "mirror-to-holger", "skade", "skade-katalog", "0.1.0",
            "--holger-base-url", "https://holger.example",
            "--holger-token", "htok",
            "--token", "stok",
        ])
        .expect("mirror-to-holger must accept --holger-token alongside the global --token");
        assert_eq!(cli.token.as_deref(), Some("stok"));
    }

    #[test]
    fn workspace_is_global_after_a_subcommand() {
        let cli = Cli::try_parse_from([
            "nornir", "test", "run", "nornir", "--server", "oden:7878", "--workspace", "nordisk",
        ])
        .expect("global --workspace must parse after a subcommand");
        assert_eq!(cli.workspace.as_deref(), Some("nordisk"));
    }

    // The five commands that USED to own a local `--workspace` must now accept the
    // GLOBAL one (proves the removal didn't drop the flag, and there's no clash).
    #[test]
    fn workspace_reaches_the_former_local_owners() {
        for argv in [
            vec!["nornir", "release", "run", "--workspace", "holger"],
            vec!["nornir", "release", "trace", "somerepo", "--workspace", "holger"],
            vec!["nornir", "index", "snapshot", "--workspace", "holger"],
            vec!["nornir", "diagram", "timeline", "--workspace", "korp"],
            vec!["nornir", "viz", "--workspace", "korp"],
        ] {
            let cli = Cli::try_parse_from(&argv)
                .unwrap_or_else(|e| panic!("`{}` must accept the global --workspace: {e}", argv.join(" ")));
            assert!(cli.workspace.is_some(), "workspace not captured for {argv:?}");
        }
    }
}

#[cfg(test)]
mod workspace_resolution_tests {
    //! The `nornir-workspace` header must carry the canonical `workspace_<name>`
    //! name (the manual's convention + what the server serves), NOT the mono-repo
    //! dir. Regression guard for the "stand in `workspace_nordisk` → nordisk" bug
    //! where the client used to send `git`.
    use super::cwd_workspace_name;
    use std::path::Path;

    #[test]
    fn standing_in_a_workspace_dir_resolves_the_suffix() {
        assert_eq!(
            cwd_workspace_name(Path::new("/run/media/rickard/T9/git/workspace_nordisk")).as_deref(),
            Some("nordisk"),
        );
        // …and from a subdir of it (e.g. the release/ control plane).
        assert_eq!(
            cwd_workspace_name(Path::new("/x/git/workspace_holger/release")).as_deref(),
            Some("holger"),
        );
    }

    #[test]
    fn deepest_workspace_component_wins() {
        assert_eq!(
            cwd_workspace_name(Path::new("/git/workspace_holger/nested/workspace_matrix/sub")).as_deref(),
            Some("matrix"),
        );
    }

    #[test]
    fn no_workspace_component_is_none_not_the_repo_dir() {
        // The old bug returned the mono-repo dir ("git"); now there is simply no
        // implied name when the path has no `workspace_<name>` segment.
        assert_eq!(cwd_workspace_name(Path::new("/run/media/rickard/T9/git/nornir")), None);
        assert_eq!(cwd_workspace_name(Path::new("/home/rickard")), None);
    }
}

fn run_viz(a: &VizArgs, config: Option<&Path>) -> 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);
    // ── Mode resolution (the agreed three-mode rule) ──────────────────────────
    // `NORNIR_SERVER` set → THIN (explicit). `--warehouse` → FAT/embedded (explicit).
    // Otherwise: if a workspace config is **found** (`--config`, or discovered by
    // walking up from cwd into a `workspace_<name>/`) → **FAT/embedded** (urdr-threads
    // reads the local `~/.nornir`). If **no config is found** → **THIN CLIENT, out of
    // the box**: a plain remote call to a local server on :7878 (token from the
    // user-readable `<home>/.nornir/token`). No server reachable → an empty local view
    // with a hint. See `.nornir/viz-modes.md`.
    // Explicit `--server <addr>`/`--token` are the GLOBAL flags now: `main()` has
    // already normalized them into `NORNIR_SERVER`/`NORNIR_SERVER_TOKEN` (with the
    // `<home>/.nornir/token` fallback), and the child `urdr-threads` inherits that
    // env — so here we only read it back to resolve the viz mode.
    if let Ok(url) = std::env::var("NORNIR_SERVER") {
        if !url.is_empty() {
            eprintln!("nornir viz: NORNIR_SERVER {url} → thin client");
        }
    }
    let server_env_set = std::env::var_os("NORNIR_SERVER").is_some();
    let warehouse_set = a.warehouse.is_some();
    if !server_env_set && !warehouse_set {
        // Discover whether a workspace config exists (walking up from cwd).
        let discovered = config
            .map(|c| {
                nornir::config::load_explicit(c)
                    .ok()
                    .map(|l| (l, c.to_path_buf()))
            })
            .unwrap_or_else(|| {
                std::env::current_dir()
                    .ok()
                    .and_then(|cwd| nornir::config::discover(&cwd).ok())
                    .map(|l| {
                        let p = l.config_path.clone();
                        (l, p)
                    })
            });
        let has_config = discovered.is_some();
        // Probe the server regardless of whether a config was found: a reachable
        // server takes priority over a discovered config (running from the mono-repo
        // root with workspace_*/release/nornir.toml present should connect to the
        // live server, not fall back to the default warehouse path).
        let server_reachable = viz_local_server_reachable();
        match viz_mode(false, false, has_config, server_reachable) {
            VizMode::Thin => {
                cmd.env("NORNIR_SERVER", "http://127.0.0.1:7878");
                if std::env::var_os("NORNIR_SERVER_TOKEN").is_none() {
                    if let Ok(tok) =
                        std::fs::read_to_string(nornir::config::nornir_home().join("token"))
                    {
                        let tok = tok.trim();
                        if !tok.is_empty() {
                            cmd.env("NORNIR_SERVER_TOKEN", tok);
                        }
                    }
                }
                if has_config {
                    eprintln!(
                        "nornir viz: workspace config found but server is reachable → thin client \
                         → http://127.0.0.1:7878"
                    );
                } else {
                    eprintln!(
                        "nornir viz: no local workspace config → thin client → http://127.0.0.1:7878"
                    );
                }
            }
            VizMode::EmptyLocal => {
                eprintln!(
                    "nornir viz: no workspace config and no server on :7878 — opening an empty \
                     local view. `cd` into a `workspace_<name>/` (fat) or start the server (thin)."
                );
            }
            VizMode::Fat => {
                // Pass the warehouse path from the discovered config so urdr-threads
                // reads the real ~/.nornir/warehouse (not the /tmp/nornir-demo-warehouse
                // CLI default). This path is already correct per the config's
                // [storage].local_path / home-derived fallback.
                if let Some((loaded, _)) = &discovered {
                    let wh = loaded.warehouse_root();
                    eprintln!(
                        "nornir viz: fat mode → warehouse {}",
                        wh.display()
                    );
                    cmd.arg("--warehouse").arg(&wh);
                }
            }
        }
    }
    if let Some(c) = config {
        cmd.arg("--config").arg(c);
    }
    // Workspace propagates via the inherited `NORNIR_WORKSPACE` env (set by the
    // global `--workspace` flag in `main`); urdr-threads reads it directly.
    if let Some(wh) = &a.warehouse {
        cmd.arg("--warehouse").arg(wh);
    }
    // LAW4b — pass --screenshot through to urdr-threads.
    if let Some(s) = &a.screenshot {
        cmd.arg("--screenshot").arg(s);
    }
    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, _config: Option<&Path>) -> 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.
/// Home-derived: `<home>/.nornir/workspaces` for the running user. ONE rule,
/// no path env-var (containers/the systemd service set `$HOME`).
fn server_root() -> PathBuf {
    nornir::config::registry_root()
}

/// `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_security(cmd: &SecurityCmd) -> Result<()> {
    match cmd {
        SecurityCmd::Scan { repo, out } => {
            // Server mode (NORNIR_SERVER): scan server-side via Mimir.SecurityScan
            // — warehouse-cached (zero network in steady state) + the sources need
            // not be on this host. CLI parity with the viz Security tab.
            #[cfg(any(feature = "mcp", feature = "server"))]
            if let Some(server) = server_target() {
                use pb_client::mimir_client::MimirClient;
                use pb_client::RepoOnly;
                let repo_name = repo
                    .file_name()
                    .map(|s| s.to_string_lossy().into_owned())
                    .unwrap_or_else(|| repo.display().to_string());
                let json = on_server(&server, move |channel, bearer| async move {
                    let mut c = MimirClient::with_interceptor(channel, auth_interceptor(bearer));
                    let r = c
                        .security_scan(RepoOnly { repo: repo_name })
                        .await
                        .map_err(|e| anyhow!("Mimir.SecurityScan RPC failed: {e}"))?;
                    Ok(r.into_inner().json)
                })?;
                let v: serde_json::Value = serde_json::from_str(&json)?;
                println!("repo            {}", v["repo"].as_str().unwrap_or(""));
                println!("components      {} (deep, server-side)", v["components"]);
                println!("cache           {} hit / {} miss", v["cache_hits"], v["cache_misses"]);
                let vulns = v["vulns"].as_array().cloned().unwrap_or_default();
                println!("vulnerabilities {} across {} crate(s)", vulns.len(), vulns.len());
                for x in &vulns {
                    let ids = x["ids"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|s| s.as_str()).collect::<Vec<_>>().join(", "))
                        .unwrap_or_default();
                    println!("{} {}: {}", x["crate"].as_str().unwrap_or(""), x["version"].as_str().unwrap_or(""), ids);
                }
                std::process::exit(vulns.len().min(120) as i32);
            }
            let rep = nornir::security::scan(repo)?;
            println!("repo            {}", rep.repo);
            println!("components      {} crates (deep, incl. transitive)", rep.components.len());
            println!("vulnerabilities {} across {} crate(s)", rep.vuln_count(), rep.vulns.len());
            for v in &rep.vulns {
                println!("{} {}: {}", v.crate_name, v.version, v.ids.join(", "));
            }
            let top: Vec<String> =
                rep.license_tally().into_iter().take(6).map(|(k, n)| format!("{k}×{n}")).collect();
            println!("licenses        {}", top.join(", "));
            if let Some(o) = out {
                std::fs::write(o, serde_json::to_string_pretty(&rep.to_cyclonedx())?)?;
                println!("CycloneDX SBOM  {}", o.display());
            }
            std::process::exit(rep.vulns.len().min(120) as i32);
        }
        SecurityCmd::UpdateDb => {
            let path = nornir::security::update_advisory_db()?;
            let n = std::fs::read_dir(path.join("crates")).map(|d| d.flatten().count()).unwrap_or(0);
            println!(
                "advisory-db ready at {} ({n} crate dirs) — offline (airgap) vuln matching enabled",
                path.display()
            );
            Ok(())
        }
    }
}

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,
            lazy,
        } => {
            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,
            );
            let n = ws.members.len();
            // Same silent-empty guard as the server register RPC: an eager
            // monitored register resolving 0 members means the descriptor wasn't
            // readable here — fail loudly instead of persisting a hollow workspace.
            if !*lazy && mode == Mode::Monitored && ws.members.is_empty() {
                bail!(
                    "monitored workspace `{}` resolved 0 members from descriptor `{}`: \
                     needs a readable nornir-workspace.toml with [repos.*] (or pass --lazy)",
                    ws.name, ws.descriptor
                );
            }
            reg.upsert(&ws)?;

            // EAGER by default: record + fetch (clone members) + build inline —
            // the SAME pipeline the poll loop runs on a change — so the workspace
            // is populated NOW. `--lazy` (or a non-monitored mode with no remotes
            // to clone) leaves population to the poll loop / a later `fetch`.
            if *lazy || mode != Mode::Monitored {
                println!(
                    "✓ registered `{}` ({}, {} member(s)){}{}/{}/{{git,builds}}",
                    ws.name,
                    ws.mode.as_str(),
                    n,
                    if *lazy { " [lazy — populate on poll]" } else { "" },
                    server_root().display(),
                    ws.name
                );
            } else {
                println!("① registered `{name}` ({n} member(s))");
                println!("② fetching {n} member(s)…");
                nornir::monitor::fetch_workspace(&reg, &server_root(), name)
                    .with_context(|| format!("fetch members of `{name}`"))?;
                println!("③ building warehouse…");
                let snap = nornir::monitor::republish(&reg, &server_root(), name, None)
                    .with_context(|| format!("build `{name}` warehouse"))?;
                println!(
                    "✓ registered `{name}` — populated now (snapshot {}) at {}/{name}/builds",
                    &snap[..snap.len().min(12)],
                    server_root().display(),
                );
            }
        }
        WorkspaceOp::Add {
            name,
            descriptor,
            monitored,
            external,
            poll,
        } => {
            // Eager add = register + fetch + build, inline — the SAME pipeline the
            // server's poll loop runs on a change, so a fat user and the server do
            // the same thing (the poll loop is just the automated re-run).
            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,
            );
            let n = ws.members.len();
            reg.upsert(&ws)?;
            println!("① registered `{name}` ({n} member(s))");
            // ② fetch — clone every git member into <root>/<name>/git/<member>/
            println!("② fetching {n} member(s)…");
            nornir::monitor::fetch_workspace(&reg, &server_root(), name)
                .with_context(|| format!("fetch members of `{name}`"))?;
            // ③ build — knowledge scan + code index + per-member snapshot → warehouse
            println!("③ building warehouse…");
            // First publish (fat-mode add): no change-set → full rebuild.
            let snap = nornir::monitor::republish(&reg, &server_root(), name, None)
                .with_context(|| format!("build `{name}` warehouse"))?;
            println!(
                "✓ added `{name}` — populated now (snapshot {}) at {}/{name}/builds",
                &snap[..snap.len().min(12)],
                server_root().display(),
            );
        }
        WorkspaceOp::Rm { name } => {
            if reg.remove(name)? {
                println!("✓ removed `{name}`");
            } else {
                bail!("no workspace `{name}` in the registry");
            }
        }
        WorkspaceOp::Fetch { name, force } => {
            let report = nornir::monitor::fetch_workspace(&reg, &server_root(), name)?;
            if *force {
                // Force = full rebuild even with no member change (re-scan +
                // deep-scan). Fat path republishes through its own handle.
                let snap = nornir::monitor::republish(&reg, &server_root(), name, None)?;
                println!("  ⏱ forced full rebuild → snapshot {snap}");
            }
            // 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
            );
        }
        WorkspaceOp::Populate { name } => {
            let root = server_root();
            let report = nornir::monitor::fetch_workspace(&reg, &root, name)?;
            for (m, e) in &report.errors {
                eprintln!("    {m}: {e}");
            }
            // Force a full republish (changed = None) even if no HEAD moved — the
            // point of `populate` is to (re)build the warehouse facts now.
            let snap = nornir::monitor::republish(&reg, &root, name, None)
                .with_context(|| format!("republish `{name}`"))?;
            println!(
                "✓ populated `{name}` — {} member(s) fetched, snapshot {}",
                report.fetched,
                if snap.is_empty() { "(none)".into() } else { snap }
            );
        }
    }
    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
        });
        // Home-derived warehouse for the service (HOME=NORNIR_HOME):
        // `<home>/.nornir/warehouse`. Pre-created + chowned below.
        let dw = nornir::config::nornir_home_from(Path::new(NORNIR_HOME)).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()));
    }
    // The service runs with `Environment=HOME=NORNIR_HOME`, so every nornir data
    // root is derived from that home as `<home>/.nornir/...` — ONE rule, no path
    // env-vars in the env file. We just pre-create the writable dirs (and chown
    // them below) so the service user can write them on first run.
    if let Some(dw) = &default_warehouse {
        // Pin the warehouse explicitly (NORNIR_WAREHOUSE is a behavior pin, not a
        // root rule): the staged config's workspace_root isn't writable, so point
        // the warehouse at the home-derived default (already created above). The
        // funnel is home-derived too — no env var, just the dir.
        env_body.push_str(&format!("NORNIR_WAREHOUSE={}\n", dw.display()));
        let funnel = nornir::config::nornir_home_from(Path::new(NORNIR_HOME)).join("funnel");
        std::fs::create_dir_all(&funnel).ok();
    }
    // Self-sync (monitored) settings. The registry root is the home-derived
    // `<home>/.nornir/workspaces` — created + chowned to the service user so the
    // poll loop can write it, and so the server's "registry exists" gate opens.
    // (There is no path env-var; `--root` overrides are no longer honored.)
    let monitor_root = if monitoring {
        if a.root.is_some() {
            eprintln!(
                "note: --root is ignored — the registry root is home-derived \
                 (<home>/.nornir/workspaces). Set the service user's $HOME instead."
            );
        }
        let root = nornir::config::nornir_home_from(Path::new(NORNIR_HOME)).join("workspaces");
        std::fs::create_dir_all(&root).with_context(|| format!("create {}", 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(())
}

// ───────────────────────── mimir (cross-repo dep graph) ─────────────────────
// CLI parity with the `Mimir` gRPC service + the MCP dep-graph tools. Routes to
// the server when `NORNIR_SERVER` is set (warehouse-cached graph, sources need
// not be local), else builds the WorkspaceGraph locally via the shared `mimir`
// lib (same fns the server calls). Every op prints pretty JSON, except `svg`
// which prints the raw SVG flowchart text — same shapes the viz/MCP emit.
fn run_mimir(op: MimirOp, loaded: &Loaded) -> Result<()> {
    use nornir::mimir;

    // Remote: one JSON-returning RPC per op (svg carries raw text in `json`).
    #[cfg(any(feature = "mcp", feature = "server"))]
    if let Some(server) = server_target() {
        return run_mimir_remote(&server, &op);
    }

    // Embedded: build the graph once (heavy — `cargo metadata`), then dispatch.
    let (g, _ws) = mimir::build_graph(loaded)?;
    let print = |v: serde_json::Value| -> Result<()> {
        println!("{}", serde_json::to_string_pretty(&v)?);
        Ok(())
    };
    match op {
        MimirOp::DepsOf { repo, transitive } => print(mimir::deps_of(&g, &repo, transitive)?)?,
        MimirOp::DependentsOf { repo, transitive } => {
            print(mimir::dependents_of(&g, &repo, transitive)?)?
        }
        MimirOp::Affected { repos } => print(mimir::affected_by_change(&g, &repos)?)?,
        MimirOp::BuildOrder => print(mimir::build_order(&g)?)?,
        MimirOp::DepPath { from, to } => print(mimir::dep_path(&g, &from, &to)?)?,
        MimirOp::ExternalUsers { krate } => print(mimir::external_dep_users(&g, &krate))?,
        MimirOp::Svg => println!("{}", mimir::svg(&g)),
        MimirOp::Overview { repo } => {
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(&iceberg_warehouse_root(loaded))?;
            print(mimir::repo_overview(&g, &wh, &repo)?)?;
        }
        MimirOp::Changed => {
            bail!(
                "`mimir changed` needs the server's release lineage — set NORNIR_SERVER \
                 to run it against a nornir-server (or use `release trace`/`release impacted-crates` locally)"
            );
        }
    }
    Ok(())
}

// ───────────────────────── diagram (viz Timeline renderers) ─────────────────
// CLI parity for the data-only `nornir::viz::diagram` renderers the egui viz
// draws. Loads the Timeline from a local warehouse, or the server's Viz.Timeline
// when `NORNIR_SERVER` is set, then prints the requested diagram to stdout.
fn run_diagram(op: DiagramOp, loaded: &Loaded) -> Result<()> {
    use nornir::viz::diagram;

    let ws_of = |_a: &DiagramArgs| -> String { env_workspace_or("workspace_holger") };
    let workspace = match &op {
        DiagramOp::Timeline(a)
        | DiagramOp::LaneSummary(a)
        | DiagramOp::Depgraph(a)
        | DiagramOp::SnapshotEdges(a)
        | DiagramOp::GateMatrix(a)
        | DiagramOp::ReleaseVersions(a)
        | DiagramOp::BenchCompare(a) => ws_of(a),
        DiagramOp::BenchHistory { args, .. } => ws_of(args),
    };

    let tl = load_diagram_timeline(loaded, &workspace)?;
    let out = match op {
        DiagramOp::Timeline(_) => diagram::timeline_svg(&tl),
        DiagramOp::LaneSummary(_) => diagram::lane_summary_table(&tl),
        DiagramOp::Depgraph(_) => diagram::depgraph_svg(&tl),
        DiagramOp::SnapshotEdges(_) => diagram::snapshot_edge_list(&tl),
        DiagramOp::GateMatrix(_) => diagram::gate_matrix_table(&tl),
        DiagramOp::ReleaseVersions(_) => diagram::release_versions_table(&tl),
        DiagramOp::BenchHistory { limit, .. } => diagram::bench_history_table(&tl, limit),
        DiagramOp::BenchCompare(_) => diagram::bench_compare_table(&tl),
    };
    println!("{out}");
    Ok(())
}

/// Load the viz `Timeline` either from the server (`Viz.Timeline`, when
/// `NORNIR_SERVER` is set) or a local warehouse — so `nornir diagram` works
/// fat/embedded and remote, like the viz itself.
fn load_diagram_timeline(loaded: &Loaded, workspace: &str) -> Result<nornir::viz::Timeline> {
    #[cfg(any(feature = "mcp", feature = "server"))]
    if let Some(server) = server_target() {
        return diagram_timeline_remote(&server, workspace);
    }
    nornir::viz::load_timeline(&iceberg_warehouse_root(loaded), workspace)
}

/// 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")?;
    let result = 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
    });
    // Remind/point out: an unserved workspace gets the served list appended so the
    // user knows what to pass to `--workspace`. Best-effort; the inner list call
    // uses a bearer-only interceptor (no workspace header) so it can't re-trigger.
    if let Err(e) = &result {
        if e.to_string().contains("is not served") {
            if let Ok(names) = served_workspaces_remote(server) {
                if !names.is_empty() {
                    return Err(anyhow!(
                        "{e}\n  workspaces served by {server}: {}\n  \u{2192} pass --workspace <name>, \
                         or cd into a workspace_<name>/ dir",
                        names.join(", ")
                    ));
                }
            }
        }
    }
    result
}

/// Best-effort list of the workspace names `server` serves (`Workspaces.List`).
/// Uses a bearer-ONLY interceptor (no `nornir-workspace` header) so it works even
/// when the currently-resolved workspace is one the server rejects.
#[cfg(any(feature = "mcp", feature = "server"))]
fn served_workspaces_remote(server: &str) -> Result<Vec<String>> {
    use pb_client::workspaces_client::WorkspacesClient;
    use pb_client::Empty;
    let token = std::env::var("NORNIR_SERVER_TOKEN")
        .context("NORNIR_SERVER_TOKEN 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}"))?;
        let interceptor = move |mut req: tonic::Request<()>| {
            req.metadata_mut().insert("authorization", bearer.clone());
            Ok::<_, tonic::Status>(req)
        };
        let mut c = WorkspacesClient::with_interceptor(channel, interceptor);
        let resp = c
            .list(Empty {})
            .await
            .map_err(|e| anyhow!("Workspaces.List RPC failed: {e}"))?;
        Ok(resp.into_inner().workspaces.into_iter().map(|w| w.name).collect())
    })
}

/// Resolve a workspace for a thin-client command when none was given (no
/// `--workspace`, no `$NORNIR_WORKSPACE`, not in a `workspace_<name>/` dir): an
/// interactive numbered picker on a TTY, else an error listing the served names
/// (so scripts/CI never hang). The picker is a CLI nicety — the full TUI is future.
#[cfg(any(feature = "mcp", feature = "server"))]
fn pick_workspace_or_explain(server: &str) -> Result<String> {
    use std::io::{IsTerminal, Write};
    let names = served_workspaces_remote(server).unwrap_or_default();
    if names.is_empty() {
        bail!(
            "no workspace selected and {server} reports none served. Pass --workspace <name>, \
             or register one with `nornir workspace register`."
        );
    }
    let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
    if !interactive {
        bail!(
            "no workspace selected (not in a workspace_<name>/ dir, no --workspace, no \
             $NORNIR_WORKSPACE).\n  Pass --workspace <name>. Served by {server}:\n    {}",
            names.join("\n    ")
        );
    }
    eprintln!("Select a workspace on {server}:");
    for (i, n) in names.iter().enumerate() {
        eprintln!("  {:>2}) {n}", i + 1);
    }
    eprint!("workspace # (1-{}, or name): ", names.len());
    std::io::stderr().flush().ok();
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).context("read workspace selection")?;
    let sel = line.trim();
    if let Ok(idx) = sel.parse::<usize>() {
        if (1..=names.len()).contains(&idx) {
            return Ok(names[idx - 1].clone());
        }
    }
    if names.iter().any(|n| n == sel) {
        return Ok(sel.to_string());
    }
    bail!("'{sel}' is not a served workspace. Choose 1-{} or a listed name.", names.len());
}

/// `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())
}

/// The canonical workspace name implied by a filesystem path: the `<name>` of the
/// DEEPEST `workspace_<name>` component. So standing anywhere under
/// `…/workspace_nordisk/…` resolves to `nordisk` — the manual's convention and the
/// same `<name>` the server's `workspaces_list` / the viz picker use (NOT the
/// mono-repo dir like `git`, NOT the `workspace_`-prefixed dir name). `None` when
/// the path carries no `workspace_<name>` segment.
fn cwd_workspace_name(path: &Path) -> Option<String> {
    path.components()
        .filter_map(|c| c.as_os_str().to_str())
        .filter_map(|s| s.strip_prefix("workspace_"))
        .filter(|s| !s.is_empty())
        .last()
        .map(String::from)
}

/// The workspace name for an embedded/warehouse command: the global `--workspace`
/// flag (placed in `$NORNIR_WORKSPACE` by `main`), else `default`. Embedded
/// commands don't infer from the cwd — only the explicit flag/env overrides.
fn env_workspace_or(default: &str) -> String {
    std::env::var("NORNIR_WORKSPACE")
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| default.to_string())
}

/// Which workspace the CLI targets in client mode (the `nornir-workspace` header):
/// `NORNIR_WORKSPACE` → else the cwd's `workspace_<name>` component (so standing in
/// `workspace_nordisk` targets `nordisk`, even before it has a descriptor) → else
/// the canonical name of a descriptor discovered by walking up → else `None` (the
/// server uses its default; it returns NotFound for an unserved 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()?;
        // Primary: a `workspace_<name>` component in the cwd path → `<name>`.
        if let Some(name) = cwd_workspace_name(&cwd) {
            return Some(name);
        }
        // Fallback: discover a descriptor by walking up and use ITS canonical
        // `workspace_<name>` — NOT `workspace_root.file_name()` (the mono-repo dir).
        config::discover(&cwd).ok().map(|l| l.workspace_name())
    })
    .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)
    })
}

/// Client-mode `Ops.RunTestMatrix` — ask the server to run the test matrix over
/// its checkouts and persist `test_results`. The thin-`nornir test run`/`test all`
/// path when `NORNIR_SERVER` is set (CLI parity with the viz 🧪 "Run matrix"
/// button). `repo` empty = the full matrix; prints the per-repo verdict.
#[cfg(any(feature = "mcp", feature = "server"))]
fn run_test_matrix_remote(server: &str, repo: &str, aspects: &str) -> Result<()> {
    use pb_client::ops_client::OpsClient;
    use pb_client::RunTestMatrixRequest;
    let (repo, aspects) = (repo.to_string(), aspects.to_string());
    let res = on_server(server, move |channel, bearer| async move {
        let mut c = OpsClient::with_interceptor(channel, auth_interceptor(bearer));
        Ok(c.run_test_matrix(RunTestMatrixRequest { repo, aspects })
            .await
            .map_err(|e| anyhow!("Ops.RunTestMatrix RPC failed: {e}"))?
            .into_inner())
    })?;
    println!("{}", res.summary);
    for t in &res.targets {
        let chip = if t.status == "pass" { "" } else if t.status == "skip" { "" } else { "" };
        println!("  {chip} {} {}", t.name, t.message);
    }
    if !res.ok {
        anyhow::bail!("test matrix had red runs (server-side)");
    }
    Ok(())
}

/// Client-mode `Ops.RunBench` — ask the server to run the benches for `repo`
/// (empty = primary) and persist a `BenchRun`. The thin-`nornir bench run` path
/// when `NORNIR_SERVER` is set (CLI parity with the viz 📈 "Run bencher" button).
#[cfg(any(feature = "mcp", feature = "server"))]
fn run_bench_remote(server: &str, repo: &str) -> Result<()> {
    use pb_client::ops_client::OpsClient;
    use pb_client::RunBenchRequest;
    let repo = repo.to_string();
    let res = on_server(server, move |channel, bearer| async move {
        let mut c = OpsClient::with_interceptor(channel, auth_interceptor(bearer));
        Ok(c.run_bench(RunBenchRequest { repo })
            .await
            .map_err(|e| anyhow!("Ops.RunBench RPC failed: {e}"))?
            .into_inner())
    })?;
    println!("{}", res.summary);
    if !res.ok {
        anyhow::bail!("bench had failures (server-side)");
    }
    Ok(())
}

/// Client-mode `Ops.RunRelease` — ask the server to run the release-grade gate
/// across the build order and persist `release_events`. The thin-`nornir release
/// run` path when `NORNIR_SERVER` is set (CLI parity with the viz 🚀 "Release
/// (heavy gate)" button). `repo` empty = the whole build order.
#[cfg(any(feature = "mcp", feature = "server"))]
fn run_release_remote(server: &str, repo: &str) -> Result<()> {
    use pb_client::ops_client::OpsClient;
    use pb_client::RunReleaseRequest;
    let repo = repo.to_string();
    let res = on_server(server, move |channel, bearer| async move {
        let mut c = OpsClient::with_interceptor(channel, auth_interceptor(bearer));
        Ok(c.run_release(RunReleaseRequest { repo })
            .await
            .map_err(|e| anyhow!("Ops.RunRelease RPC failed: {e}"))?
            .into_inner())
    })?;
    println!("{}", res.summary);
    for t in &res.targets {
        let chip = if t.status == "pass" { "" } else { "" };
        println!("  {chip} {} {}", t.name, t.message);
    }
    if !res.ok {
        anyhow::bail!("release gate failed (server-side)");
    }
    Ok(())
}

/// Submit bake-off rows to the server's `agent_model_runs` (Telemetry.SubmitBakeoff)
/// — the server holds the warehouse lock, so this is how a client fills the live
/// Leaderboard. Returns the accepted count.
#[cfg(any(feature = "mcp", feature = "server"))]
fn submit_bakeoff_remote(
    server: &str,
    rows: &[nornir::warehouse::agent_model_runs::AgentModelRunRow],
) -> Result<u32> {
    use pb_client::telemetry_client::TelemetryClient;
    use pb_client::{AgentModelRunPb, SubmitBakeoffRequest};
    let runs: Vec<AgentModelRunPb> = rows
        .iter()
        .map(|r| AgentModelRunPb {
            run_id: r.run_id.clone(),
            ts_micros: r.ts_micros,
            agent: r.agent.clone(),
            model: r.model.clone(),
            prompt_id: r.prompt_id.clone(),
            prompt: r.prompt.clone(),
            output: r.output.clone(),
            latency_ms: r.latency_ms,
            tokens_in: r.tokens_in,
            tokens_out: r.tokens_out,
            tokens_per_s: r.tokens_per_s,
            score: r.score,
            ok: r.ok,
            error: r.error.clone().unwrap_or_default(),
            cost_usd: r.cost_usd,
            mcp_tool_calls: r.mcp_tool_calls,
        })
        .collect();
    on_server(server, move |channel, bearer| async move {
        let mut client = TelemetryClient::with_interceptor(channel, auth_interceptor(bearer));
        let resp = client.submit_bakeoff(SubmitBakeoffRequest { runs }).await
            .map_err(|e| anyhow!("Telemetry.SubmitBakeoff RPC failed: {e}"))?;
        Ok(resp.into_inner().accepted)
    })
}

/// Submit test rows to the server's `test_results` (Telemetry.SubmitTestResults).
#[cfg(any(feature = "mcp", feature = "server"))]
fn submit_test_remote(
    server: &str,
    rows: &[nornir::warehouse::test_results::TestResultRow],
) -> Result<u32> {
    use pb_client::telemetry_client::TelemetryClient;
    use pb_client::{SubmitTestResultsRequest, TestResultPb};
    let pb_rows: Vec<TestResultPb> = rows
        .iter()
        .map(|r| TestResultPb {
            run_id: r.run_id.clone(),
            repo: r.repo.clone(),
            suite: r.suite.clone(),
            test_name: r.test_name.clone(),
            status: r.status.clone(),
            duration_ms: r.duration_ms,
            ts_micros: r.ts_micros,
            message: r.message.clone(),
            aspect: r.aspect.clone(),
            metric: r.metric,
        })
        .collect();
    on_server(server, move |channel, bearer| async move {
        let mut client = TelemetryClient::with_interceptor(channel, auth_interceptor(bearer));
        let resp = client.submit_test_results(SubmitTestResultsRequest { rows: pb_rows }).await
            .map_err(|e| anyhow!("Telemetry.SubmitTestResults RPC failed: {e}"))?;
        Ok(resp.into_inner().accepted)
    })
}

/// Submit release-op DAG rows to the server's `release_events`
/// (Telemetry.SubmitReleaseEvents) — the server holds the lock, so this is how a
/// fat-CLI `nornir release run` (executes on the dev's hardware) fills the live
/// 🚀 Release tab. Returns the accepted count.
#[cfg(any(feature = "mcp", feature = "server"))]
fn submit_release_remote(
    server: &str,
    rows: &[nornir::warehouse::release_events::ReleaseEventRow],
) -> Result<u32> {
    use pb_client::telemetry_client::TelemetryClient;
    use pb_client::{ReleaseEventPb, SubmitReleaseEventsRequest};
    let pb_rows: Vec<ReleaseEventPb> = rows
        .iter()
        .map(|r| ReleaseEventPb {
            run_id: r.run_id.clone(),
            seq: r.seq,
            ts_micros: r.ts_micros,
            component: r.component.clone(),
            repo: r.repo.clone(),
            op: r.op.clone(),
            phase: r.phase.clone(),
            status: r.status.clone(),
            detail: r.detail.clone(),
            // Preserve the Option: a flag distinguishes None from an empty list.
            has_depends_on: r.depends_on.is_some(),
            depends_on: r.depends_on.clone().unwrap_or_default(),
            has_elapsed_ms: r.elapsed_ms.is_some(),
            elapsed_ms: r.elapsed_ms.unwrap_or_default(),
        })
        .collect();
    on_server(server, move |channel, bearer| async move {
        let mut client = TelemetryClient::with_interceptor(channel, auth_interceptor(bearer));
        let resp = client.submit_release_events(SubmitReleaseEventsRequest { rows: pb_rows }).await
            .map_err(|e| anyhow!("Telemetry.SubmitReleaseEvents RPC failed: {e}"))?;
        Ok(resp.into_inner().accepted)
    })
}

/// Persist test rows: submit to the server (client mode, fills the live 🧪 Test
/// pane) or append the local warehouse (embedded). Mirrors [`persist_bakeoff`].
fn persist_test(
    loaded: &Loaded,
    rows: &[nornir::warehouse::test_results::TestResultRow],
) -> Result<()> {
    use nornir::warehouse::iceberg::IcebergWarehouse;
    use nornir::warehouse::test_results::{IcebergTestSink, TestSink};
    if rows.is_empty() {
        return Ok(());
    }
    #[cfg(any(feature = "mcp", feature = "server"))]
    if let Some(server) = server_target() {
        let n = submit_test_remote(&server, rows)?;
        println!("  → submitted {n} test row(s) to {server}");
        return Ok(());
    }
    let warehouse_root = loaded.warehouse_root();
    let wh = IcebergWarehouse::open(&warehouse_root)
        .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
    let sink = IcebergTestSink::new(&wh);
    sink.append(rows)?;
    Ok(())
}

/// Persist release-event rows: submit to the server (client mode, fills the live
/// 🚀 Release tab) or append the local warehouse (embedded). Mirrors
/// [`persist_bakeoff`]. Best-effort + non-fatal: a logging-row failure must
/// never abort a release run, so callers ignore the returned error.
fn persist_release_events(
    loaded: &Loaded,
    rows: &[nornir::warehouse::release_events::ReleaseEventRow],
) -> Result<()> {
    use nornir::warehouse::iceberg::IcebergWarehouse;
    use nornir::warehouse::release_events::append_release_events;
    if rows.is_empty() {
        return Ok(());
    }
    #[cfg(any(feature = "mcp", feature = "server"))]
    if let Some(server) = server_target() {
        submit_release_remote(&server, rows)?;
        return Ok(());
    }
    let warehouse_root = loaded.warehouse_root();
    let wh = IcebergWarehouse::open(&warehouse_root)
        .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
    wh.block_on(append_release_events(&wh, rows))?;
    Ok(())
}

/// Persist bake-off rows: submit to the server (client mode, fills the live
/// Leaderboard) or append the local warehouse (embedded). Mirrors `run_bench`.
fn persist_bakeoff(
    loaded: &Loaded,
    rows: &[nornir::warehouse::agent_model_runs::AgentModelRunRow],
) -> Result<()> {
    use nornir::warehouse::agent_model_runs::append_agent_model_runs;
    use nornir::warehouse::iceberg::IcebergWarehouse;
    if let Some(server) = server_target() {
        let n = submit_bakeoff_remote(&server, rows)?;
        println!("  → submitted {n} bake-off row(s) to {server}");
    } else {
        let warehouse_root = loaded.warehouse_root();
        let wh = IcebergWarehouse::open(&warehouse_root)
            .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
        wh.block_on(append_agent_model_runs(&wh, rows))?;
    }
    Ok(())
}

/// 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, WorkspaceFetchRequest, 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, lazy } => {
            if *monitored && *external {
                bail!("--monitored and --external are mutually exclusive");
            }
            let mode = if *monitored {
                "monitored"
            } else if *external {
                "external"
            } else {
                "pushed"
            }
            .to_string();
            // EAGER by default: the server fetches + builds inline so the returned
            // record carries the populated members + snapshot. `--lazy` opts back
            // out to the old record-only behaviour.
            let lazy = *lazy;
            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, lazy })
                    .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(),
                if lazy { " [lazy — populate on poll]" } else { " — populated" }
            );
        }
        WorkspaceOp::Add {
            name,
            descriptor,
            monitored,
            external,
            poll,
        } => {
            // Remote eager add = the eager register RPC: the server fetches
            // (clones members) + builds the warehouse inline and returns the
            // populated record. `add` is now just an explicit alias for the
            // default-eager `register`.
            run_workspace_remote(
                server,
                &WorkspaceOp::Register {
                    name: name.clone(),
                    descriptor: descriptor.clone(),
                    monitored: *monitored,
                    external: *external,
                    poll: poll.clone(),
                    lazy: false,
                },
            )?;
            println!("✓ added `{name}` on {server} — populated now (eager register).");
        }
        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, force } => {
            let name = name.clone();
            let force = *force;
            let rep = on_server(server, move |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                let resp = c
                    .fetch(WorkspaceFetchRequest { name, force, background: false })
                    .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
            );
        }
        WorkspaceOp::Populate { name } => {
            let name = name.clone();
            // background=true → the server clones the members and returns NOW; the
            // poll loop builds the warehouse in the background (single writer).
            // Instant populate; watch progress with `nornir workspace status`.
            let rep = on_server(server, move |channel, bearer| async move {
                let mut c = WorkspacesClient::with_interceptor(channel, auth_interceptor(bearer));
                let resp = c
                    .fetch(WorkspaceFetchRequest { name, force: false, background: true })
                    .await
                    .map_err(|e| anyhow!("Workspaces.Fetch RPC failed: {e}"))?;
                Ok(resp.into_inner())
            })?;
            for e in &rep.errors {
                eprintln!("    {e}");
            }
            println!(
                "✓ populated `{}` — {} member(s) cloned; warehouse building in background \
                 (watch `nornir workspace status {}`)",
                rep.workspace,
                rep.fetched,
                rep.workspace,
            );
        }
    }
    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(())
    })
}

/// Render+export a doc (`README`) or the whole `book` on the **server** via
/// `Docs.Export` / `Docs.Book`. The server owns the docs tree and the warehouse,
/// so a thin client (e.g. against oden) gets a real render + historize without
/// the sources on the local disk — and the server resolves sibling path-deps
/// first (DR1) so a path-dep'd repo like nornir renders. `which` is `"export"`
/// or `"book"`. Mirrors the local `run_docs_export`/`run_docs_book` output.
#[cfg(any(feature = "mcp", feature = "server"))]
fn docs_export_remote(server: &str, which: &str, repo: &str, format: &str) -> Result<()> {
    use pb_client::docs_client::DocsClient;
    use pb_client::DocsExportRequest;
    let (which, repo, format) = (which.to_string(), repo.to_string(), format.to_string());
    on_server(server, move |channel, bearer| async move {
        let mut c = DocsClient::with_interceptor(channel, auth_interceptor(bearer));
        let req = DocsExportRequest { repo: repo.clone(), format: format.clone() };
        let resp = match which.as_str() {
            "book" => c.book(req).await,
            "export" => c.export(req).await,
            other => return Err(anyhow!("docs `{other}` is not server-routable")),
        }
        .map_err(|e| anyhow!("Docs.{which} RPC failed: {e}"))?
        .into_inner();
        if which == "book" && !resp.sources.is_empty() {
            println!("assembled {} source(s) into the book:", resp.sources.len());
            for s in &resp.sources {
                println!("  + {s}");
            }
        }
        println!("wrote {} ({} bytes, format={})", resp.out, resp.bytes, resp.format);
        println!(
            "historized {} ({} bytes, sha256 {}…, git {})",
            which,
            resp.bytes,
            &resp.sha256[..12.min(resp.sha256.len())],
            &resp.git_sha[..resp.git_sha.len().min(12)],
        );
        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(())
    })
}

/// Owned, `'static` mirror of [`MimirOp`] so the request can move into the async
/// closure `on_server` runs (the CLI enum borrows from `cli`).
#[cfg(any(feature = "mcp", feature = "server"))]
enum MimirOpRemote {
    DepsOf { repo: String, transitive: bool },
    DependentsOf { repo: String, transitive: bool },
    Affected { repos: Vec<String> },
    BuildOrder,
    DepPath { from: String, to: String },
    ExternalUsers { krate: String },
    Svg,
    Overview { repo: String },
    Changed,
}

impl MimirOp {
    #[cfg(any(feature = "mcp", feature = "server"))]
    fn clone_for_remote(&self) -> MimirOpRemote {
        match self {
            MimirOp::DepsOf { repo, transitive } => {
                MimirOpRemote::DepsOf { repo: repo.clone(), transitive: *transitive }
            }
            MimirOp::DependentsOf { repo, transitive } => {
                MimirOpRemote::DependentsOf { repo: repo.clone(), transitive: *transitive }
            }
            MimirOp::Affected { repos } => MimirOpRemote::Affected { repos: repos.clone() },
            MimirOp::BuildOrder => MimirOpRemote::BuildOrder,
            MimirOp::DepPath { from, to } => {
                MimirOpRemote::DepPath { from: from.clone(), to: to.clone() }
            }
            MimirOp::ExternalUsers { krate } => {
                MimirOpRemote::ExternalUsers { krate: krate.clone() }
            }
            MimirOp::Svg => MimirOpRemote::Svg,
            MimirOp::Overview { repo } => MimirOpRemote::Overview { repo: repo.clone() },
            MimirOp::Changed => MimirOpRemote::Changed,
        }
    }
}

/// Run a `Mimir` op against a running server — one RPC per op. The server returns
/// the SAME JSON the embedded `mimir` lib computes; we pretty-print it (svg
/// carries raw SVG flowchart text in the `json` field, printed verbatim).
#[cfg(any(feature = "mcp", feature = "server"))]
fn run_mimir_remote(server: &str, op: &MimirOp) -> Result<()> {
    use pb_client::mimir_client::MimirClient;
    use pb_client::{AffectedQuery, CrateQuery, DepPathQuery, DepQuery, Empty, RepoOnly};

    let op = op.clone_for_remote();
    let json = on_server(server, move |channel, bearer| async move {
        let mut c = MimirClient::with_interceptor(channel, auth_interceptor(bearer));
        let r = match op {
            MimirOpRemote::DepsOf { repo, transitive } => {
                c.deps_of(DepQuery { repo, transitive }).await
            }
            MimirOpRemote::DependentsOf { repo, transitive } => {
                c.dependents_of(DepQuery { repo, transitive }).await
            }
            MimirOpRemote::Affected { repos } => c.affected_by_change(AffectedQuery { repos }).await,
            MimirOpRemote::BuildOrder => c.build_order(Empty {}).await,
            MimirOpRemote::DepPath { from, to } => c.dep_path(DepPathQuery { from, to }).await,
            MimirOpRemote::ExternalUsers { krate } => c.external_dep_users(CrateQuery { krate }).await,
            MimirOpRemote::Svg => c.svg(Empty {}).await,
            MimirOpRemote::Overview { repo } => c.repo_overview(RepoOnly { repo }).await,
            MimirOpRemote::Changed => c.changed_since_last_release(Empty {}).await,
        };
        Ok(r.map_err(|e| anyhow!("Mimir RPC failed: {e}"))?.into_inner().json)
    })?;
    // svg is raw text; everything else is JSON — pretty-print when it parses.
    match serde_json::from_str::<serde_json::Value>(&json) {
        Ok(v) => println!("{}", serde_json::to_string_pretty(&v)?),
        Err(_) => println!("{json}"),
    }
    Ok(())
}

/// Fetch the viz `Timeline` from the server's `Viz.Timeline` RPC (deserializes the
/// model's serde shape), so `nornir diagram` works in client mode.
#[cfg(any(feature = "mcp", feature = "server"))]
fn diagram_timeline_remote(server: &str, workspace: &str) -> Result<nornir::viz::Timeline> {
    use pb_client::viz_client::VizClient;
    use pb_client::VizTimelineRequest;

    let workspace = workspace.to_string();
    let json = on_server(server, move |channel, bearer| async move {
        let mut c = VizClient::with_interceptor(channel, auth_interceptor(bearer));
        let r = c
            .timeline(VizTimelineRequest { workspace })
            .await
            .map_err(|e| anyhow!("Viz.Timeline RPC failed: {e}"))?;
        Ok(r.into_inner().json)
    })?;
    serde_json::from_str(&json).context("deserialize Timeline from Viz.Timeline")
}

#[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(all(feature = "docs-export", not(any(feature = "mcp", feature = "server"))))]
fn docs_export_remote(_s: &str, _which: &str, _repo: &str, _format: &str) -> 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::repo_dir_resolved(&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) => {
            // Client mode (NORNIR_SERVER set): run the benches server-side over
            // the monitored checkout via Ops.RunBench (the viz 📈 "Run bencher"
            // twin) — the server has the checkout + the warehouse lock. Else run
            // locally and submit. (Fixes the reported thin `nornir bench` gap.)
            if let Some(server) = server_target() {
                return run_bench_remote(&server, &a.repo);
            }
            let _repo = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::repo_dir_resolved(&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(())
}

/// C6 test-matrix CLI: run native tests + persist to `test_results`, or read the
/// matrix back. Mirrors `run_bench`'s subprocess-then-persist shape.
fn run_test(op: TestOp, loaded: &Loaded) -> Result<()> {
    use nornir::warehouse::iceberg::IcebergWarehouse;
    use nornir::warehouse::test_results::{
        query_test_results, render_matrix, rows_to_json, summarize_runs, TestSelector,
    };

    match op {
        TestOp::Run(a) => {
            // Client mode (NORNIR_SERVER set): run server-side over the monitored
            // checkout via Ops.RunTestMatrix (the viz 🧪 "Run repo" twin); else
            // run locally. Embedded-XOR-client, mirroring `bench run`.
            if let Some(server) = server_target() {
                return run_test_matrix_remote(&server, &a.repo, a.aspects.as_deref().unwrap_or(""));
            }
            let _repo = repo_or_err(loaded, &a.repo)?;
            let aspects = parse_aspects_arg(a.aspects.as_deref())?;
            run_test_one(loaded, &a.repo, &aspects)?;
        }
        TestOp::All(a) => {
            // Client mode: the FULL matrix server-side (the viz 🧪 "Run full
            // matrix" twin); empty repo = every repo.
            if let Some(server) = server_target() {
                return run_test_matrix_remote(&server, "", a.aspects.as_deref().unwrap_or(""));
            }
            let aspects = parse_aspects_arg(a.aspects.as_deref())?;
            let repos: Vec<String> = loaded.nornir.repo.keys().cloned().collect();
            if repos.is_empty() {
                println!("no repos configured in nornir.toml");
                return Ok(());
            }
            let aspect_labels: Vec<&str> = aspects.iter().map(|a| a.label()).collect();
            println!(
                "▶ full aspect matrix [{}] across {} repo(s): {}",
                aspect_labels.join(","),
                repos.len(),
                repos.join(", "),
            );
            // Collect one outcome grid cell per (repo, aspect) for the terminal grid.
            let mut grid: Vec<(String, Vec<(nornir::test_matrix::Aspect, String)>)> = Vec::new();
            let mut any_red = false;
            for repo in &repos {
                match run_test_one(loaded, repo, &aspects) {
                    Ok((green, cells)) => {
                        any_red |= !green;
                        grid.push((repo.clone(), cells));
                    }
                    Err(e) => {
                        eprintln!("{repo}: {e:#}");
                        any_red = true;
                        grid.push((repo.clone(), Vec::new()));
                    }
                }
            }
            print!("{}", render_aspect_grid(&grid, &aspects));
            if any_red {
                anyhow::bail!("test matrix had red runs (see above)");
            }
        }
        TestOp::List(a) => {
            run_test_list(loaded, &a)?;
        }
        TestOp::History(a) => {
            let warehouse_root = loaded.warehouse_root();
            // Read-only + lock-tolerant: coexist with a live server holding the
            // catalog lock (copied-aside snapshot) — same as `release events`.
            let wh = IcebergWarehouse::open_read_only(&warehouse_root)
                .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
            // Try as a repo first; if empty, treat the selector as a run id.
            let by_repo =
                wh.block_on(query_test_results(&wh, &TestSelector::Repo(a.repo.clone())))?;
            let mut rows = if by_repo.is_empty() {
                wh.block_on(query_test_results(&wh, &TestSelector::Run(a.repo.clone())))?
            } else {
                by_repo
            };
            // Cap to the N most recent runs if asked.
            if a.limit > 0 {
                let keep: std::collections::HashSet<String> = summarize_runs(&rows)
                    .into_iter()
                    .take(a.limit)
                    .map(|s| s.run_id)
                    .collect();
                rows.retain(|r| keep.contains(&r.run_id));
            }
            if a.json {
                println!("{}", rows_to_json(&rows));
            } else if rows.is_empty() {
                println!(
                    "no test runs for `{}` yet — run `nornir test {}` first",
                    a.repo, a.repo
                );
            } else {
                print!("{}", render_matrix(&rows));
            }
        }
        TestOp::Coverage(a) => {
            run_test_coverage(loaded, &a)?;
        }
    }
    Ok(())
}

/// autonom completeness-gate CLI: discover the surface, difference it against
/// coverage + the allowlist, persist the verdict, and exit red on any gap or
/// stale allowlist entry. `--seed-allowlist` rewrites the allowlist instead.
fn run_test_coverage(loaded: &Loaded, a: &TestCoverageArgs) -> Result<()> {
    use nornir::autonom;
    use nornir::warehouse::iceberg::IcebergWarehouse;

    let workspace = loaded.workspace_name();
    let repo = a.repo.clone().unwrap_or_else(|| workspace.clone());

    // Discover the CLI subcommand surface from clap (anti-drift: the actual
    // registered subcommands, never a hand list).
    let cli_commands: Vec<String> = Cli::command()
        .get_subcommands()
        .map(|c| c.get_name().to_string())
        .collect();
    let inputs = autonom::nornir_surface_inputs(cli_commands);

    let warehouse_root = loaded.warehouse_root();
    let wh = IcebergWarehouse::open(&warehouse_root)
        .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;

    // The checked-in allowlist lives in the repo's `.nornir/autonom-allow.toml`.
    let repo_root = loaded.nornir.repo_dir_for(&loaded.workspace_root, &repo);
    let allowlist_path = autonom::allowlist_path(&repo_root);
    let allowlist = autonom::load_allowlist(&allowlist_path)?;

    let run_id = nornir::warehouse::test_results::new_run_id();
    let state = autonom::gather(&wh, &workspace, &repo, &inputs, allowlist, &run_id)?;

    if a.seed_allowlist {
        let seeded = autonom::reseed(&state);
        autonom::save_allowlist(&allowlist_path, &seeded)?;
        println!(
            "✓ seeded {}{} allowlist entr{} (every currently-uncovered surface). \
             Burn it down by deleting entries as tests land.",
            allowlist_path.display(),
            seeded.entries.len(),
            if seeded.entries.len() == 1 { "y" } else { "ies" },
        );
        return Ok(());
    }

    // Persist this run's verdict to surface_coverage.
    autonom::persist(&wh, &state, &run_id, &workspace)?;

    if a.json {
        let rows = autonom::read_run(&wh, &run_id)?;
        println!("{}", serde_json::to_string_pretty(&rows)?);
        if !state.report.is_green() {
            anyhow::bail!("autonom gate RED: {}", state.report.summary());
        }
        return Ok(());
    }

    println!("autonom completeness gate · workspace `{workspace}` · repo `{repo}`");
    println!("  {}", state.report.summary());
    if !state.report.gap.missing.is_empty() {
        println!("  GAP (uncovered + un-allowlisted) — wire a test or allowlist with a reason:");
        for n in &state.report.gap.missing {
            println!("{}", n.key_str());
        }
    }
    if !state.report.stale.is_empty() {
        println!("  STALE allowlist entries (now covered or surface-gone) — DELETE them:");
        for e in &state.report.stale {
            println!("{}  ({})", e.key, e.reason);
        }
    }
    if state.report.is_green() {
        println!("  GREEN ⟺ every surface is wired (or allowlisted with a live reason).");
    } else {
        anyhow::bail!(
            "autonom gate RED: {} missing, {} stale — run `nornir test coverage --seed-allowlist` \
             to excuse the current gap, then burn it down",
            state.report.gap.missing.len(),
            state.report.stale.len(),
        );
    }
    Ok(())
}

/// `nornir test list` — print the BUILD-FREE tri-state matrix (`ok | fail | X`)
/// for one or every repo: the `test_inventory` ⟕ `test_results` join. Discovery
/// rode the syn knowledge scan (no `cargo build`); a discovered test with no run
/// result shows `X` (not-run). This is the CLI twin of the viz 🧪 Test pane (CLI
/// parity). Thin mode (`--server`) reads the same join over `Viz.TestMatrix`.
fn run_test_list(loaded: &Loaded, a: &TestListArgs) -> Result<()> {
    use nornir::warehouse::test_inventory::TestMatrixRow;

    // Which repos to list: the requested one, else every configured repo.
    let repos: Vec<String> = match &a.repo {
        Some(r) => vec![r.clone()],
        None => loaded.nornir.repo.keys().cloned().collect(),
    };

    // Gather the matrix rows (thin via Viz.TestMatrix, else embedded warehouse).
    let mut rows: Vec<TestMatrixRow> = if let Some(server) = server_target() {
        let token = std::env::var("NORNIR_SERVER_TOKEN").unwrap_or_default();
        let workspace = std::env::var("NORNIR_WORKSPACE").unwrap_or_default();
        let (inventory, results) =
            nornir::viz::remote::fetch_test_matrix(&server, &token, &workspace)?;
        let all = nornir::warehouse::test_inventory::join_matrix(&inventory, &results);
        // Scope to the requested repo when one was named (the RPC returns all).
        match &a.repo {
            Some(r) => all.into_iter().filter(|m| &m.repo == r).collect(),
            None => all,
        }
    } else {
        let warehouse_root = loaded.warehouse_root();
        let wh = nornir::warehouse::iceberg::IcebergWarehouse::open_read_only(&warehouse_root)
            .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
        let mut out = Vec::new();
        for repo in &repos {
            out.extend(nornir::warehouse::test_inventory::query_test_matrix(&wh, repo)?);
        }
        out
    };

    // Apply the filters.
    if a.heavy_only {
        rows.retain(|r| r.is_heavy);
    }
    if a.not_run {
        rows.retain(|r| r.state == "X");
    }

    if a.json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(());
    }

    if rows.is_empty() {
        println!(
            "no tests discovered for [{}] yet — add/republish the workspace so the syn knowledge \
             scan inventories every #[test] (build-free), then they show here as X until run.",
            repos.join(", ")
        );
        return Ok(());
    }

    let ok = rows.iter().filter(|r| r.state == "ok").count();
    let fail = rows.iter().filter(|r| r.state == "fail").count();
    let not_run = rows.iter().filter(|r| r.state == "X").count();
    let heavy = rows.iter().filter(|r| r.is_heavy).count();
    println!(
        "🧪 test matrix — {ok} ok · {fail} fail · {not_run} X (not run) · {heavy} heavy  ({} discovered)",
        rows.len()
    );
    for r in &rows {
        let glyph = match r.state.as_str() {
            "ok" => "ok  ",
            "fail" => "fail",
            _ => "X   ",
        };
        let heavy_tag = if r.is_heavy { " [heavy]" } else { "" };
        let msg = if r.message.is_empty() { String::new() } else { format!("{}", r.message) };
        println!("  {glyph}  {}::{}::{}{heavy_tag}{msg}", r.repo, r.suite, r.test_name);
    }
    Ok(())
}

/// Parse the `--aspects` CLI arg into an [`Aspect`] list, defaulting to the
/// sensible set when absent/empty. Errors on an unknown aspect name.
fn parse_aspects_arg(arg: Option<&str>) -> Result<Vec<nornir::test_matrix::Aspect>> {
    use nornir::test_matrix::{parse_aspect, Aspect};
    let Some(s) = arg.map(str::trim).filter(|s| !s.is_empty()) else {
        return Ok(Aspect::DEFAULT.to_vec());
    };
    let mut out = Vec::new();
    for tok in s.split(',').map(str::trim).filter(|t| !t.is_empty()) {
        match parse_aspect(tok) {
            Some(a) => {
                if !out.contains(&a) {
                    out.push(a);
                }
            }
            None => anyhow::bail!(
                "unknown aspect `{tok}` — valid: build,unit,doctest,clippy,fmt,audit,\
                 bench-smoke,coverage,feature-powerset,msrv,examples"
            ),
        }
    }
    if out.is_empty() {
        anyhow::bail!("--aspects given but no valid aspect parsed");
    }
    Ok(out)
}

/// Run one repo's **multi-aspect** matrix (EPIC L) and persist every row via the
/// warehouse `TestSink`. Returns `(green, grid_cells)` where `green` is true iff
/// no row is red and `grid_cells` is one `(aspect, status)` per aspect for the
/// `test all` terminal grid.
fn run_test_one(
    loaded: &Loaded,
    repo: &str,
    aspects: &[nornir::test_matrix::Aspect],
) -> Result<(bool, Vec<(nornir::test_matrix::Aspect, String)>)> {
    use nornir::test_matrix::{detect_runner, list_tests, outcome_to_rows, run_aspect, stall_secs};
    use nornir::warehouse::test_results::{listed_rows, new_run_id, status, TestResultRow};

    let repo_root = config::repo_dir_resolved(&loaded.workspace_root, repo);
    let stall = stall_secs();
    let labels: Vec<&str> = aspects.iter().map(|a| a.label()).collect();
    println!(
        "{repo}: aspects [{}] in {} (stall-watchdog {})",
        labels.join(","),
        repo_root.display(),
        if stall == 0 { "off".to_string() } else { format!("{stall}s") },
    );

    // One run id + timestamp across every aspect's rows.
    let run_id = new_run_id();
    let ts_micros = chrono::Utc::now().timestamp_micros();
    let mut rows: Vec<TestResultRow> = Vec::new();
    let mut cells: Vec<(nornir::test_matrix::Aspect, String)> = Vec::new();

    // ── PHASE 1: test inventory (n-001) ──────────────────────────────────
    // Discover EVERY `#[test]` via the runner's `list` (cargo nextest list /
    // cargo test -- --list) and seed one `listed` row per test BEFORE running
    // anything. A `listed` row with no later pass/fail in this run renders as
    // NotRun, so the 🧪 matrix shows every test that EXISTS, not just the ones
    // that ran. Discovery never hard-fails the run.
    let runner = detect_runner();
    match list_tests(&repo_root, runner) {
        Ok(names) => {
            let seeded = listed_rows(&names, &run_id, repo, ts_micros);
            println!("   📋 discovered {} test(s) ({})", seeded.len(), runner.label());
            rows.extend(seeded);
        }
        Err(e) => println!("   📋 test inventory skipped: {e}"),
    }

    for &aspect in aspects {
        let out = run_aspect(&repo_root, aspect);
        cells.push((aspect, out.status.clone()));
        let chip = match out.status.as_str() {
            status::PASS => "",
            status::SKIP => "",
            _ => "",
        };
        let metric_note = if out.metric != 0.0 { format!(" [{:.2}]", out.metric) } else { String::new() };
        println!("   {chip} {}{}{}", aspect.label(), out.message, metric_note);
        rows.extend(outcome_to_rows(&out, &run_id, repo, ts_micros));
    }

    if rows.is_empty() {
        println!("  (no rows produced for {repo})");
        return Ok((true, cells));
    }

    // Persist the rows: in client mode (`NORNIR_SERVER` set) ship them to the
    // server's `test_results` over Telemetry.SubmitTestResults so the live 🧪
    // Test pane fills; embedded mode appends the local warehouse. (Both paths in
    // `persist_test`, mirroring `persist_bakeoff`.)
    persist_test(loaded, &rows)?;

    let red = rows.iter().any(|r| status::is_red(&r.status));
    let mark = if red { "" } else { "" };
    let passed = rows.iter().filter(|r| r.status == status::PASS).count();
    let failed = rows.iter().filter(|r| r.status == status::FAIL).count();
    let stalled = rows.iter().filter(|r| r.status == status::STALLED).count();
    let skipped = rows.iter().filter(|r| r.status == status::SKIP).count();
    println!(
        "{mark} {repo}: {passed} passed · {failed} failed · {stalled} stalled · {skipped} skipped  ({} rows → run {})",
        rows.len(),
        &run_id[..8.min(run_id.len())],
    );
    for r in rows.iter().filter(|r| status::is_red(&r.status)) {
        let detail = if r.message.is_empty() { String::new() } else { format!("{}", r.message) };
        println!("  ✗ [{}] {}::{} {}{}", r.aspect, r.suite, r.test_name, r.status, detail);
    }
    Ok((!red, cells))
}

/// Render the `test all` per-repo×aspect terminal grid. One row per repo, one
/// column per aspect; ✓ green / ✗ red / ○ skip / · missing.
fn render_aspect_grid(
    grid: &[(String, Vec<(nornir::test_matrix::Aspect, String)>)],
    aspects: &[nornir::test_matrix::Aspect],
) -> String {
    use nornir::warehouse::test_results::status;
    if grid.is_empty() {
        return String::new();
    }
    let repo_w = grid.iter().map(|(r, _)| r.len()).max().unwrap_or(4).max(4);
    // Short, fixed-width aspect column headers.
    let headers: Vec<String> = aspects.iter().map(|a| short_aspect(a.label())).collect();
    let col_w = headers.iter().map(|h| h.len()).max().unwrap_or(3).max(3);

    let mut out = String::from("\n");
    // Header line.
    out.push_str(&format!("{:<repo_w$}", "repo", repo_w = repo_w));
    for h in &headers {
        out.push_str(&format!("  {:>col_w$}", h, col_w = col_w));
    }
    out.push('\n');
    for (repo, cells) in grid {
        out.push_str(&format!("{:<repo_w$}", repo, repo_w = repo_w));
        for a in aspects {
            let chip = cells
                .iter()
                .find(|(asp, _)| asp == a)
                .map(|(_, st)| match st.as_str() {
                    status::PASS => "",
                    status::SKIP => "",
                    _ if status::is_red(st) => "",
                    _ => "·",
                })
                .unwrap_or("·");
            out.push_str(&format!("  {:>col_w$}", chip, col_w = col_w));
        }
        out.push('\n');
    }
    out.push_str("\nlegend: ✓ pass · ✗ red (fail/stalled) · ○ skip (tool absent) · · not run\n");
    out
}

/// A compact column header for an aspect label (e.g. `feature-powerset` → `pwr`).
fn short_aspect(label: &str) -> String {
    match label {
        "build" => "bld",
        "unit" => "unt",
        "doctest" => "doc",
        "clippy" => "clp",
        "fmt" => "fmt",
        "audit" => "aud",
        "bench-smoke" => "bch",
        "coverage" => "cov",
        "feature-powerset" => "pwr",
        "msrv" => "msr",
        "examples" => "exa",
        other => other,
    }
    .to_string()
}

fn run_release(op: ReleaseOp, loaded: &Loaded) -> Result<()> {
    match op {
        ReleaseOp::GatePathPatches(a) => {
            let _ = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&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) => {
            // Client mode (NORNIR_SERVER set): run the release-grade gate
            // server-side via Ops.RunRelease (the viz 🚀 "Release (heavy gate)"
            // twin), persisting `release_events`. Empty repo = whole build order.
            if let Some(server) = server_target() {
                return run_release_remote(&server, &a.repo);
            }
            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, json } => {
            // Empty (default) = every workspace; the global `--workspace` narrows it.
            let workspace = env_workspace_or("");
            let warehouse_root = loaded.warehouse_root();
            // Read-only trace: tolerate a live server holding the catalog lock
            // (copied-aside snapshot fallback) rather than deadlocking on it.
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open_read_only(&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::Events { selector, json } => {
            use nornir::warehouse::release_events::{
                query_release_events, render_topo, rows_to_json, EventSelector,
            };
            let warehouse_root = loaded.warehouse_root();
            // Read-only, lock-tolerant: coexist with a live server holding the
            // catalog lock (copied-aside snapshot) instead of deadlocking.
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open_read_only(&warehouse_root)
                .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
            // Try the selector as an exact run_id first; if no rows carry it,
            // fall back to treating it as a repo name. This makes
            // `nornir release events <repo|run_id>` Just Work either way.
            let by_run = wh
                .block_on(query_release_events(&wh, &EventSelector::Run(selector.clone())))?;
            let rows = if by_run.is_empty() {
                wh.block_on(query_release_events(&wh, &EventSelector::Repo(selector.clone())))?
            } else {
                by_run
            };
            if json {
                println!("{}", rows_to_json(&rows));
            } else if rows.is_empty() {
                println!(
                    "no release events for `{selector}` (not a known run_id or repo, or no \
                     `nornir release run` has recorded events yet)"
                );
            } else {
                print!("{}", render_topo(&rows));
            }
        }
        ReleaseOp::Publish(a) => {
            let repo = repo_or_err(loaded, &a.repo)?;
            let repo_root = config::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&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::repo_dir_resolved(&loaded.workspace_root, &repo);
            let md = release::cargo::changelog_markdown(&repo_root, &range)?;
            print!("{md}");
        }
        ReleaseOp::ImpactedCrates { repo, base } => {
            let repo_root = config::repo_dir_resolved(&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.
            // Read-only dep-graph query: tolerate a live server's catalog lock.
            let warehouse_root = loaded.warehouse_root();
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open_read_only(&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::repo_dir_resolved(&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, holger_token } => {
            let repo_root = config::repo_dir_resolved(&loaded.workspace_root, &repo);
            let tok = holger_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::repo_dir_resolved(&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_read_only(&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> {
    // Read-only: the latest run feeds gates/docs. Tolerate a live server
    // holding the catalog lock (snapshot-copy fallback) instead of aborting.
    let wh = warehouse::open_read_only(&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::repo_dir_resolved(&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::repo_dir_resolved(&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;

    // Workspace to filter dep_graph snapshots: global `--workspace` / env, else
    // the historical default keyed in the iceberg rows.
    let workspace = env_workspace_or("workspace_holger");

    // 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: 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 warehouse_root = loaded.warehouse_root();
    // Read-only dep-graph load for topo-ordering: tolerate a live server's
    // catalog lock via the copied-aside snapshot fallback.
    let wh = IcebergWarehouse::open_read_only(&warehouse_root)
        .with_context(|| format!("open iceberg warehouse at {}", warehouse_root.display()))?;
    let snapshots = wh
        .block_on(query_dep_graph_snapshots(&wh, &workspace, None))
        .with_context(|| format!("query dep_graph_edges for workspace `{}`", 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",
                workspace
            );
            selected.clone()
        }
    };
    println!("▶ release run order: {}", order.join(""));

    // Release-op DAG emitter (B2, fat-CLI path). Keyed by this run's id so its
    // events group together. `depends_on` for a repo is the set of in-workspace
    // producers it consumes (edge `from == repo` ⇒ `to` is the dependency),
    // taken from the same dep-graph snapshot that ordered the run. Emits are
    // best-effort + non-fatal (a logging-row failure must not abort a release).
    use nornir::warehouse::release_events::{
        phase as ev_phase, status as ev_status, ReleaseEventEmitter,
    };
    let events = ReleaseEventEmitter::new(run_id.clone());
    // Server mode: the per-emit `append_release_events(&wh, …)` can't reach the
    // locked server warehouse (our `wh` is read-only), so the emitter buffers
    // every row and this guard ships the whole run over `Telemetry.
    // SubmitReleaseEvents` when `run_release_run` returns — on EVERY exit path
    // (success, `?`, or a phase `bail!`), so a partial/failed release still fills
    // the live 🚀 Release tab. Embedded mode is a no-op (the emit already wrote
    // the local warehouse). Best-effort + non-fatal.
    struct ReleaseEventFlush<'a> {
        loaded: &'a Loaded,
        events: &'a ReleaseEventEmitter,
    }
    impl Drop for ReleaseEventFlush<'_> {
        fn drop(&mut self) {
            if server_target().is_none() {
                return; // embedded: emit already appended the local warehouse
            }
            let rows = self.events.recorded_rows();
            if rows.is_empty() {
                return;
            }
            match persist_release_events(self.loaded, &rows) {
                Ok(()) => println!(
                    "  → submitted {} release event(s) to the server",
                    rows.len()
                ),
                Err(e) => eprintln!("  ⚠ release_events submit failed (non-fatal): {e:#}"),
            }
        }
    }
    let _release_event_flush = ReleaseEventFlush { loaded, events: &events };
    let dep_edges: Vec<nornir::warehouse::dep_graph::CrossRepoEdge> =
        latest.as_ref().map(|s| s.edges.clone()).unwrap_or_default();
    let deps_of = |repo: &str| -> Vec<String> {
        let mut d: Vec<String> = dep_edges
            .iter()
            .filter(|e| e.from == repo && e.to != repo)
            .map(|e| e.to.clone())
            .collect();
        d.sort();
        d.dedup();
        d
    };
    events.emit(
        &wh, &workspace, "", "run", ev_phase::START, ev_status::RUNNING,
        &format!("order: {}", order.join("")), None, None,
    );

    // 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::repo_dir_resolved(&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(),
            });
        }

        // Dep-graph producers this repo waited on (the DAG edges for its events).
        let deps = deps_of(name);

        if !args.skip_tests {
            let t0 = std::time::Instant::now();
            events.emit(
                &wh, name, name, "test", ev_phase::START, ev_status::RUNNING, "",
                Some(deps.clone()), None,
            );
            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");
            events.emit(
                &wh, name, name, "test", ev_phase::END,
                if ok { ev_status::OK } else { ev_status::FAIL },
                &format!("{passed} passed, {failed} failed"),
                Some(deps.clone()),
                Some(t0.elapsed().as_millis() as i64),
            );
            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,
                    });
                }
                events.emit(
                    &wh, &workspace, "", "run", ev_phase::END, ev_status::FAIL,
                    &format!("aborted at `{name}` test phase"), None, None,
                );
                bail!("`{name}` test phase failed — aborting release run");
            }
        } else {
            events.emit(
                &wh, name, name, "test", ev_phase::SKIP, ev_status::WARN, "--skip-tests",
                Some(deps.clone()), None,
            );
            println!("  tests: skipped (--skip-tests)");
        }

        if !args.skip_bench {
            println!("  ⚡ running nornir-bench in {}", repo_root.display());
            let b0 = std::time::Instant::now();
            events.emit(
                &wh, name, name, "bench", ev_phase::START, ev_status::RUNNING, "",
                Some(deps.clone()), None,
            );
            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)");
                    events.emit(
                        &wh, name, name, "bench", ev_phase::END, ev_status::WARN,
                        "no examples/nornir-bench.rs", Some(deps.clone()),
                        Some(b0.elapsed().as_millis() as i64),
                    );
                }
                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()
                            );
                        }
                        events.emit(
                            &wh, name, name, "bench", ev_phase::END, ev_status::FAIL,
                            &format!("{n_failed} failing bench test(s)"), Some(deps.clone()),
                            Some(b0.elapsed().as_millis() as i64),
                        );
                        events.emit(
                            &wh, &workspace, "", "run", ev_phase::END, ev_status::FAIL,
                            &format!("aborted at `{name}` bench phase"), None, None,
                        );
                        bail!("`{name}` bench reported {n_failed} failing test(s) — aborting");
                    }
                    events.emit(
                        &wh, name, name, "bench", ev_phase::END, ev_status::OK,
                        &format!("{} result(s)", run.results.len()), Some(deps.clone()),
                        Some(b0.elapsed().as_millis() as i64),
                    );
                }
            }
        } 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
            let g0 = std::time::Instant::now();
            events.emit(
                &wh, name, name, "gate", ev_phase::START, ev_status::RUNNING, "gate-all",
                Some(deps.clone()), None,
            );
            let gate_res = run_gate_all(loaded, name)
                .with_context(|| format!("gate-all for `{name}`"));
            events.emit(
                &wh, name, name, "gate", ev_phase::END,
                if gate_res.is_ok() { ev_status::OK } else { ev_status::FAIL },
                if gate_res.is_ok() { "all gates passed" } else { "gate failed" },
                Some(deps.clone()),
                Some(g0.elapsed().as_millis() as i64),
            );
            gate_res?;
        } 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,
                    &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, &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, &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(),
                });
            }
            events.emit(
                &wh, name, name, "publish", ev_phase::START, ev_status::RUNNING,
                if args.dry_run_publish { "dry-run" } else { "" },
                Some(deps.clone()), None,
            );
            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,
                });
            }
            events.emit(
                &wh, name, name, "publish", ev_phase::END,
                if pub_ok { ev_status::OK } else { ev_status::FAIL },
                if pub_ok { "published" } else { "publish failed" },
                Some(deps.clone()),
                Some(t0.elapsed().as_millis() as i64),
            );
            if !pub_ok {
                if let Some(p) = &progress_end {
                    p.emit(&ReleaseEvent::RunEnd {
                        ts: now(),
                        run_id: run_id_for_end.clone(),
                        ok: false,
                    });
                }
                events.emit(
                    &wh, &workspace, "", "run", ev_phase::END, ev_status::FAIL,
                    &format!("aborted at `{name}` publish phase"), None, None,
                );
                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,
            &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:#}"),
        }
    }

    events.emit(
        &wh, &workspace, "", "run", ev_phase::END, ev_status::OK,
        &format!("{} repo(s) green", order.len()), None, None,
    );
    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,
                )
            }
            // Book/Export render on the server too (it owns the docs tree + the
            // warehouse, and resolves sibling path-deps first — DR1). `--out`
            // is a local-only convenience and is not honoured in client mode.
            #[cfg(feature = "docs-export")]
            DocsOp::Export(a) => return docs_export_remote(&server, "export", &a.repo.repo, &a.format),
            #[cfg(feature = "docs-export")]
            DocsOp::Book(a) => return docs_export_remote(&server, "book", &a.repo.repo, &a.format),
            _ => {}
        }
    }
    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
    // Honor an explicit `[repo.<name>].path` override, then tolerate a case
    // mismatch between the `[repo.<name>]` key and the on-disk directory (e.g.
    // `[repo.njord]` ↔ a `Njord/` checkout). The override is what lets
    // `docs book nornir` render nornir's *own* book from a configured
    // `nornir-orch` worktree (`[repo.nornir] path = "nornir-orch"`) instead of
    // silently resolving to the by-name `<workspace_root>/nornir` checkout.
    let repo_root = loaded.nornir.repo_dir_for(&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);

    // What this repo asks `render` to emit (`.nornir/docs.toml`; default markdown).
    let cfg = docs::DocsRenderCfg::load(&layout)?;

    if cfg.wants_markdown() {
        let reports = docs::render_all(&layout, &ctx)?;
        if reports.is_empty() {
            // A hard "nothing to do" only when markdown was the sole request;
            // with `outputs = ["pdf"]` an empty managed-doc set is expected.
            if !cfg.wants_pdf() {
                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" }
            );
        }

        // Fill `nornir:gen:*` markers (notably `depgraph`) in place for the
        // non-managed `.nornir/*.md` sources — design.md, plan.md, … — which are
        // published as-is and would otherwise carry empty/invisible marker blocks.
        let src_reports = docs::render_sources_in_place(&layout, &ctx)?;
        for r in &src_reports {
            let verb = if r.changed { "wrote" } else { "unchanged" };
            println!(
                "{verb}: {} ({} section{})",
                r.path.display(),
                r.sections.len(),
                if r.sections.len() == 1 { "" } else { "s" }
            );
        }
    }

    if cfg.wants_pdf() {
        #[cfg(feature = "docs-export")]
        {
            render_book_pdf(&layout, &repo_root, &ctx)?;
        }
        #[cfg(not(feature = "docs-export"))]
        {
            anyhow::bail!(
                "{} requests `pdf` output, but this nornir was built without the \
                 `docs-export` feature. Reinstall with `cargo install nornir --features cli` \
                 (or `--features docs-export`).",
                docs::DocsRenderCfg::path(&layout).display()
            );
        }
    }

    Ok(())
}

/// Render the whole-documentation book to `<repo>/docs/book.pdf` as part of
/// `docs render` (driven by `outputs = ["pdf"]` in `.nornir/docs.toml`).
///
/// Unlike `docs book`, this does **not** historize into the Iceberg warehouse —
/// `render` is the lightweight "refresh the on-disk artifact" verb. It writes
/// only the PDF and never any markdown, so a repo's hand-edited `*.md` are left
/// untouched.
#[cfg(feature = "docs-export")]
fn render_book_pdf(
    layout: &docs::RepoLayout,
    repo_root: &std::path::Path,
    ctx: &docs::Ctx,
) -> Result<()> {
    let format = docs::DocFormat::parse("pdf")?;
    let (bytes, sources) = docs::build_book(repo_root, ctx, format)?;
    let out = layout.export_path("book", format.extension());
    if let Some(parent) = out.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&out, &bytes)?;
    println!(
        "wrote {} ({} bytes) from {} source(s):",
        out.display(),
        bytes.len(),
        sources.len()
    );
    for s in &sources {
        let shown = s.strip_prefix(repo_root).unwrap_or(s);
        println!("  + {}", shown.display());
    }
    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::repo_dir_resolved(&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::repo_dir_resolved(&loaded.workspace_root, &a.repo);
            let g = introspect::depgraph::extract(&repo_root)?;
            print!("{}", g.to_svg());
        }
        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::repo_dir_resolved(&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::repo_dir_resolved(&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 workspace = env_workspace_or("workspace_holger");
            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, &workspace, &sha, &branch);
            }
            let wh = nornir::warehouse::iceberg::IcebergWarehouse::open(
                &iceberg_warehouse_root(loaded),
            )?;
            let snap = nornir::index::snapshot::snapshot_to_iceberg(
                &wh,
                &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 workspace = env_workspace_or("workspace_holger");
            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, &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::repo_dir_resolved(&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_and_model(),
            );
            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)?,
        VectorOp::Bench(a) => run_vector_bench(&a),
    }
    Ok(())
}

/// `nornir vector bench` — time the CPU cosine kernels (G2) and print the
/// scalar/SIMD/int8 numbers, the speedups, and the int8 quantization error.
#[cfg(feature = "vector")]
fn run_vector_bench(a: &VectorBenchArgs) {
    use nornir::vector;
    println!(
        "vector cosine kernel bench — corpus {} × {} dim, {} iters",
        a.n, a.dim, a.iters
    );
    println!("  SIMD kernel: {}   int8 VNNI: {}", vector::active_simd(), vector::vnni_available());
    let rep = vector::bench_kernels(a.n, a.dim, a.iters);
    println!(
        "  {:<16} {:>10} {:>14} {:>12}",
        "kernel", "time", "throughput", "max_err"
    );
    for t in &rep.timings {
        println!(
            "  {:<16} {:>8}µs {:>10.1} Mdps {:>12.2e}",
            t.name, t.micros, t.mdps, t.max_err
        );
    }
    println!(
        "  speedup vs scalar — SIMD {:.2}×, int8 {:.2}×",
        rep.simd_speedup(),
        rep.int8_speedup()
    );
}

/// `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::repo_dir_resolved(&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)"
}

/// `"<backend>, model <name> (<dim>-dim)"` — surfaces the selected embedding
/// model (`$NORNIR_EMBED_MODEL` / registry default) alongside the backend.
#[cfg(feature = "vector")]
fn vector_backend_and_model() -> String {
    format!(
        "{}, model {}",
        vector_backend_name(),
        nornir::vector::selected_model_desc()
    )
}

#[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::repo_dir_resolved(&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 {
    // Same rule as `config::Loaded::warehouse_root`: absolute/relative
    // `[storage].local_path`, else the home-derived `<home>/.nornir/warehouse`.
    loaded.warehouse_root()
}

/// Funnel-store root for the CLI, resolved through the **shared**
/// [`funnel::Store::resolve_root`] precedence so a CLI-created funnel lands
/// exactly where the gRPC server / MCP read it (the E4 consistency fix):
/// explicit `--funnel-root` (none today) > config `[storage].local_path` >
/// the home-derived `<home>/.nornir/funnel`.
///
/// NB: this deliberately differs from [`iceberg_warehouse_root`] in the
/// no-`local_path` fallback: the funnel default is the home-derived
/// `<home>/.nornir/funnel` (matching the server's `FunnelStore::default_root`),
/// not the bench/dep-graph warehouse. Consistency with the *server* is what
/// makes the funnel visible in viz.
fn funnel_root(loaded: &Loaded) -> PathBuf {
    // Mirror `warehouse_root()`'s precedence: an explicit `[storage].local_path`
    // pin wins (shared with the warehouse dir), otherwise the PER-WORKSPACE
    // funnel `<home>/.nornir/workspaces/<name>/funnel` — not a global dir.
    if loaded.nornir.storage.local_path.is_empty() {
        loaded.funnel_root()
    } else {
        nornir::funnel::Store::resolve_root(
            &loaded.workspace_root,
            &loaded.nornir.storage.local_path,
            None,
        )
    }
}

/// 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" }
}