zc2 0.0.45

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
// `zc` is a binary crate (no external API consumers). It retains some reserved
// API surface (e.g. CreditManager helpers, snapshot accessors) and serde-bound
// fields that are part of JSON/wire contracts but not read by code paths in
// this build (e.g. discovery/response fields). Allow dead_code crate-wide
// rather than deleting serde-contract fields or future scaffolding; the genuine
// unused-import/variable noise was removed via `cargo fix` (audit M5).
#![allow(dead_code)]

extern crate serde;
extern crate toml;

use std::env;
#[cfg(unix)]
mod agent;
/// Stand-in for platforms without the agent: everything reports "not here".
#[cfg(not(unix))]
mod agent {
    pub fn run_cli(_: &[String], _: bool) -> i32 {
        eprintln!("zc agent is not supported on this platform yet");
        2
    }
    pub mod jobs_cli {
        pub fn run(_: &[String], _: bool) -> i32 {
            eprintln!("zc jobs needs the zc agent, which is not supported on this platform yet");
            2
        }
    }
    pub mod handoff {
        pub fn try_up(_: &[String]) -> Option<i32> {
            None
        }
        pub fn try_down() -> Option<i32> {
            None
        }
        pub fn try_price(_: crate::PriceCmd) -> Option<i32> {
            None
        }
        pub fn price_direct(_: crate::PriceCmd) -> i32 {
            eprintln!("zc price needs the hub client, which is not built on this platform yet");
            2
        }
    }
}
mod async_exec;
mod autobroker;
mod bench_node;
mod broker;
mod build_id;
mod common;
mod credentials;
mod dataset;
mod enroll;
mod envs;
mod exec;
mod hub_allocation;
mod infer;
mod init;
mod manager;
mod mesh;
mod mesh_dir;
mod model_uri;
mod profile;
mod sched;
mod serve;
mod serve_general;
mod session;
mod spaces;
mod ui;
mod up;
mod update;
mod verified_fetch;
mod vpn;
/// Re-exports of the shared zakuro-wire schema (RFC 0001).
mod wire;

#[cfg(test)]
mod integration_tests;

/// Name of the `zc hooks` helper binary that `zc hooks` execs.
///
/// It is a separate crate (`crates/zc-hooks`, `publish = false`) because it
/// owns the private `zakuro-client` git dependency, which would otherwise bar
/// `zc2` from crates.io entirely -- cargo rejects a manifest naming any git
/// source, optional included. See #104.
#[cfg(windows)]
const HOOKS_BIN: &str = "zc-hooks.exe";
/// See [`HOOKS_BIN`].
#[cfg(not(windows))]
const HOOKS_BIN: &str = "zc-hooks";

fn start_broker(host: Option<&str>, port: Option<u16>, daemon: bool) {
    use broker::BrokerConfig;
    use colored::Colorize;

    broker::apply_user_broker_defaults();
    let config = BrokerConfig {
        host: host.unwrap_or("0.0.0.0").to_string(),
        port: port.unwrap_or(9000),
        daemon,
        verbose: !daemon, // verbose in foreground mode
        enable_p2p: broker::p2p_default(),
        ..Default::default()
    };

    if daemon {
        // Daemon mode: minimal output, run in background
        println!("Broker starting on {}:{}...", config.host, config.port);

        // Fork to background using nohup-style approach
        // For true daemonization, we'd use fork() but this is simpler
        if let Err(e) = broker::start_server(config) {
            eprintln!("Broker error: {}", e);
            std::process::exit(1);
        }
    } else {
        // Foreground mode: show banner and live transactions
        println!();
        println!(
            "  {}",
            "╔═══════════════════════════════════════════╗".cyan()
        );
        println!(
            "  {}          {}            {}",
            "║".cyan(),
            "Zakuro Compute Broker".bold().white(),
            "║".cyan()
        );
        println!(
            "  {}",
            "╚═══════════════════════════════════════════╝".cyan()
        );
        println!();
        println!(
            "  {}  http://{}:{}",
            "Listening:".green(),
            config.host,
            config.port
        );
        match broker::hub_registration::disabled_reason(
            config.api_url.as_deref(),
            config.api_key.as_deref(),
        ) {
            None => println!(
                "  {}        {}",
                "Hub:".green(),
                config.api_url.as_deref().unwrap_or_default()
            ),
            Some(reason) => println!(
                "  {}        {} ({}) — this broker will NOT appear on the mesh; run `zc login`",
                "Hub:".red().bold(),
                "NOT REGISTERING".red().bold(),
                reason
            ),
        }
        println!();
        println!("  {}", "API Endpoints:".bold());
        println!(
            "  {}",
            "─────────────────────────────────────────────".dimmed()
        );
        println!("    {}  /health              Health check", "GET ".green());
        println!("    {}  /workers             List workers", "GET ".green());
        println!("    {} /workers             Register worker", "POST".blue());
        println!(
            "    {} /workers/heartbeat   Worker heartbeat",
            "POST".blue()
        );
        println!(
            "    {}  /workers/:id         Unregister worker",
            "DEL ".red()
        );
        println!("    {} /execute             Execute request", "POST".blue());
        println!("    {} /price               Estimate price", "POST".blue());
        println!("    {}  /credits/:user       Get balance", "GET ".green());
        println!("    {} /credits/:user/add   Add credits", "POST".blue());
        println!(
            "  {}",
            "─────────────────────────────────────────────".dimmed()
        );
        println!();
        println!("  Press {} to stop.", "Ctrl+C".yellow().bold());
        println!();

        // Start synchronous server with live transaction logging
        if let Err(e) = broker::start_server(config) {
            eprintln!("{} {}", "Broker error:".red(), e);
            std::process::exit(1);
        }
    }
}

fn launch() {
    manager::pull();
    manager::kill();
    manager::restart();
}
fn setup() {
    common::download_auth();
    common::download_conf();
    launch();
}

fn show_user_info(api_key: &str) {
    use colored::Colorize;
    use std::time::Duration;

    // Get API URL from environment or use production default
    let api_url = crate::credentials::default_api_url();

    // Create HTTP client
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(Duration::from_secs(10)))
            .timeout_global(Some(Duration::from_secs(10)))
            .build(),
    );

    // Call /api/auth/me/api-key endpoint (API key authentication)
    let endpoint = format!("{}/api/auth/me/api-key", api_url.trim_end_matches('/'));
    let response = match agent
        .get(&endpoint)
        .header("Authorization", &format!("Bearer {}", api_key))
        .call()
    {
        Ok(r) => r,
        Err(e) => {
            eprintln!("{} {}", "Failed to connect to API:".red(), e);
            eprintln!("  Endpoint: {}", endpoint);
            eprintln!();
            eprintln!("  Make sure:");
            eprintln!("  • ZAKURO_API_KEY is set to your API key");
            eprintln!("  • You have internet connectivity");
            eprintln!("  • API is reachable: {}", api_url);
            return;
        }
    };

    // Parse response
    if response.status().as_u16() != 200 {
        eprintln!("{} HTTP {}", "API error:".red(), response.status());
        if let Ok(body) = response.into_body().read_to_string() {
            eprintln!("  {}", body);
        }
        return;
    }

    let body = match response.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{} {}", "Failed to read response:".red(), e);
            return;
        }
    };

    // Parse JSON response
    let data: serde_json::Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{} {}", "Failed to parse response:".red(), e);
            return;
        }
    };

    // Display user info
    println!();
    if let Some(user_id) = data.get("zakuro_user_id").and_then(|v| v.as_str()) {
        println!("  {}  {}", "User ID:".bold(), user_id.cyan());
    }
    if let Some(username) = data.get("username").and_then(|v| v.as_str()) {
        println!("  {}  {}", "Username:".bold(), username);
    }
    if let Some(email) = data.get("email").and_then(|v| v.as_str()) {
        println!("  {}  {}", "Email:".bold(), email);
    }
    if let Some(balance) = data.get("credits_balance").and_then(|v| v.as_f64()) {
        println!(
            "  {}  {}",
            "Balance:".bold(),
            if balance >= 0.0 {
                format!("{:.4} credits", balance).green()
            } else {
                format!("{:.4} credits", balance).red()
            }
        );
    }
    if let Some(disabled) = data.get("disabled").and_then(|v| v.as_bool()) {
        println!(
            "  {}  {}",
            "Status:".bold(),
            if disabled {
                "Disabled".red()
            } else {
                "Active".green()
            }
        );
    }
    println!("  {}  {}", "API:".bold(), api_url.green());
    println!();
}

fn help(full: bool) {
    use colored::Colorize;

    println!();
    println!(
        "{}  {}",
        "zc".bold().cyan(),
        "— the zakuro compute client".dimmed()
    );
    println!("{}: zc [COMMAND]", "Usage".bold());
    println!(
        "       {}  (no command, in a terminal) opens the interactive session",
        "zc".cyan()
    );
    println!();

    println!("{}", "Start here".bold());
    println!(
        "      {}    First run: sign in, check this machine, choose what to share",
        "zc setup".cyan()
    );
    println!("      {}    Sign in with your browser", "zc login".cyan());
    println!(
        "      {} zakuro://…   Open a hub link from the terminal",
        "zc link".cyan()
    );
    println!("      {}       Your account & credits", "zc me".cyan());
    println!(
        "      {}   Check this machine (profile, container runtime)",
        "zc doctor".cyan()
    );
    println!();

    println!("{}", "Connect to the mesh".bold());
    println!(
        "      {}    Join the zakuro WireGuard mesh",
        "zc connect".cyan()
    );
    println!("      {} Leave the mesh", "zc disconnect".cyan());
    println!(
        "      {}     Show your connection & peer",
        "zc status".cyan()
    );
    println!();

    println!("{}", "Use compute".bold());
    println!("      {}        List available workers", "zc ls".cyan());
    println!(
        "      {}  Machine-readable listing (price + capabilities)",
        "zc ls --json".cyan()
    );
    println!(
        "      {}  Show each worker's estimate (median, observations)",
        "zc ls --estimate".cyan()
    );
    println!("      {}     Benchmark the mesh", "zc bench".cyan());
    println!(
        "      {} zc://<uuid> -m \"...\"   One-shot model inference",
        "zc infer".cyan()
    );
    println!(
        "      {} zc://<uuid> --file a.wav [--language xx]   Transcribe audio with a speech model",
        "zc infer".cyan()
    );
    println!(
        "      {} zc://<uuid>            Interactive chat with a model",
        "zc chat".cyan()
    );
    println!(
        "      {}  What this node runs for the hub's deployments",
        "zc deployments".cyan()
    );
    println!();

    println!("{}", "Share your machine".bold());
    println!(
        "      {}     Offer this machine to the mesh",
        "zc share".cyan()
    );
    println!(
        "      {} [N]  Offer N workers (default 1)",
        "zc share --workers".cyan()
    );
    println!(
        "      {} P   Price it, in zkcr/hour (default 3.6)",
        "zc share --price".cyan()
    );
    println!("      {}   Stop sharing", "zc unshare".cyan());
    println!(
        "      {}   Run the menu-bar/widget agent at login",
        "zc agent install".cyan()
    );
    println!(
        "      {}    What the agent is doing (add --json)",
        "zc agent status".cyan()
    );
    println!(
        "      {}      Jobs this node runs (--live to follow them)",
        "zc jobs".cyan()
    );
    println!(
        "      {}      What this Mac charges (also: inherit, default <c/h>, default mesh)",
        "zc price".cyan()
    );
    println!(
        "      {}   Host Spaces on this machine (status | enable | disable)",
        "zc spaces".cyan()
    );
    println!();

    if full {
        println!("{}", "Broker".bold());
        println!("      broker [host] [port]      Start a broker (-d daemon).");
        println!("                                (opt-in self-update: ZAKURO_AUTO_UPDATE=1, ZAKURO_AUTO_UPDATE_INTERVAL=<secs or 10m, default 600, min 300>; builds from crates.io)");
        println!("      brokers                   List mesh brokers by zc://node-<fp> id.");
        println!("                                (remote dispatch with vouchers on, ZAKURO_REQUIRE_VOUCHER: a job needs a positive");
        println!("                                 budget_credits in X-Zakuro-Requirements, or it fails 400 BUDGET_REQUIRED)");
        println!();
        println!("{}", "Local Docker mesh".bold());
        println!("      mesh up [N]               Launch an N-node Docker compute mesh + broker.");
        println!("      mesh status | mesh down   Inspect / tear down the local mesh.");
        println!();
        println!("{}", "Headless enrollment".bold());
        println!("      token create              Mint a one-time join token for a headless node.");
        println!("      join <token>              Enroll this node using a join token.");
        println!();
        {
            println!("{}", "Zakuro Drive Hooks".bold());
            println!(
                "      hooks <add|get|list|update|remove|logs>   Manage drive file-event hooks."
            );
            println!();
        }
        println!("{}", "Maintenance".bold());
        println!("      update [--from-source]    Self-update zc from the signed get.zakuro-ai.com manifest");
        println!("                                (or build from source). --insecure-skip-signature: lab only.");
        println!("      pull | images | ps | kill | restart   Manage local zakuro containers.");
        println!("      info                      System info, clusters, and network status.");
        println!();
        println!("{}", "Aliases".dimmed());
        println!("      {}   login=init · connect/disconnect/status=vpn · share=up · unshare=down · ls=workers",
            "(old names still work)".dimmed());
        println!();
    } else {
        println!(
            "      {}   Show advanced commands (broker, mesh, tokens, maintenance)",
            "zc --full".dimmed()
        );
        println!();
    }

    println!(
        "Guides: {}",
        "https://docs.zakuro-ai.com/".cyan().underline()
    );
}

/// The mesh proxy for a request to `url`, and none when `url` is this
/// machine: the sidecar's proxy can't reach the host's loopback, so a local
/// broker called through it looks down.
fn mesh_proxy_for(url: &str) -> Option<ureq::Proxy> {
    if vpn::is_loopback_url(url) {
        None
    } else {
        vpn::mesh_proxy()
    }
}

/// Ask the hub which brokers the mesh authorises, and which of them answer.
/// `None` when the directory is unavailable — signed out, or the hub is
/// unreachable — which is a different thing from an empty mesh.
fn mesh_listing_from_directory() -> Option<(Vec<ListedBroker>, Listing)> {
    let all = mesh_dir::directory().ok()?;
    let offline = all
        .iter()
        .filter(|b| !b.revoked && b.endpoint.is_none())
        .count();
    let live: Vec<mesh_dir::MeshBroker> = all
        .into_iter()
        .filter(|b| !b.revoked && b.endpoint.is_some())
        .collect();
    let probes = mesh_dir::probe_all_within(
        live,
        std::time::Duration::from_secs(4),
        mesh_dir::LISTING_DEADLINE,
    );
    let self_fp = (9000..=9010)
        .filter_map(broker::uri::probe_local)
        .find_map(|h| h.node_id)
        .map(|id| broker::node_identity::strip_node_arg(&id).to_string());

    let unreachable = probes.iter().filter(|p| !p.reachable).count();
    let brokers: Vec<ListedBroker> = probes
        .iter()
        .filter(|p| p.reachable)
        .map(|p| ListedBroker {
            is_self: self_fp.as_deref() == Some(p.broker.fp.as_str()),
            fp: p.broker.fp.clone(),
            name: p.node_name.clone(),
        })
        .collect();
    Some((
        brokers,
        Listing::Directory {
            unreachable,
            offline,
            as_of_secs: None,
        },
    ))
}

/// The last mesh listing, kept so `zc ls` answers before the network does.
///
/// A fresh listing costs the hub roster (≈0.9 s) plus a mesh round trip to
/// every broker (≈0.75 s, more when one is dead). None of that is what a
/// person running `zc ls` is waiting for: the workers come live from this
/// machine's broker in milliseconds, and the broker roster changes on the
/// scale of minutes. So `zc ls` lists from here when the copy is recent,
/// says how old it is, and refreshes it in a detached process for next
/// time.
mod listing_cache {
    use super::{ListedBroker, Listing};
    use serde::{Deserialize, Serialize};

    /// Past this, the copy is not used: the listing is probed live.
    pub const MAX_AGE_SECS: u64 = 15 * 60;

    #[derive(Serialize, Deserialize)]
    struct Cached {
        fetched_at: u64,
        brokers: Vec<(String, Option<String>, bool)>,
        unreachable: usize,
        offline: usize,
    }

    fn path() -> Option<std::path::PathBuf> {
        Some(
            crate::credentials::dir()?
                .join("cache")
                .join("mesh-listing.json"),
        )
    }

    fn now() -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    }

    pub fn load() -> Option<(Vec<ListedBroker>, Listing)> {
        load_within(MAX_AGE_SECS)
    }

    /// The last copy however old, for a view that labels its age and
    /// replaces it as soon as a fresh listing arrives (the session).
    pub fn load_any() -> Option<(Vec<ListedBroker>, Listing)> {
        load_within(u64::MAX)
    }

    fn load_within(max_age: u64) -> Option<(Vec<ListedBroker>, Listing)> {
        let c: Cached = serde_json::from_str(&std::fs::read_to_string(path()?).ok()?).ok()?;
        let age = now().saturating_sub(c.fetched_at);
        (age <= max_age).then(|| {
            (
                c.brokers
                    .into_iter()
                    .map(|(fp, name, is_self)| ListedBroker { fp, name, is_self })
                    .collect(),
                Listing::Directory {
                    unreachable: c.unreachable,
                    offline: c.offline,
                    as_of_secs: Some(age),
                },
            )
        })
    }

    /// Write atomically, so a reader never meets half a file.
    pub fn save(brokers: &[ListedBroker], listing: &Listing) {
        let Listing::Directory {
            unreachable,
            offline,
            ..
        } = listing
        else {
            return; // a local-only view is not the mesh; keep the last one
        };
        let Some(p) = path() else { return };
        let c = Cached {
            fetched_at: now(),
            brokers: brokers
                .iter()
                .map(|b| (b.fp.clone(), b.name.clone(), b.is_self))
                .collect(),
            unreachable: *unreachable,
            offline: *offline,
        };
        let Ok(text) = serde_json::to_string(&c) else {
            return;
        };
        if let Some(dir) = p.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        let tmp = p.with_extension(format!("json.{}", std::process::id()));
        if std::fs::write(&tmp, text).is_ok() {
            let _ = std::fs::rename(&tmp, &p);
        }
    }

    /// Refresh the copy in a detached process, so this one can exit now.
    pub fn refresh_in_background() {
        if let Ok(exe) = std::env::current_exe() {
            let _ = std::process::Command::new(exe)
                .arg(REFRESH_VERB)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn();
        }
    }

    /// The hidden verb the background refresh runs as.
    pub const REFRESH_VERB: &str = "__mesh-listing-refresh";

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

        /// The session shows the last listing at once, however old, and
        /// says how old; `zc ls` still refuses one past [`MAX_AGE_SECS`].
        #[test]
        fn a_stale_copy_is_refused_by_load_but_kept_by_load_any() {
            let brokers = vec![ListedBroker {
                fp: "aaaa".into(),
                name: Some("i9".into()),
                is_self: false,
            }];
            save(
                &brokers,
                &Listing::Directory {
                    unreachable: 0,
                    offline: 0,
                    as_of_secs: None,
                },
            );
            let p = path().unwrap();
            let mut v: serde_json::Value =
                serde_json::from_str(&std::fs::read_to_string(&p).unwrap()).unwrap();
            v["fetched_at"] = serde_json::json!(now() - 10_000);
            std::fs::write(&p, v.to_string()).unwrap();
            assert!(load().is_none());
            let (b, l) = load_any().expect("kept");
            assert_eq!(b[0].fp, "aaaa");
            match l {
                Listing::Directory { as_of_secs, .. } => assert!(as_of_secs.unwrap() >= 10_000),
                other => panic!("{other:?}"),
            }
        }
    }
}

/// The mesh listing for `zc ls`: the cached copy when it is recent (and a
/// background refresh of it), otherwise a live probe, saved for next time.
fn mesh_listing() -> (Vec<ListedBroker>, Listing) {
    if let Some(hit) = listing_cache::load() {
        listing_cache::refresh_in_background();
        return hit;
    }
    match mesh_listing_from_directory() {
        Some((brokers, listing)) => {
            listing_cache::save(&brokers, &listing);
            (brokers, listing)
        }
        None => (
            Vec::new(),
            Listing::LocalOnly("the hub directory is unavailable".to_string()),
        ),
    }
}

/// Where a `zc ls` listing came from. The hub knows every broker the mesh
/// authorises; a single broker knows only the workers it has discovered, so a
/// listing built from one is smaller and says so.
#[derive(Debug, Clone, PartialEq)]
pub enum Listing {
    /// The hub's directory: every broker, named.
    Directory {
        unreachable: usize,
        offline: usize,
        /// How old the listing is when it came from the cache; `None` when
        /// it was probed just now.
        as_of_secs: Option<u64>,
    },
    /// Only what this machine's broker knows, and why.
    LocalOnly(String),
}

/// One broker in the listing, as the directory describes it.
#[derive(Debug, Clone, PartialEq)]
pub struct ListedBroker {
    /// Key-derived fingerprint, without the `zc://node-` prefix.
    pub fp: String,
    /// What the broker calls itself, when the directory knows.
    pub name: Option<String>,
    pub is_self: bool,
}

/// The node fingerprint a worker belongs to, without the `zc://node-` prefix.
fn worker_node_fp(worker: &serde_json::Value) -> Option<String> {
    worker
        .get("node")
        .and_then(|v| v.as_str())
        .map(|n| n.trim_start_matches("zc://node-").to_string())
}

/// Render `zc ls`: the brokers of the mesh, each with a table of the workers
/// this machine knows about underneath it — the layout zakuro-ai.com shows:
///
/// ```text
/// zc://node-4f2a9c1b8e7d0a35  gpu-box
///     WORKER  STATUS  CPUs  GPUs   MEM  PRICE
///     gpu-04  ready     32     4  256G    3.6
/// ```
///
/// Only nodes with workers are listed: a broker this machine has no worker
/// detail for, or one the hub cannot reach, offers nothing to read or use,
/// and 100+ such lines buried the few nodes that do.
pub fn render_mesh_listing(
    brokers: &[ListedBroker],
    workers: &[serde_json::Value],
    listing: &Listing,
) -> String {
    use colored::Colorize;
    let mut out = String::new();
    out.push('\n');

    let mut by_fp: std::collections::BTreeMap<String, Vec<&serde_json::Value>> =
        std::collections::BTreeMap::new();
    for w in workers {
        if let Some(fp) = worker_node_fp(w) {
            by_fp.entry(fp).or_default().push(w);
        }
    }

    // A listing from this broker alone has to say so before anything else,
    // or it reads as the whole mesh.
    if let Listing::LocalOnly(why) = listing {
        out.push_str(&format!(
            "  {}  {}\n\n",
            "This machine:".bold(),
            format!("only what this broker knows · {why}").dimmed()
        ));
    }

    let mut rows: Vec<(String, Option<String>, bool, Vec<&serde_json::Value>)> = match listing {
        Listing::Directory { .. } => brokers
            .iter()
            .map(|b| {
                (
                    b.fp.clone(),
                    b.name.clone(),
                    b.is_self,
                    by_fp.get(&b.fp).cloned().unwrap_or_default(),
                )
            })
            .collect(),
        // Nothing but what we discovered, so the groups are the workers'.
        Listing::LocalOnly(_) => by_fp
            .iter()
            .map(|(fp, ws)| (fp.clone(), None, false, ws.clone()))
            .collect(),
    };
    rows.retain(|(.., ws)| !ws.is_empty());
    if rows.is_empty() {
        out.push_str(&format!(
            "  {}\n\n",
            "No workers available on the mesh.".dimmed()
        ));
        return out;
    }

    for (fp, name, is_self, ws) in &rows {
        let id = format!("zc://node-{fp}");
        let mut label = name.clone().unwrap_or_default();
        if *is_self {
            label.push_str(if label.is_empty() {
                "(this machine)"
            } else {
                " (this machine)"
            });
        }
        out.push_str(&format!(
            "{}  {}\n",
            ui::paint(&id, ui::tone::URI),
            label.dimmed()
        ));
        out.push_str(&worker_table(ws));
    }

    // What the table cannot show: how many nodes there are and how many we
    // could not see. Last, where a summary belongs.
    let mut head = vec![format!(
        "{} node(s) · {} worker(s)",
        rows.len(),
        workers.len()
    )];
    if !workers.is_empty() {
        head.push("PRICE in zkcr/h".to_string());
    }
    if let Listing::Directory {
        as_of_secs: Some(age),
        ..
    } = listing
    {
        let ago = match age {
            0..=59 => format!("{age}s"),
            60..=3599 => format!("{}m", age / 60),
            _ => format!("{}h", age / 3600),
        };
        head.push(format!("brokers as of {ago} ago"));
    }
    out.push_str(&format!("\n{}\n", head.join(" · ").dimmed()));
    out.push('\n');
    out
}

/// One node's workers as a table: name, status, then what each one offers
/// and what it charges for it. Numbers are right-aligned so they compare
/// down the column.
fn worker_table(ws: &[&serde_json::Value]) -> String {
    use colored::Colorize;
    let num = |w: &serde_json::Value, total: &str, avail: &str| {
        w.get(total)
            .and_then(|v| v.as_f64())
            .or_else(|| w.get(avail).and_then(|v| v.as_f64()))
            .unwrap_or(0.0)
    };
    let cells: Vec<[String; 6]> = ws
        .iter()
        .map(|w| {
            [
                w.get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("?")
                    .to_string(),
                worker_status(w),
                format!("{:.0}", num(w, "cpus_total", "cpus_available")),
                format!("{:.0}", num(w, "gpus_total", "gpus_available")),
                format!("{:.0}G", num(w, "memory_total_gib", "memory_available_gib")),
                worker_price(w),
            ]
        })
        .collect();
    let head = ["WORKER", "STATUS", "CPUs", "GPUs", "MEM", "PRICE"];
    let mut width = head.map(str::len);
    for row in &cells {
        for (i, c) in row.iter().enumerate() {
            width[i] = width[i].max(c.chars().count());
        }
    }
    let line = |row: [&str; 6]| {
        let mut l = String::from("    ");
        for (i, c) in row.iter().enumerate() {
            let pad = " ".repeat(width[i].saturating_sub(c.chars().count()));
            match i {
                0 | 1 => l.push_str(&format!("{c}{pad}")),
                _ => l.push_str(&format!("{pad}{c}")),
            }
            if i < 5 {
                l.push_str("  ");
            }
        }
        l.trim_end().to_string()
    };
    let mut out = format!("{}\n", line(head).dimmed());
    for row in &cells {
        out.push_str(&line(row.each_ref().map(String::as_str)));
        out.push('\n');
    }
    out
}

/// A worker's status in the listing's words: a healthy worker is `ready`
/// to take work, which is the question the column answers. Anything else
/// (`draining`, `unhealthy`, …) is passed through as the broker said it.
fn worker_status(w: &serde_json::Value) -> String {
    match w.get("status").and_then(|v| v.as_str()).unwrap_or("?") {
        "healthy" => "ready".to_string(),
        other => other.to_string(),
    }
}

/// A worker's advertised price in zkcr/h, as it prices itself. `free` is a
/// real answer and reads better than `0`.
fn worker_price(w: &serde_json::Value) -> String {
    match w
        .get("price_per_hour")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.0)
    {
        p if p <= 0.0 => "free".to_string(),
        p => format!("{p}"),
    }
}

/// Whether a failed broker call means nothing answered at all: no
/// connection, no such host, or no reply in time. An HTTP error status is an
/// answer, from the broker or from a proxy in front of it.
fn broker_unreachable(err: &ureq::Error) -> bool {
    matches!(
        err,
        ureq::Error::ConnectionFailed
            | ureq::Error::HostNotFound
            | ureq::Error::Io(_)
            | ureq::Error::Timeout(_)
    )
}

/// Render the `zc ls` table. Every column is sized from the values it holds,
/// so a long worker name or `zc://` address can't push a row out of its
/// columns, and numbers carry no digits they don't need.
fn render_workers_table(workers: &[serde_json::Value], total: u64, broker_url: &str) -> String {
    use colored::Colorize;

    /// One cell: the text to print, which may carry colour escapes, and how
    /// wide it looks on screen. Padding uses `vis`, so colour never shifts a
    /// column.
    struct Cell {
        body: String,
        vis: usize,
    }
    impl Cell {
        fn plain(body: impl Into<String>) -> Self {
            let body = body.into();
            let vis = body.chars().count();
            Cell { body, vis }
        }
        fn painted(body: String, vis: usize) -> Self {
            Cell { body, vis }
        }
        fn pad(&self, width: usize, right: bool) -> String {
            let fill = " ".repeat(width.saturating_sub(self.vis));
            if right {
                format!("{fill}{}", self.body)
            } else {
                format!("{}{fill}", self.body)
            }
        }
    }

    /// `20.000` → `20`, `3.600` → `3.6`, `3.625` unchanged: a fixed number of
    /// decimals in every row is padding, not information.
    fn num(v: f64, decimals: usize) -> String {
        let s = format!("{v:.decimals$}");
        match s.contains('.') {
            true => s.trim_end_matches('0').trim_end_matches('.').to_string(),
            false => s,
        }
    }

    // A worker is never addressed on its own: a broker owns one or more of
    // them and decides which one runs a job. So the worker columns carry no
    // address, and each group is headed by its broker's zc:// id.
    //
    // EST/OBS (the broker's posterior median service time, and how many
    // observations back it) only appear when at least one worker in the
    // payload carries an `estimate` field. That field is opt-in on the
    // broker side (`GET /workers?estimate=1`) and absent talking to an older
    // broker, so its absence here must degrade to exactly today's table
    // rather than a column full of blanks.
    let has_estimate = workers.iter().any(|w| w.get("estimate").is_some());
    let mut heads: Vec<&str> = vec![
        "WORKER", "STATUS", "CPUs", "GPUs", "MEM", "PRICE", "5h", "1w", "1m",
    ];
    let mut right: Vec<bool> = vec![false, false, true, true, true, true, true, true, true];
    if has_estimate {
        heads.push("EST");
        heads.push("OBS");
        right.push(true);
        right.push(true);
    }
    let heads = heads;
    let right = right;
    /// Two spaces, so neighbouring right-aligned numbers don't read as one.
    const GAP: &str = "  ";
    /// Worker rows sit under their broker's line.
    const INDENT: &str = "    ";

    let f64_of = |w: &serde_json::Value, k: &str| w.get(k).and_then(|v| v.as_f64()).unwrap_or(0.0);
    let u64_of = |w: &serde_json::Value, k: &str| w.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
    let str_of = |w: &serde_json::Value, k: &str| {
        w.get(k).and_then(|v| v.as_str()).unwrap_or("?").to_string()
    };

    // "1234 / 5000 (25%)", or "0 / ∞" when the worker has no quota.
    let window = |count: u64, quota: u64| -> Cell {
        if quota == 0 {
            return Cell::plain(format!("{count} / ∞"));
        }
        let pct = count as f64 / quota as f64 * 100.0;
        let s = format!("{count} / {quota} ({pct:.0}%)");
        let vis = s.chars().count();
        let painted = if pct >= 90.0 {
            s.red()
        } else if pct >= 70.0 {
            s.yellow()
        } else {
            s.green()
        };
        Cell::painted(painted.to_string(), vis)
    };

    // Grouped by owning broker, and ordered, so the same mesh always prints
    // the same way.
    let mut groups: std::collections::BTreeMap<String, Vec<&serde_json::Value>> =
        std::collections::BTreeMap::new();
    for w in workers {
        groups.entry(str_of(w, "node")).or_default().push(w);
    }
    for owned in groups.values_mut() {
        owned.sort_by_key(|w| str_of(w, "name"));
    }

    let row_of = |w: &serde_json::Value| -> Vec<Cell> {
        let status = str_of(w, "status");
        let status_cell = match status.as_str() {
            "healthy" => Cell::painted(status.green().to_string(), status.chars().count()),
            "unhealthy" => Cell::painted(status.red().to_string(), status.chars().count()),
            "busy" => Cell::painted(status.yellow().to_string(), status.chars().count()),
            _ => Cell::plain(status),
        };
        let price = match w.get("price_per_hour").and_then(|v| v.as_f64()) {
            Some(p) => num(p, 3),
            None => "—".to_string(),
        };
        let mut cells = vec![
            Cell::plain(str_of(w, "name")),
            status_cell,
            Cell::plain(num(f64_of(w, "cpus_available"), 1)),
            Cell::plain(u64_of(w, "gpus_available").to_string()),
            Cell::plain(format!("{}GiB", num(f64_of(w, "memory_available_gib"), 1))),
            Cell::plain(price),
            window(u64_of(w, "requests_5h"), u64_of(w, "quota_5h")),
            window(u64_of(w, "requests_1w"), u64_of(w, "quota_1w")),
            window(u64_of(w, "requests_1m"), u64_of(w, "quota_1m")),
        ];
        if has_estimate {
            // "—" (the same dash used for an unknown price) for never
            // measured: it must never look like a confident `0ms`, which is
            // precisely the confusion that let an unmeasured worker outrank
            // one measured at 5ms.
            let est = match w
                .get("estimate")
                .and_then(|e| e.get("median_service_ms"))
                .and_then(|v| v.as_f64())
            {
                Some(ms) => format!("{}ms", num(ms, 1)),
                None => "—".to_string(),
            };
            let obs = w
                .get("estimate")
                .and_then(|e| e.get("observations"))
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0);
            cells.push(Cell::plain(est));
            cells.push(Cell::plain(num(obs, 1)));
        }
        cells
    };

    let rows: Vec<(String, Vec<Cell>)> = groups
        .iter()
        .flat_map(|(broker, owned)| owned.iter().map(|w| (broker.clone(), row_of(w))))
        .collect();

    // Every column is as wide as the widest thing in it, header included.
    let widths: Vec<usize> = heads
        .iter()
        .enumerate()
        .map(|(i, h)| {
            rows.iter()
                .map(|(_, r)| r[i].vis)
                .chain(std::iter::once(h.chars().count()))
                .max()
                .unwrap_or(0)
        })
        .collect();

    let line = |cells: &[Cell]| -> String {
        let padded: Vec<String> = cells
            .iter()
            .enumerate()
            .map(|(i, c)| c.pad(widths[i], right[i]))
            .collect();
        format!("{INDENT}{}", padded.join(GAP))
    };
    let table_width = INDENT.len() + widths.iter().sum::<usize>() + GAP.len() * (widths.len() - 1);
    let rule = format!("  {}", "─".repeat(table_width - 2).dimmed());

    let header: Vec<Cell> = heads
        .iter()
        .map(|h| Cell::painted(h.bold().to_string(), h.chars().count()))
        .collect();

    let mut out = String::new();
    out.push('\n');
    out.push_str(&format!(
        "  {}  {} broker(s) · {} worker(s) at {}\n",
        "Mesh:".bold(),
        groups.len(),
        total,
        broker_url
    ));
    out.push_str(&format!("{rule}\n"));
    out.push_str(&format!("{}\n", line(&header)));
    out.push_str(&format!("{rule}\n"));
    for (broker, owned) in &groups {
        // What the broker as a whole can take, which is what you weigh when
        // choosing where to send a job.
        let cpus: f64 = owned.iter().map(|w| f64_of(w, "cpus_available")).sum();
        let gpus: u64 = owned.iter().map(|w| u64_of(w, "gpus_available")).sum();
        let mem: f64 = owned
            .iter()
            .map(|w| f64_of(w, "memory_available_gib"))
            .sum();
        let plural = if owned.len() == 1 {
            "worker"
        } else {
            "workers"
        };
        let gpu_part = match gpus {
            0 => String::new(),
            n => format!(" · {n} GPUs"),
        };
        out.push_str(&format!(
            "  {}   {} {plural} · {} CPUs{gpu_part} · {}GiB\n",
            broker.cyan(),
            owned.len(),
            num(cpus, 1),
            num(mem, 1)
        ));
        for w in owned {
            out.push_str(&format!("{}\n", line(&row_of(w))));
        }
    }
    out.push_str(&format!("{rule}\n\n"));
    out
}

fn show_workers(broker_url: &str, node_filter: Option<&str>, json: bool, estimate: bool) {
    use colored::Colorize;
    use std::time::Duration;

    let url = workers_request_url(broker_url, node_filter, estimate);
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(Duration::from_secs(3)))
            .timeout_global(Some(Duration::from_secs(5)))
            .proxy(mesh_proxy_for(broker_url))
            .build(),
    );
    let is_local_target = vpn::is_loopback_url(broker_url);

    let response = match agent.get(&url).call() {
        Ok(r) => r,
        Err(e) if !broker_unreachable(&e) => {
            // The broker answered, with an error. Starting another broker on
            // its port could only fail, so the answer is what to report.
            eprintln!(
                "{} broker at {} answered: {}",
                "Error:".red(),
                broker_url,
                e
            );
            return;
        }
        Err(e) if !is_local_target => {
            // A remote (mesh) broker that does not answer is an error to report,
            // never a reason to start a broker on THIS machine.
            eprintln!("{} broker unreachable: {}", "Error:".red(), e);
            return;
        }
        Err(_) => {
            // Broker not running — auto-start it silently in the background
            let broker_port: u16 = broker_url
                .rsplit(':')
                .next()
                .and_then(|p| p.trim_end_matches('/').parse().ok())
                .unwrap_or(9000);
            eprintln!("  Broker not running — starting on port {}...", broker_port);
            let config = broker::BrokerConfig {
                host: "0.0.0.0".to_string(),
                port: broker_port,
                daemon: true,
                verbose: false,
                ..Default::default()
            };
            async_exec::spawn_detached(move || {
                let _ = broker::start_server(config);
            });
            // Poll /health until ready (up to 5s)
            let health_url = format!("{}/health", broker_url.trim_end_matches('/'));
            let ready = (0..50).any(|_| {
                std::thread::sleep(std::time::Duration::from_millis(100));
                agent.get(&health_url).call().is_ok()
            });
            if !ready {
                eprintln!("{} Broker failed to start within 5s", "Error:".red());
                return;
            }
            match agent.get(&url).call() {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("{} {}", "Error:".red(), e);
                    return;
                }
            }
        }
    };

    let body = match response.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{} {}", "Error reading response:".red(), e);
            return;
        }
    };

    let data: serde_json::Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{} {}", "Error parsing response:".red(), e);
            return;
        }
    };

    let workers = match data.get("workers").and_then(|v| v.as_array()) {
        Some(w) => w,
        None => {
            eprintln!("No workers field in response");
            return;
        }
    };
    let total = data
        .get("total")
        .and_then(|v| v.as_u64())
        .unwrap_or(workers.len() as u64);

    // `--json`: emit the full broker `/workers` payload verbatim (each worker
    // object already carries `price_per_hour`, `cpus_available` and
    // `memory_available_gib` — see `WorkerInfo` in `broker/server.rs`). No IP
    // fields are present in this response (client-facing `worker_to_info`
    // scrubs them), so this stays consistent with the IP-free CLI default.
    if json {
        println!("{}", serde_json::to_string(&data).unwrap_or_default());
        return;
    }

    // The hub knows every broker the mesh authorises; this broker knows only
    // the workers it has discovered. Prefer the first and fill in from the
    // second, and when the hub cannot be reached say that rather than passing
    // off one broker's view as the mesh.
    if node_filter.is_none() {
        let (brokers, listing) = mesh_listing();
        print!("{}", render_mesh_listing(&brokers, workers, &listing));
        return;
    }
    print!("{}", render_workers_table(workers, total, broker_url));
}

/// Render a `GET /brokers` JSON body into human-readable output.
///
/// IP-FREE RULE: this is the only place `zc brokers` formats output, and it
/// must never print an IP or raw peer_url — only the key-derived
/// `zc://node-<fp>` ids the `/brokers` handler already scrubbed. It
/// deliberately reads only `self`/`self_build`/`brokers[].id|reachable|build`,
/// so even if a future `/brokers` response regressed and started including a
/// `peer_url` field, this renderer would never surface it.
fn render_brokers_output(data: &serde_json::Value) -> String {
    use colored::Colorize;

    // Only ever reads the `build` sub-object's own fields, so a regressed
    // response cannot smuggle an address through this column either.
    let build_label = |v: &serde_json::Value, key: &str| -> Option<String> {
        serde_json::from_value::<build_id::BuildId>(v.get(key)?.clone())
            .ok()
            .filter(build_id::BuildId::is_known)
            .map(|b| b.label())
    };

    let mut out = String::new();
    let self_id = data.get("self").and_then(|v| v.as_str()).unwrap_or("?");
    let self_build =
        build_label(data, "self_build").unwrap_or_else(|| "build undisclosed".to_string());
    out.push_str(&format!(
        "  {}  {}  {}\n",
        "Self:".bold(),
        self_id,
        self_build
    ));

    let brokers = data
        .get("brokers")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    if brokers.is_empty() {
        out.push_str("  No other brokers known.\n");
        return out;
    }

    out.push_str(&format!("  {} peer broker(s):\n", brokers.len()));
    for b in &brokers {
        let id = b.get("id").and_then(|v| v.as_str()).unwrap_or("?");
        let reachable = b
            .get("reachable")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let dot = if reachable {
            "●".green().to_string()
        } else {
            "●".red().to_string()
        };
        // A peer's build is only as fresh as its last cached advert, so an
        // entry may legitimately have none yet.
        let build = build_label(b, "build").unwrap_or_else(|| "build undisclosed".to_string());
        out.push_str(&format!("    {} {}  {}\n", dot, id, build));
    }
    out
}

/// `zc brokers` — ensure a local broker is running, GET `/brokers`, print it.
/// Mirrors `show_workers`'s auto-spawn behaviour.
/// `zc brokers`: the mesh directory. Roster-native — asks the hub which
/// brokers are authorized and where they advertised themselves, probes each
/// one's `/health` over the mesh, and prints key-derived ids only. Needs no
/// local broker and no peer key. When the directory is unavailable (signed
/// out and no cached roster) it falls back to a local broker's own `/brokers`
/// view, which is what this command used to be.
fn show_brokers_cmd() {
    use colored::Colorize;
    match mesh_dir::directory() {
        Ok(list) => {
            let offline = list
                .iter()
                .filter(|b| !b.revoked && b.endpoint.is_none())
                .count();
            let live: Vec<mesh_dir::MeshBroker> = list
                .into_iter()
                .filter(|b| !b.revoked && b.endpoint.is_some())
                .collect();
            let probes = mesh_dir::probe_all_within(
                live,
                std::time::Duration::from_secs(4),
                mesh_dir::LISTING_DEADLINE,
            );
            // Mark this machine's own broker, if one is running, by identity.
            let self_fp = (9000..=9010)
                .filter_map(broker::uri::probe_local)
                .find_map(|h| h.node_id)
                .map(|id| broker::node_identity::strip_node_arg(&id).to_string());
            println!();
            print!("{}", mesh_dir::render(&probes, self_fp.as_deref(), offline));
            println!();
        }
        Err(e) => {
            eprintln!(
                "  {} mesh directory unavailable ({}); showing the local broker's view",
                "note:".yellow(),
                e
            );
            match resolve_default_broker(None) {
                Ok(url) => show_brokers(&url),
                Err(e) => {
                    eprintln!("Error: {}", e);
                    std::process::exit(1);
                }
            }
        }
    }
}

fn show_brokers(broker_url: &str) {
    use colored::Colorize;
    use std::time::Duration;

    let url = format!("{}/brokers", broker_url.trim_end_matches('/'));
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(Duration::from_secs(3)))
            .timeout_global(Some(Duration::from_secs(5)))
            .proxy(mesh_proxy_for(broker_url))
            .build(),
    );

    let response = match agent.get(&url).call() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("{} {}", "Error:".red(), e);
            return;
        }
    };

    let body = match response.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{} {}", "Error reading response:".red(), e);
            return;
        }
    };

    let data: serde_json::Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{} {}", "Error parsing response:".red(), e);
            return;
        }
    };

    println!();
    print!("{}", render_brokers_output(&data));
    println!();
}

/// Resolve the broker URL for commands (`workers`, `discovery`) that default
/// to `zc://localhost`. When the caller passed an explicit broker target
/// (CLI arg or `ZAKURO_BROKER` env var), behave exactly as before: resolve
/// it and fail if unreachable. Otherwise (the default case) make sure a
/// local broker exists, auto-spawning one in the background if needed.
pub(crate) fn resolve_default_broker(explicit_cli: Option<&str>) -> Result<String, String> {
    let env_broker = env::var("ZAKURO_BROKER").ok();
    if autobroker::should_auto_spawn(explicit_cli, env_broker.as_deref()) {
        autobroker::ensure_local_broker(true)
    } else {
        let raw = explicit_cli
            .map(|s| s.to_string())
            .or(env_broker)
            .unwrap_or_else(|| "zc://localhost".to_string());
        broker::uri::resolve(&raw)
    }
}

/// Drives `zc serve`: parse args, resolve the broker + marketplace API,
/// download/launch/register each specialized model, and (for `--general`)
/// print the Phase-2 follow-up note. Real `llama-server` processes are only
/// spawned here (not in `serve.rs`'s unit tests).
fn run_serve(args: &[String]) {
    let parsed = match serve::parse_serve_args(args) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Error: {}", e);
            eprintln!("Usage: zc serve zc://<owner>/<name> [more…] [--price <zkcr_per_mtok>] [--port <base_port>] [--api-url <url>] [--advertise <host>] [--general]");
            std::process::exit(2);
        }
    };

    let broker_url = match resolve_default_broker(None) {
        Ok(u) => u,
        Err(e) => {
            eprintln!("Error resolving broker: {}", e);
            std::process::exit(1);
        }
    };
    let api_url = parsed
        .api_url
        .clone()
        .unwrap_or_else(credentials::default_api_url);
    let auth_bearer = env::var("ZAKURO_API_KEY").ok();
    // CLI wins over env so one-off runs can override a shell profile export.
    let advertise = parsed.advertise.clone().or_else(|| {
        env::var("ZAKURO_ADVERTISE_ADDR")
            .ok()
            .filter(|v| !v.is_empty())
    });

    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(10)))
            .timeout_global(Some(std::time::Duration::from_secs(600)))
            .proxy(mesh_proxy_for(&broker_url))
            .build(),
    );

    let mut children = Vec::new();
    for (i, address) in parsed.model_addresses.iter().enumerate() {
        // Resolved per model rather than up front, so one unresolvable address
        // does not stop the others from being served.
        let model_uuid = resolve_model_address_or_exit(address);
        let model_uuid = &model_uuid;
        let port = parsed.base_port + i as u16;
        println!("Serving {} on port {}...", model_uuid, port);
        match serve::serve_one_model(
            &agent,
            &api_url,
            &broker_url,
            model_uuid,
            port,
            parsed.price_per_mtok,
            auth_bearer.as_deref(),
            advertise.as_deref(),
        ) {
            Ok((child, worker_name)) => {
                println!(
                    "  registered worker '{}' with broker {}",
                    worker_name, broker_url
                );
                children.push(child);
            }
            Err(e) => {
                eprintln!("Error serving {}: {}", model_uuid, e);
            }
        }
    }

    if parsed.general {
        // The general provider's front server owns base_port; the on-demand
        // llama-servers it spawns start one port above (they're loopback-only
        // backends; only the front port is advertised to the broker).
        let general_uri = serve::worker_uri(advertise.as_deref(), parsed.base_port);
        let registration = serve::worker_registration_general(
            "zc-serve-general",
            &general_uri,
            parsed.price_per_mtok,
        );
        match serve::register_worker(&agent, &broker_url, &registration) {
            Err(e) => {
                eprintln!("Error registering general provider: {e}");
                std::process::exit(1);
            }
            Ok(worker_id) => {
                println!(
                    "registered general-provider worker with broker {}",
                    broker_url
                );
                // Heartbeat for the lifetime of the front server: `run
                // forever` is the right lifetime here — if this process
                // dies the heartbeats stop with it and the broker expires
                // the worker on its own staleness clock.
                let hb_agent = agent.clone();
                let hb_broker = broker_url.clone();
                let _ = std::thread::Builder::new()
                    .name("zc-serve-general-heartbeat".into())
                    .spawn(move || {
                        let never = std::sync::atomic::AtomicBool::new(false);
                        serve::run_heartbeat_loop(
                            &never,
                            serve::HEARTBEAT_INTERVAL,
                            std::thread::sleep,
                            || {
                                if let Err(e) =
                                    serve::send_heartbeat(&hb_agent, &hb_broker, &worker_id)
                                {
                                    eprintln!("  [SERVE] general heartbeat failed: {e}");
                                }
                            },
                        );
                    });

                let hooks = serve_general::production_hooks(
                    agent.clone(),
                    api_url.clone(),
                    auth_bearer.clone(),
                );
                let loader = serve_general::GeneralLoader::new(
                    hooks,
                    parsed.base_port + 1,
                    serve_general::GeneralLoader::max_loaded_from_env(),
                );
                // Blocking: the front server IS the process from here on.
                if let Err(e) = serve_general::run_general_server(loader, parsed.base_port) {
                    eprintln!("Error running general provider server: {e}");
                    std::process::exit(1);
                }
            }
        }
    }

    if children.is_empty() && !parsed.general {
        std::process::exit(1);
    }

    // Keep the process alive while any llama-server child is serving.
    for mut child in children {
        let _ = child.wait();
    }
}

/// Resolve the broker URL for `zc infer`/`zc chat`: the explicit `--broker`
/// flag if given, else the credential-resolved default (mirrors every other
/// subcommand's `resolve_default_broker(None)` pattern).
fn resolve_infer_broker(explicit: Option<&str>) -> Result<String, String> {
    match explicit {
        // `--broker zc://node-<fp>` goes through the same resolver as every
        // other command (local id match, then the mesh directory). A raw
        // http(s):// URL is still accepted here for scripts that already hold one.
        Some(url) if url.starts_with("zc://") => broker::uri::resolve(url),
        Some(url) => Ok(url.to_string()),
        None => resolve_default_broker(None),
    }
}

/// `Authorization: Bearer <key>` for broker client calls, from the env /
/// saved credentials. Fleet brokers run in remote mode and require it on
/// `/infer` and `/execute`; a local free-mode broker ignores it.
fn bearer_header() -> Option<String> {
    credentials::load_into_env();
    env::var("ZAKURO_API_KEY")
        .ok()
        .filter(|k| !k.trim().is_empty())
        .map(|k| format!("Bearer {}", k.trim()))
}

/// POST `{broker}/infer` with `body`, returning the parsed JSON response and
/// its `X-Zakuro-*` receipt headers on success, or a human-readable error
/// message (broker error body, transport error, or bad JSON) on failure.
fn post_infer(
    agent: &ureq::Agent,
    broker_url: &str,
    body: &serde_json::Value,
) -> Result<(serde_json::Value, Vec<(String, String)>), String> {
    let url = format!("{}/infer", broker_url.trim_end_matches('/'));
    let mut req = agent.post(&url).header("Content-Type", "application/json");
    if let Some(auth) = bearer_header() {
        req = req.header("Authorization", &auth);
    }
    let response = req
        .send_json(body)
        .map_err(|e| format!("broker request failed: {e}"))?;

    let status = response.status();
    let receipt: Vec<(String, String)> = response
        .headers()
        .iter()
        .filter(|(k, _)| k.as_str().starts_with("x-zakuro-"))
        .filter_map(|(k, v)| Some((k.as_str().to_string(), v.to_str().ok()?.to_string())))
        .collect();
    let text = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("reading broker response: {e}"))?;

    if !status.is_success() {
        // Non-2xx bodies are `{"error": "..."}` (Task 4 contract); surface
        // that message rather than the raw JSON. `format_infer_error` is
        // applied by the caller, so just hand back the raw body here.
        return Err(text);
    }

    serde_json::from_str::<serde_json::Value>(&text)
        .map(|v| (v, receipt))
        .map_err(|e| format!("parsing broker response: {e} (body: {text})"))
}

/// Hub runtime fallback: `POST {api}/api/models/{uuid}/infer` with the saved
/// API key. Returns the reply in broker shape plus receipt headers, or the
/// hub's error text verbatim.
fn post_hub_infer(
    model_uuid: &str,
    messages: &[serde_json::Value],
    max_tokens: Option<u64>,
) -> Result<(serde_json::Value, Vec<(String, String)>), String> {
    credentials::load_into_env();
    let api_url = env::var("ZAKURO_API_URL")
        .ok()
        .filter(|u| !u.trim().is_empty())
        .unwrap_or_else(credentials::default_api_url);
    let key = env::var("ZAKURO_API_KEY")
        .ok()
        .filter(|k| !k.trim().is_empty())
        .ok_or_else(|| "no API key for the hub fallback; run `zc login` (hub)".to_string())?;
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(10)))
            .timeout_global(Some(std::time::Duration::from_secs(300)))
            .http_status_as_error(false)
            .build(),
    );
    let url = format!(
        "{}/api/models/{}/infer",
        api_url.trim_end_matches('/'),
        model_uuid
    );
    let response = agent
        .post(&url)
        .header("Authorization", &format!("Bearer {}", key.trim()))
        .send_json(infer::build_hub_body(messages, max_tokens))
        .map_err(|e| format!("hub request failed: {e} (hub)"))?;
    let status = response.status();
    let text = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("reading hub response: {e} (hub)"))?;
    if !status.is_success() {
        return Err(infer::format_hub_error(&text));
    }
    infer::parse_hub_reply(&text)
}

/// Hub runtime transcription: `POST {api}/api/models/{uuid}/transcribe`,
/// multipart `file` (+ optional `language`). Returns the parsed reply or the
/// hub's error text verbatim.
fn post_hub_transcribe(
    model_uuid: &str,
    audio: &[u8],
    filename: &str,
    content_type: &str,
    language: Option<&str>,
) -> Result<infer::TranscribeReply, String> {
    credentials::load_into_env();
    let api_url = env::var("ZAKURO_API_URL")
        .ok()
        .filter(|u| !u.trim().is_empty())
        .unwrap_or_else(credentials::default_api_url);
    let key = env::var("ZAKURO_API_KEY")
        .ok()
        .filter(|k| !k.trim().is_empty())
        .ok_or_else(|| "no API key for the hub; run `zc login` (hub)".to_string())?;
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(10)))
            .timeout_global(Some(std::time::Duration::from_secs(900)))
            .http_status_as_error(false)
            .build(),
    );
    let url = format!(
        "{}/api/models/{}/transcribe",
        api_url.trim_end_matches('/'),
        model_uuid
    );
    let boundary = format!("zc-{}", uuid::Uuid::new_v4().simple());
    let (ct, body) = infer::build_multipart(&boundary, filename, content_type, audio, language);
    let response = agent
        .post(&url)
        .header("Authorization", &format!("Bearer {}", key.trim()))
        .header("Content-Type", &ct)
        .send(&body[..])
        .map_err(|e| format!("hub request failed: {e} (hub)"))?;
    let status = response.status();
    let text = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("reading hub response: {e} (hub)"))?;
    if !status.is_success() {
        return Err(infer::format_hub_error(&text));
    }
    infer::parse_transcribe_reply(&text)
}

/// `zc infer <addr> --file <audio>`: transcribe via the hub.
fn run_infer_file(parsed: &infer::InferArgs, path: &str) {
    let meta = match std::fs::metadata(path) {
        Ok(m) if m.is_file() => m,
        Ok(_) => {
            eprintln!("Error: --file {path}: not a regular file");
            std::process::exit(2);
        }
        Err(e) => {
            eprintln!("Error: cannot read --file {path}: {e}");
            std::process::exit(2);
        }
    };
    if meta.len() > infer::MAX_AUDIO_BYTES {
        eprintln!(
            "Error: --file {path} is {} MiB; the limit is {} MiB",
            meta.len() / (1024 * 1024),
            infer::MAX_AUDIO_BYTES / (1024 * 1024)
        );
        std::process::exit(2);
    }
    let audio = match std::fs::read(path) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("Error: cannot read --file {path}: {e}");
            std::process::exit(2);
        }
    };
    let filename = std::path::Path::new(path)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "audio".to_string());
    let model_uuid = resolve_model_address_or_exit(&parsed.model);
    match post_hub_transcribe(
        &model_uuid,
        &audio,
        &filename,
        infer::audio_content_type(path),
        parsed.language.as_deref(),
    ) {
        Ok(r) => println!("{}", infer::format_transcribe_reply(&r)),
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    }
}

/// `zc infer` — one-shot consumer call into a served model.
fn run_infer(args: &[String]) {
    let parsed = match infer::parse_infer_args(args) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Error: {}", e);
            eprintln!("Usage: zc infer zc://<owner>/<name> -m \"<prompt>\" [--max-tokens N] [--system \"<sys>\"] [--broker <url>]");
            eprintln!("       zc infer zc://<owner>/<name> --file <audio> [--language xx]");
            std::process::exit(2);
        }
    };

    if let Some(path) = parsed.file.as_deref() {
        run_infer_file(&parsed, path);
        return;
    }

    let broker_url = match resolve_infer_broker(parsed.broker.as_deref()) {
        Ok(u) => u,
        Err(e) => {
            eprintln!("Error resolving broker: {}", e);
            std::process::exit(1);
        }
    };

    // Resolved before anything is dispatched: the broker routes on the UUID
    // and has no marketplace credentials on the dispatch path, so a name has
    // to become an id here, in the client.
    let model_uuid = resolve_model_address_or_exit(&parsed.model);

    let body = infer::build_infer_body(
        &model_uuid,
        &parsed.prompt,
        parsed.system.as_deref(),
        parsed.max_tokens,
    );

    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(10)))
            .timeout_global(Some(std::time::Duration::from_secs(300)))
            .http_status_as_error(false)
            .proxy(mesh_proxy_for(&broker_url))
            .build(),
    );

    let result = match post_infer(&agent, &broker_url, &body) {
        Err(e) if infer::should_fall_back_to_hub(parsed.broker.is_some(), &e) => post_hub_infer(
            &model_uuid,
            &infer::build_messages(&parsed.prompt, parsed.system.as_deref()),
            parsed.max_tokens,
        ),
        Err(e) => Err(infer::format_infer_error(&e)),
        ok => ok,
    };
    match result {
        Ok((resp, receipt)) => {
            println!("{}", infer::format_infer_reply(&resp, &receipt));
        }
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    }
}

/// Resolve a typed `zc://` address to the concrete model UUID, or exit with an
/// explanation. Shared by `zc infer` and `zc chat`, which differ only in what
/// they do afterwards.
fn resolve_model_address_or_exit(addr: &crate::model_uri::ModelAddress) -> String {
    // Fills ZAKURO_API_URL / ZAKURO_API_KEY from the saved config when they are
    // not already set, so a signed-in user needs no flags to reach a private
    // model.
    credentials::load_into_env();
    let api_url = std::env::var("ZAKURO_API_URL")
        .ok()
        .filter(|u| !u.trim().is_empty())
        .unwrap_or_else(credentials::default_api_url);
    let api_key = std::env::var("ZAKURO_API_KEY").ok();
    match crate::model_uri::resolve_address(addr, &api_url, api_key.as_deref()) {
        Ok(u) => u,
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    }
}

/// `zc chat` — interactive REPL over the `/infer` route. Reads lines from
/// stdin, accumulating the conversation, until EOF or `/quit`.
fn run_chat(args: &[String]) {
    use std::io::{self, BufRead, Write};

    let parsed = match infer::parse_chat_args(args) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Error: {}", e);
            eprintln!("Usage: zc chat zc://<owner>/<name> [--system \"<sys>\"] [--broker <url>]");
            std::process::exit(2);
        }
    };

    let broker_url = match resolve_infer_broker(parsed.broker.as_deref()) {
        Ok(u) => u,
        Err(e) => {
            eprintln!("Error resolving broker: {}", e);
            std::process::exit(1);
        }
    };

    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(10)))
            .timeout_global(Some(std::time::Duration::from_secs(300)))
            .http_status_as_error(false)
            .proxy(mesh_proxy_for(&broker_url))
            .build(),
    );

    let model_uuid = resolve_model_address_or_exit(&parsed.model);

    let mut messages: Vec<serde_json::Value> = Vec::new();
    if let Some(sys) = &parsed.system {
        messages.push(serde_json::json!({"role": "system", "content": sys}));
    }

    println!(
        "zc chat — model zc://{} (broker {})",
        model_uuid, broker_url
    );
    println!("Type your message and press Enter. /quit or Ctrl-D to exit.\n");

    let stdin = io::stdin();
    // Set once the broker has no provider for the model; later turns go
    // straight to the hub runtime.
    let mut use_hub = false;
    loop {
        print!("> ");
        let _ = io::stdout().flush();

        let mut line = String::new();
        let bytes_read = match stdin.lock().read_line(&mut line) {
            Ok(n) => n,
            Err(e) => {
                eprintln!("Error reading input: {}", e);
                break;
            }
        };
        if bytes_read == 0 {
            // EOF
            break;
        }
        let line = line.trim_end_matches('\n').trim_end_matches('\r');
        if line.trim() == "/quit" {
            break;
        }
        if line.trim().is_empty() {
            continue;
        }

        messages.push(serde_json::json!({"role": "user", "content": line}));
        let body = infer::build_chat_body(&model_uuid, &messages, None);

        let result = if use_hub {
            post_hub_infer(&model_uuid, &messages, None)
        } else {
            match post_infer(&agent, &broker_url, &body) {
                Err(e) if infer::should_fall_back_to_hub(parsed.broker.is_some(), &e) => {
                    use_hub = true;
                    post_hub_infer(&model_uuid, &messages, None)
                }
                Err(e) => Err(infer::format_infer_error(&e)),
                ok => ok,
            }
        };
        match result {
            Ok((resp, _)) => {
                println!("{}", infer::format_infer_output(&resp));
                if let Some(content) = resp.get("content").and_then(|v| v.as_str()) {
                    messages.push(serde_json::json!({"role": "assistant", "content": content}));
                }
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                // Drop the failed user turn so the conversation stays coherent.
                messages.pop();
            }
        }
        println!();
    }
}

fn require_auth() {
    eprintln!("This command requires authentication.\n");
    eprintln!("Set your token with:");
    eprintln!("  export ZAKURO_API_KEY=\"your-token-here\"\n");
    eprintln!("Don't have a token? Request access at https://zakuro-ai.com");
}

/// Rewrite user-facing verbs to the canonical commands the dispatcher already
/// understands. The new names (login/connect/disconnect/status/share/unshare/ls)
/// are what we document; the old names keep working because they're the targets.
/// Aliases are silent — no deprecation noise — so pinned scripts and the harness
/// are unaffected.
fn normalize_aliases(mut args: Vec<String>) -> Vec<String> {
    let Some(verb) = args.get(1).cloned() else {
        return args;
    };
    let rest = || args[2..].to_vec();
    let rebuilt: Option<Vec<String>> = match verb.as_str() {
        "login" => Some([vec![args[0].clone(), "init".into()], rest()].concat()),
        "share" => Some([vec![args[0].clone(), "up".into()], rest()].concat()),
        "unshare" => Some([vec![args[0].clone(), "down".into()], rest()].concat()),
        "ls" => Some([vec![args[0].clone(), "workers".into()], rest()].concat()),
        // Mesh verbs: `zc connect` == `zc vpn connect`, etc.
        "connect" => Some(
            [
                vec![args[0].clone(), "vpn".into(), "connect".into()],
                rest(),
            ]
            .concat(),
        ),
        "disconnect" => Some(
            [
                vec![args[0].clone(), "vpn".into(), "disconnect".into()],
                rest(),
            ]
            .concat(),
        ),
        "status" => Some([vec![args[0].clone(), "vpn".into(), "status".into()], rest()].concat()),
        _ => None,
    };
    if let Some(r) = rebuilt {
        args = r;
    }
    args
}

/// Strip a bare `--json` modifier out of the arg vector, wherever it appears,
/// and report whether it was present. `--json` is accepted by `workers`/`ls`
/// (see `show_workers`) to emit the machine-readable listing (price +
/// capabilities included) instead of the human table; stripping it here keeps
/// every downstream positional/length-based `match` arm unaffected by its
/// presence or position in the command line.
fn extract_json_flag(mut args: Vec<String>) -> (Vec<String>, bool) {
    let present = args.iter().any(|a| a == "--json");
    if present && !owns_json_flag(&args) {
        args.retain(|a| a != "--json");
    }
    (args, present)
}

/// Subcommands that parse `--json` themselves and must therefore still see it.
///
/// Stripping it globally is what `workers`/`ls` need, and it silently
/// disarmed `zc bench --json`: bench ran, printed its human view to stdout,
/// and emitted no document at all. A subcommand that owns the flag keeps it.
fn owns_json_flag(args: &[String]) -> bool {
    matches!(args.get(1).map(String::as_str), Some("bench"))
}

/// Strip a bare `--estimate` modifier out of the arg vector, the same way
/// `extract_json_flag` handles `--json`. `--estimate` asks `workers`/`ls` to
/// request each worker's posterior (median service time, spread, and how
/// many observations back it) from the broker — `GET /workers?estimate=1` —
/// and to render it. It costs nothing when absent: the broker never computes
/// or serializes the estimate group unless asked (zc#267).
fn extract_estimate_flag(mut args: Vec<String>) -> (Vec<String>, bool) {
    let present = args.iter().any(|a| a == "--estimate");
    if present {
        args.retain(|a| a != "--estimate");
    }
    (args, present)
}

/// Build the `GET /workers` URL `show_workers` calls: an optional node
/// filter and the opt-in `estimate=1` combine into one query string, so the
/// broker computes and serializes the posterior only when asked.
fn workers_request_url(broker_url: &str, node_filter: Option<&str>, estimate: bool) -> String {
    let base = broker_url.trim_end_matches('/');
    let mut params = Vec::new();
    if let Some(n) = node_filter {
        // Pass the bare node name (strip zc://); server also normalises. Bare
        // names contain no query-special characters so no percent-encoding
        // is needed.
        params.push(format!("node={}", n.strip_prefix("zc://").unwrap_or(n)));
    }
    if estimate {
        params.push("estimate=1".to_string());
    }
    if params.is_empty() {
        format!("{base}/workers")
    } else {
        format!("{base}/workers?{}", params.join("&"))
    }
}

/// The local broker's workers, for the session: short timeouts and, unlike
/// `zc ls`, no auto-start — the session never starts a broker on its own.
fn fetch_worker_list(broker_url: &str) -> Result<Vec<serde_json::Value>, String> {
    let url = workers_request_url(broker_url, None, false);
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(2)))
            .timeout_global(Some(std::time::Duration::from_secs(3)))
            .proxy(mesh_proxy_for(broker_url))
            .build(),
    );
    let body = agent
        .get(&url)
        .call()
        .map_err(|e| format!("broker at {broker_url}: {e}"))?
        .into_body()
        .read_to_string()
        .map_err(|e| format!("broker at {broker_url}: {e}"))?;
    let v: serde_json::Value =
        serde_json::from_str(&body).map_err(|e| format!("broker at {broker_url}: {e}"))?;
    Ok(v.get("workers")
        .and_then(|w| w.as_array())
        .cloned()
        .unwrap_or_default())
}

fn main() {
    credentials::load_into_env();
    // rustls 0.23 no longer auto-installs a crypto provider; do it once
    // at startup so every later ClientConfig / ServerConfig builder picks
    // ring up implicitly. install_default() returns Err if called twice,
    // which on the binary side cannot happen — keep the call infallible
    // by ignoring the result.
    let _ = rustls::crypto::ring::default_provider().install_default();

    envs::update();
    let raw_args: Vec<String> = normalize_aliases(env::args().collect());
    let (raw_args, json_flag) = extract_json_flag(raw_args);
    let (args, estimate_flag) = extract_estimate_flag(raw_args);

    // Show help even without ZAKURO_API_KEY
    let full_help = args.iter().any(|a| a == "--full");
    if args
        .get(1)
        .map(|a| a == "-h" || a == "--help")
        .unwrap_or(false)
    {
        help(full_help);
        return;
    }
    if args.get(1).map(|a| a == "--full").unwrap_or(false) {
        help(true);
        return;
    }
    // Bare `zc` in a terminal opens the session; everywhere else (a pipe,
    // CI, ZC_PLAIN) it prints help exactly as before.
    if session::should_open(
        args.len(),
        std::io::IsTerminal::is_terminal(&std::io::stdout()),
        env::var_os("ZC_PLAIN").is_some(),
        env::var("TERM").ok().as_deref(),
    ) {
        std::process::exit(session::run());
    }

    // Bare `zc` prints help.
    if args.len() == 1 {
        help(full_help);
        return;
    }

    let zakuro_auth = env::var("ZAKURO_API_KEY").ok();
    let _broker_url = env::var("ZAKURO_BROKER").unwrap_or_else(|_| "zc://localhost".to_string());

    // `zc up [--workers N] [--port P] [--broker-port P] [-d]` — any number of args
    if args.get(1).map(String::as_str) == Some(listing_cache::REFRESH_VERB) {
        if let Some((brokers, listing)) = mesh_listing_from_directory() {
            listing_cache::save(&brokers, &listing);
        }
        return;
    }

    if args.get(1).map(|a| a == "up").unwrap_or(false) {
        let up_args: Vec<String> = args[2..].to_vec();
        if let Some(code) = agent::handoff::try_up(&up_args) {
            std::process::exit(code);
        }
        let (workers, base_port, broker_port, daemon) = up::parse_args(&up_args);
        up::apply_price_arg(&up_args);
        up::start_up(workers, base_port, broker_port, daemon);
        return;
    }

    // `zc mesh [up [N] | down | status]` — Docker compute-node mesh (local).
    if args.get(1).map(|a| a == "mesh").unwrap_or(false) {
        match args.get(2).map(|s| s.as_str()).unwrap_or("status") {
            "up" => {
                let n = args
                    .get(3)
                    .and_then(|s| s.parse::<usize>().ok())
                    .unwrap_or(4);
                mesh::up(n);
            }
            "down" => mesh::down(),
            "status" | "ls" | "ps" => mesh::status(),
            other => eprintln!("usage: zc mesh [up <N>|down|status] (got '{}')", other),
        }
        return;
    }

    // `zc agent [run|install|uninstall|status [--json]]` — the loopback control
    // service behind the macOS menu-bar app and widget.
    if args.get(1).map(|a| a == "agent").unwrap_or(false) {
        std::process::exit(agent::run_cli(&args[2..], json_flag));
    }

    // `zc jobs [--state live|done] [--json] | zc jobs --live` — this node's
    // jobs, from the agent's `/v2/jobs` and `/v2/events`.
    if args.get(1).map(|a| a == "jobs").unwrap_or(false) {
        std::process::exit(agent::jobs_cli::run(&args[2..], json_flag));
    }

    // `zc hub allocate [--enable ... | --disable]` — lend capacity to the hub.
    if args.get(1).map(|a| a == "hub").unwrap_or(false) {
        std::process::exit(hub_allocation::run_cli(&args[2..]));
    }

    // `zc spaces [enable [--min-price-per-hour N] | disable | status]`.
    if args.get(1).map(|a| a == "spaces").unwrap_or(false) {
        std::process::exit(spaces::run_cli(&args[2..]));
    }

    // `zc deployments` — local reconciler state (debugging aid): what this
    // node believes it's running for the hub's desired deployments, plus a
    // `docker ps` view filtered to the containers it created.
    if args.get(1).map(|a| a == "deployments").unwrap_or(false) {
        broker::deploy::print_deployments();
        return;
    }

    // `zc doctor` — local diagnostics: the active ZAKURO_ENV profile, then the
    // container-runtime probe.
    if args.get(1).map(|a| a == "doctor").unwrap_or(false) {
        println!("{}", profile::doctor_report(&profile::resolve()));
        let probe = broker::deploy::runtime_probe();
        println!("{}", broker::deploy::doctor_report(&probe));
        std::process::exit(if probe.available { 0 } else { 1 });
    }

    // `zc vpn [connect [--native|--docker] | disconnect | status]`
    if args.get(1).map(|a| a == "vpn").unwrap_or(false) {
        vpn::run_cli(&args[2..]);
        return;
    }

    // `zc update [--from-source]` — self-update the running zc binary. Exits 1
    // on any failure.
    if args.get(1).map(|a| a == "update").unwrap_or(false) {
        std::process::exit(update::run_cli(&args[2..]));
    }

    // `zc down [--port BASE] [--broker-port PORT]`
    if args.get(1).map(|a| a == "down").unwrap_or(false) {
        if let Some(code) = agent::handoff::try_down() {
            std::process::exit(code);
        }
        let down_args: Vec<String> = args[2..].to_vec();
        let (_, base_port, broker_port, _) = up::parse_args(&down_args);
        // Scan worker range: base_port to base_port+39
        up::stop_up(broker_port, base_port, base_port + 39);
        return;
    }

    // `zc hooks <add|get|list|update|remove|logs> …` — variable args, parsed in hooks.rs.
    // Delegated to the `zc-hooks` sidecar binary rather than linked in.
    // `hooks` is the only code in zc that needs the private zakuro-client git
    // dependency, and cargo refuses to publish a crate whose manifest names a
    // git source -- optional ones included. Confining that dep to the
    // `publish = false` zc-hooks crate is what lets zc2 reach crates.io (#104).
    //
    // Looked up next to the running executable first so a release bundle is
    // self-contained, then on PATH. Exit status is forwarded so scripts calling
    // `zc hooks` keep working unchanged.
    if args.get(1).map(|a| a == "hooks").unwrap_or(false) {
        let sibling = std::env::current_exe()
            .ok()
            .and_then(|p| p.parent().map(|d| d.join(HOOKS_BIN)));
        let sidecar = sibling
            .clone()
            .filter(|p| p.is_file())
            .unwrap_or_else(|| std::path::PathBuf::from(HOOKS_BIN));

        match std::process::Command::new(&sidecar)
            .args(&args[2..])
            .status()
        {
            Ok(st) => std::process::exit(st.code().unwrap_or(1)),
            Err(e) => {
                eprintln!("`zc hooks` needs the `{HOOKS_BIN}` helper, which was not found.");
                match &sibling {
                    Some(p) => eprintln!("  tried: {} then $PATH", p.display()),
                    None => eprintln!("  tried: $PATH"),
                }
                eprintln!("  reason: {e}");
                eprintln!();
                eprintln!("Install it alongside zc, or build it from the repo:");
                eprintln!("  cargo build --release -p zc-hooks   (requires zakuro-drive access)");
                std::process::exit(2);
            }
        }
    }

    // `zc init` / `zc login` — device-code sign-in (init.rs).
    if args.get(1).map(|a| a == "init").unwrap_or(false) {
        std::process::exit(init::run());
    }

    // `zc token create [--ttl N] [--label X]` — mint a one-time join token
    if args.get(1).map(|a| a == "token").unwrap_or(false)
        && args.get(2).map(|a| a == "create").unwrap_or(false)
    {
        std::process::exit(enroll::run_token_create(&args[3..]));
    }

    // `zc join <zj_token> [--api-url URL] [--force]` — headless enrollment
    if args.get(1).map(|a| a == "join").unwrap_or(false) {
        std::process::exit(enroll::run_join(&args[2..]));
    }

    // `zc serve zc://{uuid} [zc://{uuid2} …] [--price P] [--port PORT] [--api-url URL] [--general]`
    // — provider side of native model inference (specialized path).
    if args.get(1).map(|a| a == "serve").unwrap_or(false) {
        run_serve(&args[2..]);
        return;
    }

    // `zc infer zc://{uuid} -m "<prompt>" [--max-tokens N] [--system "<sys>"] [--broker <url>]`
    // — one-shot consumer call into a served model (Task 6, phase 1).
    if args.get(1).map(|a| a == "infer").unwrap_or(false) {
        run_infer(&args[2..]);
        return;
    }

    // `zc chat zc://{uuid} [--system "<sys>"] [--broker <url>]`
    // — interactive REPL over the same `/infer` route.
    if args.get(1).map(|a| a == "chat").unwrap_or(false) {
        run_chat(&args[2..]);
        return;
    }

    // `zc dataset get zc://owner/name [-o DIR] [--api-url URL]`
    // — fetch a public marketplace dataset. A noun namespace, so `zc dataset
    // ls`/`info` can follow without spending more top-level verbs.
    if args.get(1).map(|a| a == "dataset").unwrap_or(false) {
        std::process::exit(dataset::run(&args[2..]));
    }

    // `zc space worker [space_id]` — the in-container Spaces entrypoint
    // (singular `space`; the consumer-side `zc spaces …` is separate).
    if args.get(1).map(|a| a == "space").unwrap_or(false) {
        std::process::exit(spaces::worker::run_cli(&args[2..]));
    }

    match args.len() {
        1 => unreachable!(),
        2 => {
            let arg0 = &args[1];
            match &arg0[..] {
                "-h" => help(false),
                "--help" => help(false),
                "ps" => manager::ps(),
                "dist" => match common::dist() {
                    Ok(res) => {
                        println!("{}", res);
                    }
                    Err(why) => {
                        eprintln!("{}", why);
                    }
                },
                "images" => manager::images(),
                // "nmap" => network::nmap(),
                "launch" => launch(),
                "download_conf" => common::download_conf(),
                "download_auth" => common::download_auth(),
                "setup" => setup(),
                "pull" => manager::pull(),
                "workers" => {
                    let broker_url = match resolve_default_broker(None) {
                        Ok(u) => u,
                        Err(e) => {
                            eprintln!("Error: {}", e);
                            std::process::exit(1);
                        }
                    };
                    show_workers(&broker_url, None, json_flag, estimate_flag);
                }
                "brokers" => show_brokers_cmd(),
                "price" => std::process::exit(run_price(&args[2..])),
                "logs" => common::logs(true),
                "nodes" => manager::nodes(),
                "restart" => manager::restart(),
                "servers" => manager::server_list(),
                "add_worker" => manager::add_worker(),
                "kill" => manager::kill(),
                "connect" => manager::connect(),
                "rmi" => manager::rmi(),
                "--version" => common::version(),
                "-v" => common::version(),
                "vars" => {
                    if let Err(e) = common::context(None) {
                        eprintln!("Error reading context: {}", e);
                    }
                }
                "broker" => {
                    start_broker(None, None, false); // foreground mode
                }
                "up" => {
                    up::start_up(1, 3960, 9000, false);
                }
                "bench" => {
                    broker::bench::run_from_args(&args[2..]);
                }
                "info" => {
                    broker::info::print_info();
                }
                "me" | "whoami" | "credits" => match &zakuro_auth {
                    Some(auth) => show_user_info(auth),
                    None => require_auth(),
                },
                _ => help(false),
            }
        }
        3 => {
            let arg0 = &args[1];
            let arg1 = &args[2];
            match &arg0[..] {
                "--docker" => match &arg1[..] {
                    "rm" => manager::remove_container(),
                    _ => {
                        let _ = exec::zk0(&arg1[..]);
                    }
                },
                "-d" | "--daemon" => match &arg1[..] {
                    "rm" => manager::remove_container(),
                    "broker" => {
                        start_broker(None, None, true); // daemon mode
                    }
                    _ => {
                        let _ = exec::zk0(&arg1[..]);
                    }
                },
                "push" => {
                    manager::push(Some(&arg1[..]));
                }
                "context" => {
                    if let Err(e) = common::context(Some(&arg1[..])) {
                        eprintln!("Error setting context: {}", e);
                    }
                }
                "build" => {
                    common::build(Some(args));
                }
                "broker" => {
                    // broker <port>
                    let port: u16 = arg1.parse().unwrap_or(9000);
                    start_broker(None, Some(port), false); // foreground mode
                }
                "workers" => {
                    // `workers zc://node-<name>` filters the default broker's mesh view
                    // by node; `workers zc://<broker>` targets a specific broker.
                    if let Some(node) = arg1
                        .strip_prefix("zc://")
                        .filter(|rest| rest.starts_with("node-"))
                    {
                        // `workers zc://node-<name>` filters by node but still
                        // targets the *default* broker — no explicit broker
                        // target was given, so the auto-spawn path applies.
                        let broker_url = match resolve_default_broker(None) {
                            Ok(u) => u,
                            Err(e) => {
                                eprintln!("Error: {}", e);
                                std::process::exit(1);
                            }
                        };
                        show_workers(&broker_url, Some(node), json_flag, estimate_flag);
                    } else {
                        let broker_url = match broker::uri::resolve(arg1) {
                            Ok(u) => u,
                            Err(e) => {
                                eprintln!("Error: {}", e);
                                std::process::exit(1);
                            }
                        };
                        show_workers(&broker_url, None, json_flag, estimate_flag);
                    }
                }
                // `price [<value>|inherit]` — through the agent when it is
                // running, otherwise straight to the hub.
                "price" => std::process::exit(run_price(&args[2..])),
                "bench" => {
                    // bench <url> or bench <option>
                    broker::bench::run_from_args(&args[2..]);
                }
                _ => help(false),
            }
        }
        4 => {
            let arg0 = &args[1];
            let arg1 = &args[2];
            let arg2 = &args[3];
            match &arg0[..] {
                "-d" | "--daemon" => match &arg1[..] {
                    "broker" => {
                        // -d broker <port>
                        let port: u16 = arg2.parse().unwrap_or(9000);
                        start_broker(None, Some(port), true); // daemon mode
                    }
                    _ => help(false),
                },
                "broker" => {
                    // broker <host> <port>
                    let port: u16 = arg2.parse().unwrap_or(9000);
                    start_broker(Some(arg1), Some(port), false); // foreground mode
                }
                // `price default <value>`
                "price" => std::process::exit(run_price(&args[2..])),
                // Forward the 4-token `zc bench …` form (e.g. `bench -s best_latency`,
                // `bench mesh -h`) — the other arms route bench but this one missed it.
                "bench" => {
                    broker::bench::run_from_args(&args[2..]);
                }
                _ => help(false),
            }
        }
        _ => {
            let arg0 = &args[1];
            match &arg0[..] {
                "build" => {
                    common::build(Some(args));
                }
                "bench" => {
                    // Pass remaining args to bench
                    let bench_args: Vec<String> = args[2..].to_vec();
                    broker::bench::run_from_args(&bench_args);
                }
                "up" => {
                    let up_args: Vec<String> = args[2..].to_vec();
                    let (workers, base_port, broker_port, daemon) = up::parse_args(&up_args);
                    up::apply_price_arg(&up_args);
                    up::start_up(workers, base_port, broker_port, daemon);
                }
                _ => {
                    help(false);
                }
            }
        }
    }
}

/// `zc brokers` — list the mesh brokers this node can reach, IP-free.
///
/// Renders the `GET /brokers` response (see `broker/server.rs::handle_brokers`)
/// into human-readable output. This is the seam under unit test: it must never
/// emit an IP or raw peer_url, only key-derived `zc://node-<fp>` ids.
#[cfg(test)]
mod json_flag_tests {
    use super::*;

    fn argv(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn ls_has_the_flag_stripped_so_its_length_match_still_works() {
        let (args, present) = extract_json_flag(argv(&["zc", "ls", "--json"]));
        assert!(present);
        assert_eq!(args, argv(&["zc", "ls"]));
    }

    #[test]
    fn bench_keeps_the_flag_because_it_parses_it_itself() {
        // Stripping it here made `zc bench --json` print the human view to
        // stdout and emit no document at all.
        let (args, present) = extract_json_flag(argv(&["zc", "bench", "-n", "20", "--json"]));
        assert!(present);
        assert_eq!(args, argv(&["zc", "bench", "-n", "20", "--json"]));
    }

    #[test]
    fn a_command_without_the_flag_is_untouched() {
        let (args, present) = extract_json_flag(argv(&["zc", "bench", "-n", "20"]));
        assert!(!present);
        assert_eq!(args, argv(&["zc", "bench", "-n", "20"]));
    }
}

#[cfg(test)]
mod alias_tests {
    use super::normalize_aliases;

    fn norm(cmd: &[&str]) -> Vec<String> {
        normalize_aliases(cmd.iter().map(|s| s.to_string()).collect())
    }

    #[test]
    fn maps_primary_verbs_to_canonical() {
        assert_eq!(norm(&["zc", "login"]), vec!["zc", "init"]);
        assert_eq!(
            norm(&["zc", "share", "--workers", "4"]),
            vec!["zc", "up", "--workers", "4"]
        );
        assert_eq!(norm(&["zc", "unshare"]), vec!["zc", "down"]);
        assert_eq!(norm(&["zc", "ls"]), vec!["zc", "workers"]);
    }

    #[test]
    fn mesh_verbs_expand_to_vpn_subcommand() {
        assert_eq!(
            norm(&["zc", "connect", "--docker"]),
            vec!["zc", "vpn", "connect", "--docker"]
        );
        assert_eq!(norm(&["zc", "disconnect"]), vec!["zc", "vpn", "disconnect"]);
        assert_eq!(norm(&["zc", "status"]), vec!["zc", "vpn", "status"]);
    }

    #[test]
    fn unknown_and_empty_pass_through() {
        assert_eq!(norm(&["zc", "me"]), vec!["zc", "me"]);
        assert_eq!(norm(&["zc"]), vec!["zc"]);
        // Old names are untouched (they're the alias targets).
        assert_eq!(
            norm(&["zc", "vpn", "connect"]),
            vec!["zc", "vpn", "connect"]
        );
    }
}

#[cfg(test)]
mod brokers_cli_tests {
    use super::render_brokers_output;
    use serde_json::json;

    /// A `/brokers` response shaped like the real handler's, but deliberately
    /// salted with IP-shaped strings an old/buggy renderer might leak.
    fn sample_brokers_json_with_internal_ips() -> serde_json::Value {
        json!({
            "self": "zc://node-aaaaaaaaaaaaaaaa",
            "self_build": {"version": "0.0.33", "git": "0447049", "binary_sha256": "aa".repeat(32)},
            "brokers": [
                {"id": "zc://node-deadbeefcafebabe", "reachable": true, "peer_url": "http://10.13.13.5:9000",
                 "build": {"version": "0.0.33", "git": "0447049", "binary_sha256": "aa".repeat(32)}},
                {"id": "zc://node-0123456789abcdef", "reachable": false, "peer_url": "http://127.0.0.1:9001",
                 "build": null}
            ]
        })
    }

    #[test]
    fn brokers_output_is_ip_free() {
        let body = render_brokers_output(&sample_brokers_json_with_internal_ips());
        assert!(!body.contains("10.13.13."));
        assert!(!body.contains("127.0.0.1"));
        assert!(body.contains("zc://node-"));
    }

    /// The point of the column (zc#305): the build each broker reports is
    /// printed, self included, so skew is readable without parsing JSON.
    #[test]
    fn brokers_output_names_each_brokers_build() {
        let body = render_brokers_output(&sample_brokers_json_with_internal_ips());
        assert!(
            body.contains("0.0.33 (0447049) sha:aaaaaaaaaaaa"),
            "build label missing from:\n{body}"
        );
        assert_eq!(
            body.matches("0.0.33 (0447049) sha:aaaaaaaaaaaa").count(),
            2,
            "self and the one peer that disclosed a build"
        );
    }

    /// A peer with no cached advert yet, or one older than build disclosure,
    /// must read as unknown rather than silently borrowing another's build.
    #[test]
    fn a_peer_without_a_build_reads_as_undisclosed() {
        let body = render_brokers_output(&sample_brokers_json_with_internal_ips());
        assert!(body.contains("build undisclosed"), "{body}");
    }

    /// The whole response may predate the field; the renderer must not panic
    /// or drop the brokers it can still show.
    #[test]
    fn a_response_with_no_build_fields_at_all_still_renders() {
        let body = render_brokers_output(&json!({
            "self": "zc://node-aaaaaaaaaaaaaaaa",
            "brokers": [{"id": "zc://node-deadbeefcafebabe", "reachable": true}]
        }));
        assert!(body.contains("zc://node-deadbeefcafebabe"), "{body}");
        assert_eq!(body.matches("build undisclosed").count(), 2);
    }
}

/// Tests for the `--json` modifier on `workers`/`ls` (acceptance criterion:
/// "a logged-in zc must list all brokers on the mesh with their price and
/// compute capabilities, live"). `show_workers`'s JSON branch prints the raw
/// `/workers` broker response verbatim, so these tests pin the two seams
/// callers depend on: (1) `--json` is recognised and stripped regardless of
/// position, and (2) the `WorkerInfo` wire shape it passes through already
/// carries `price_per_hour`, `cpus_available` and `memory_available_gib` per
/// worker (see `broker/server.rs::WorkerInfo`/`worker_to_info`).
#[cfg(test)]
mod json_listing_tests {
    use super::extract_json_flag;
    use serde_json::json;

    fn strip(cmd: &[&str]) -> (Vec<String>, bool) {
        extract_json_flag(cmd.iter().map(|s| s.to_string()).collect())
    }

    #[test]
    fn detects_and_strips_trailing_json_flag() {
        let (args, present) = strip(&["zc", "workers", "--json"]);
        assert!(present);
        assert_eq!(args, vec!["zc", "workers"]);
    }

    #[test]
    fn detects_and_strips_json_flag_before_positional_args() {
        // `zc ls` normalizes to `zc workers`; `--json` may land before a node filter.
        let (args, present) = strip(&["zc", "workers", "--json", "zc://node-abc123"]);
        assert!(present);
        assert_eq!(args, vec!["zc", "workers", "zc://node-abc123"]);
    }

    #[test]
    fn absent_json_flag_leaves_args_untouched() {
        let (args, present) = strip(&["zc", "workers"]);
        assert!(!present);
        assert_eq!(args, vec!["zc", "workers"]);
    }

    /// Pins the JSON schema `check_listing` in zak-journey's
    /// `journey/mesh/listing.py` parses: a `{"workers": [...]}` body whose
    /// entries carry non-null `price_per_hour`, `cpus_available` and
    /// `memory_available_gib` alongside `name`/`node`.
    #[test]
    fn worker_listing_json_carries_price_and_capability_fields() {
        let body = json!({
            "total": 1,
            "workers": [{
                "id": "w1",
                "name": "worker-1",
                "uri": "zc://worker-node-abc-1",
                "worker_type": "cpu",
                "status": "healthy",
                "cpus_available": 8.0,
                "cpus_total": 8.0,
                "memory_available_gib": 32.0,
                "memory_total_gib": 32.0,
                "gpus_available": 0,
                "gpus_total": 0,
                "price_per_hour": 3.6,
                "min_charge": 0.0,
                "active_requests": 0,
                "avg_latency_ms": 0.0,
                "max_timeout_secs": 60.0,
                "requests_5h": 0, "requests_1w": 0, "requests_1m": 0,
                "quota_5h": 0, "quota_1w": 0, "quota_1m": 0,
                "node": "zc://node-abc123",
            }],
        });

        let workers = body.get("workers").and_then(|v| v.as_array()).unwrap();
        let w = &workers[0];
        assert!(w.get("node").and_then(|v| v.as_str()).is_some());
        assert!(w.get("price_per_hour").and_then(|v| v.as_f64()).is_some());
        assert!(w.get("cpus_available").and_then(|v| v.as_f64()).is_some());
        assert!(w
            .get("memory_available_gib")
            .and_then(|v| v.as_f64())
            .is_some());
        // No IP-shaped fields — the JSON path reuses the same client-facing
        // /workers response as the human table, which is already IP-free.
        assert!(!body.to_string().contains("127.0.0.1"));
    }
}

/// Tests for the `--estimate` modifier on `workers`/`ls`: it is stripped like
/// `--json`, and it is what makes `show_workers` ask the broker for each
/// worker's posterior (`GET /workers?estimate=1`) instead of getting the
/// plain listing that omits it by default.
#[cfg(test)]
mod estimate_flag_tests {
    use super::{extract_estimate_flag, workers_request_url};

    fn strip(cmd: &[&str]) -> (Vec<String>, bool) {
        extract_estimate_flag(cmd.iter().map(|s| s.to_string()).collect())
    }

    #[test]
    fn detects_and_strips_trailing_estimate_flag() {
        let (args, present) = strip(&["zc", "workers", "--estimate"]);
        assert!(present);
        assert_eq!(args, vec!["zc", "workers"]);
    }

    #[test]
    fn absent_estimate_flag_leaves_args_untouched() {
        let (args, present) = strip(&["zc", "workers"]);
        assert!(!present);
        assert_eq!(args, vec!["zc", "workers"]);
    }

    #[test]
    fn plain_request_carries_no_query_by_default() {
        assert_eq!(
            workers_request_url("http://localhost:9000", None, false),
            "http://localhost:9000/workers"
        );
    }

    #[test]
    fn estimate_flag_adds_the_opt_in_query_param() {
        assert_eq!(
            workers_request_url("http://localhost:9000", None, true),
            "http://localhost:9000/workers?estimate=1"
        );
    }

    #[test]
    fn node_filter_and_estimate_combine_into_one_query_string() {
        assert_eq!(
            workers_request_url("http://localhost:9000", Some("zc://node-abc"), true),
            "http://localhost:9000/workers?node=node-abc&estimate=1"
        );
    }
}

/// Run `zc price …`: through the agent when it is running, straight to the
/// hub when it is not.
fn run_price(args: &[String]) -> i32 {
    match parse_price_args(args) {
        // Hub-only commands about the benchmark band: no agent involved.
        Ok(PriceCmd::Recommend) => bench_node::cli::price_recommend(),
        Ok(PriceCmd::Auto) => bench_node::cli::price_auto(),
        Ok(cmd) => {
            let code =
                agent::handoff::try_price(cmd).unwrap_or_else(|| agent::handoff::price_direct(cmd));
            // A price of its own ends auto mode.
            if code == 0 && matches!(cmd, PriceCmd::Device(_)) {
                bench_node::cli::price_fixed();
            }
            code
        }
        Err(e) => {
            eprintln!("Error: {e}");
            eprintln!("{PRICE_USAGE}");
            2
        }
    }
}

/// What `zc price […]` was asked for.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PriceCmd {
    /// `zc price` — what this Mac charges now.
    Show,
    /// `zc price <n>` — this Mac charges `n` credits/hour.
    Device(f64),
    /// `zc price inherit` — this Mac follows the account default again.
    Inherit,
    /// `zc price default <n>` — the account default, for every device.
    Default(f64),
    /// `zc price default mesh` — the account default follows the mesh price
    /// again, mirroring what `inherit` does one level down.
    DefaultMesh,
    /// `zc price recommend` — the mesh price band for this node.
    Recommend,
    /// `zc price auto` — follow the mesh median.
    Auto,
}

impl PriceCmd {
    /// The credits/hour this command carries, for the one bounds check both
    /// writing paths make before they send anything.
    pub fn value(self) -> Option<f64> {
        match self {
            PriceCmd::Device(v) | PriceCmd::Default(v) => Some(v),
            PriceCmd::Show
            | PriceCmd::Inherit
            | PriceCmd::DefaultMesh
            | PriceCmd::Recommend
            | PriceCmd::Auto => None,
        }
    }
}

pub const PRICE_USAGE: &str = "Usage: zc price                    What this Mac charges
       zc price <credits/hour>     Set what this Mac charges
       zc price inherit            Follow the account default again
       zc price default <c/h>      Set the account default for every device
       zc price default mesh       Follow the mesh price again, account-wide
       zc price recommend          The mesh price band for this node
       zc price auto               Follow the mesh median price";

/// Parse the words after `zc price`.
fn parse_price_args(args: &[String]) -> Result<PriceCmd, String> {
    let words: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
    match words[..] {
        [] => Ok(PriceCmd::Show),
        ["inherit"] => Ok(PriceCmd::Inherit),
        ["recommend"] => Ok(PriceCmd::Recommend),
        ["auto"] => Ok(PriceCmd::Auto),
        ["default"] => Err("`zc price default` needs a value in credits/hour".to_string()),
        ["default", "mesh"] => Ok(PriceCmd::DefaultMesh),
        ["default", v] => parse_price_arg(v).map(PriceCmd::Default),
        [v] => parse_price_arg(v).map(PriceCmd::Device),
        _ => Err(format!(
            "`zc price {}` is not a price command",
            words.join(" ")
        )),
    }
}

/// `zc price <value>`: a finite number of credits/hour. `nan` and `inf` parse
/// as `f64`, but JSON has no such values: sent, they would become `null`,
/// which clears this Mac's price back to the account default.
fn parse_price_arg(s: &str) -> Result<f64, String> {
    match s.parse::<f64>() {
        Ok(v) if v.is_finite() => Ok(v),
        Ok(_) => Err(format!(
            "invalid price value '{s}': the price must be a finite number of credits/hour"
        )),
        Err(_) => Err(format!("invalid price value '{s}'")),
    }
}

#[cfg(test)]
mod price_command_tests {
    use super::{parse_price_args, PriceCmd};

    fn parse(words: &[&str]) -> Result<PriceCmd, String> {
        let owned: Vec<String> = words.iter().map(|w| w.to_string()).collect();
        parse_price_args(&owned)
    }

    #[test]
    fn each_form_maps_to_one_command() {
        assert_eq!(parse(&[]), Ok(PriceCmd::Show));
        assert_eq!(parse(&["18"]), Ok(PriceCmd::Device(18.0)));
        assert_eq!(parse(&["3.6"]), Ok(PriceCmd::Device(3.6)));
        assert_eq!(parse(&["inherit"]), Ok(PriceCmd::Inherit));
        assert_eq!(parse(&["default", "42"]), Ok(PriceCmd::Default(42.0)));
        assert_eq!(parse(&["default", "mesh"]), Ok(PriceCmd::DefaultMesh));
        assert_eq!(parse(&["recommend"]), Ok(PriceCmd::Recommend));
        assert_eq!(parse(&["auto"]), Ok(PriceCmd::Auto));
    }

    #[test]
    fn a_form_that_would_clear_or_mangle_a_price_is_refused() {
        // `nan` / `inf` serialize as JSON null, which the hub reads as
        // "follow the account default": neither may reach it as a value.
        for bad in [
            vec!["nan"],
            vec!["inf"],
            vec!["-inf"],
            vec!["abc"],
            vec![""],
            vec!["default"],
            vec!["default", "nan"],
            vec!["default", "abc"],
            vec!["inherit", "18"],
            vec!["18", "42"],
            vec!["default", "42", "18"],
            vec!["default", "mesh", "18"],
            vec!["mesh"],
        ] {
            assert!(parse(&bad).is_err(), "{bad:?} must be refused");
        }
        assert!(parse(&["default"]).unwrap_err().contains("credits/hour"));
    }
}

#[cfg(test)]
mod price_arg_tests {
    use super::parse_price_arg;

    #[test]
    fn a_price_argument_must_be_a_finite_number() {
        assert_eq!(parse_price_arg("18"), Ok(18.0));
        assert_eq!(parse_price_arg("3.6"), Ok(3.6));
        for bad in ["nan", "NaN", "inf", "-inf", "infinity", "abc", ""] {
            assert!(parse_price_arg(bad).is_err(), "{bad:?} must be refused");
        }
        let e = parse_price_arg("nan").unwrap_err();
        assert!(e.contains("finite"), "{e}");
    }
}

#[cfg(test)]
mod broker_target_tests {
    use super::broker_unreachable;
    use crate::vpn::is_loopback_url;

    #[test]
    fn only_this_machine_counts_as_a_loopback_broker() {
        for (url, want) in [
            ("http://localhost:9001", true),
            ("http://LOCALHOST:9000", true),
            ("http://127.0.0.1:9001/workers", true),
            ("http://127.0.0.53:9000", true),
            ("http://[::1]:9000/health", true),
            ("http://10.13.13.5:9000", false),
            ("https://stg.api.zakuro-ai.com", false),
            ("http://localhost.example.com:9000", false),
            ("http://my-127.0.0.1.example:9000", false),
            ("not a url", false),
        ] {
            assert_eq!(is_loopback_url(url), want, "{url}");
        }
    }

    #[test]
    fn only_a_broker_that_never_answered_is_unreachable() {
        use std::io::{Error, ErrorKind};
        assert!(broker_unreachable(&ureq::Error::ConnectionFailed));
        assert!(broker_unreachable(&ureq::Error::HostNotFound));
        assert!(broker_unreachable(&ureq::Error::Io(Error::from(
            ErrorKind::ConnectionRefused
        ))));
        assert!(broker_unreachable(&ureq::Error::Timeout(
            ureq::Timeout::Connect
        )));
        // Something answered. Starting a second broker on its port can only
        // fail, so the reply is the error to report.
        assert!(!broker_unreachable(&ureq::Error::StatusCode(500)));
        assert!(!broker_unreachable(&ureq::Error::StatusCode(404)));
    }
}

#[cfg(test)]
mod workers_table_tests {
    use super::render_workers_table;

    /// Each line's visible text: colour escapes removed, so the assertions
    /// below measure what a reader actually sees.
    fn visible(table: &str) -> Vec<String> {
        let mut out = Vec::new();
        for line in table.lines() {
            let mut s = String::new();
            let mut chars = line.chars();
            while let Some(c) = chars.next() {
                if c == '\u{1b}' {
                    for e in chars.by_ref() {
                        if e == 'm' {
                            break;
                        }
                    }
                } else {
                    s.push(c);
                }
            }
            out.push(s);
        }
        out
    }

    /// The lines that form the grid: the two rules, the header, the rows.
    fn grid(table: &str) -> Vec<String> {
        visible(table)
            .into_iter()
            .filter(|l| l.contains('─') || l.contains("WORKER") || l.starts_with("    "))
            .collect()
    }

    /// Put a worker under the broker that owns it.
    fn with_node(mut w: serde_json::Value, node: &str) -> serde_json::Value {
        w["node"] = serde_json::json!(node);
        w
    }

    fn worker(name: &str, uri: &str, cpus: f64, mem: f64, price: f64) -> serde_json::Value {
        serde_json::json!({
            "name": name, "status": "healthy", "uri": uri,
            "node": "zc://node-dd715b7f6d94d44e",
            "cpus_available": cpus, "gpus_available": 0,
            "memory_available_gib": mem, "price_per_hour": price,
        })
    }

    /// Real rows from the staging mesh. Names reach 31 characters and
    /// addresses 33, where the table used to reserve 18 and 24, so every one
    /// of these rows ran past its columns and stopped matching the header.
    fn staging_rows() -> Vec<serde_json::Value> {
        vec![
            worker(
                "dd715b7f-w0",
                "zc://worker-dd715b7f6d94d44e-3960",
                10.0,
                3.4,
                20.0,
            ),
            worker(
                "worker-zc-worker-cloudcompute-2",
                "zc://worker-af185d3fcc82649f-3960",
                8.0,
                15.5,
                3.6,
            ),
        ]
    }

    #[test]
    fn every_row_lines_up_with_the_header() {
        let rows = staging_rows();
        let table = render_workers_table(&rows, rows.len() as u64, "http://localhost:9000");
        let grid = grid(&table);
        assert!(
            grid.len() >= 5,
            "two rules, a header and two rows: {grid:?}"
        );

        let widths: Vec<usize> = grid.iter().map(|l| l.chars().count()).collect();
        assert!(
            widths.windows(2).all(|w| w[0] == w[1]),
            "every line of the grid is the same width: {widths:?}\n{table}"
        );

        let header = grid
            .iter()
            .find(|l| l.contains("WORKER"))
            .expect("a header");
        // The broker heads its group; repeating it on every row would only
        // push the table past a readable width.
        assert!(
            !header.contains("BROKER"),
            "no per-row broker column: {header}"
        );
        // The budget: the widest names and `zc://` addresses on the mesh,
        // two-space gaps, and no column that repeats another. Dropping NODE
        // bought 18 of these columns; adding one back blows the budget.
        assert!(
            widths[0] <= 130,
            "the table stays within a wide terminal: {} columns\n{table}",
            widths[0]
        );

        let name_at = header.find("WORKER").expect("a WORKER column");
        let price_end = header.find("PRICE").expect("a PRICE column") + "PRICE".len();
        let mut worker_lines = grid
            .iter()
            .filter(|l| l.starts_with("    ") && !l.contains("WORKER"));
        for w in rows.iter() {
            let line = worker_lines.next().expect("a row per worker");
            let name = w["name"].as_str().unwrap();
            assert_eq!(
                &line[name_at..name_at + name.len()],
                name,
                "NAME starts in its column: {line}"
            );
            assert!(
                line[..price_end].ends_with(&["20", "3.6"][usize::from(name.len() > 11)]),
                "PRICE ends in its column: {line}"
            );
        }
    }

    /// Two brokers, three workers. A worker is not addressable: a broker
    /// owns one or more of them and picks which one runs a job, so the only
    /// address here is the broker's, printed once above the workers it owns.
    #[test]
    fn workers_are_listed_under_the_broker_that_owns_them() {
        let i9 = "zc://node-e18d8c0ed6ec7b5a";
        let x399 = "zc://node-6188100f5daf463e";
        let rows = vec![
            with_node(
                worker(
                    "worker-zc-worker-i9-1",
                    "zc://worker-e18d8c0ed6ec7b5a-3960",
                    20.0,
                    31.0,
                    3.6,
                ),
                i9,
            ),
            with_node(
                worker(
                    "worker-zc-worker-x399-1",
                    "zc://worker-6188100f5daf463e-3960",
                    32.0,
                    62.6,
                    3.6,
                ),
                x399,
            ),
            with_node(
                worker(
                    "worker-zc-worker-i9-2",
                    "zc://worker-d2f66b53e3fe399f-3960",
                    20.0,
                    31.0,
                    3.6,
                ),
                i9,
            ),
        ];
        let table = render_workers_table(&rows, rows.len() as u64, "http://localhost:9000");
        let lines = visible(&table);

        assert!(
            !table.contains("zc://worker-"),
            "no worker address is offered as a target:\n{table}"
        );
        for id in [i9, x399] {
            assert_eq!(
                lines.iter().filter(|l| l.contains(id)).count(),
                1,
                "{id} names its group once:\n{table}"
            );
        }
        // The two i9 workers sit together, under their broker.
        let at = |needle: &str| {
            lines
                .iter()
                .position(|l| l.contains(needle))
                .unwrap_or_else(|| panic!("{needle} is listed:\n{table}"))
        };
        // Each broker is followed by its own workers and nothing else, so a
        // group never interleaves with another. (Groups are ordered by broker
        // id, so which one comes first is not part of the contract.)
        assert_eq!(
            at(i9) + 1,
            at("worker-zc-worker-i9-1"),
            "the i9 broker heads its own workers:\n{table}"
        );
        assert_eq!(
            at("worker-zc-worker-i9-2"),
            at("worker-zc-worker-i9-1") + 1,
            "and they stay together:\n{table}"
        );
        assert_eq!(
            at(x399) + 1,
            at("worker-zc-worker-x399-1"),
            "the x399 broker heads its own worker:\n{table}"
        );
        // The counts people read first: how many places can take a job, and
        // how much compute sits behind them.
        let head = lines
            .iter()
            .find(|l| l.contains("broker"))
            .expect("a summary line");
        assert!(
            head.contains('2') && head.contains('3'),
            "2 brokers, 3 workers: {head}"
        );
    }

    #[test]
    fn numbers_carry_no_digits_they_do_not_need() {
        let rows = staging_rows();
        let table = render_workers_table(&rows, rows.len() as u64, "http://localhost:9000");
        for noise in ["20.000", "3.600", "10.0 ", "8.0 "] {
            assert!(
                !table.contains(noise),
                "{noise:?} is padding, not information:\n{table}"
            );
        }
        // A price that needs its decimals keeps them.
        let priced = vec![worker("w0", "zc://worker-a-3960", 2.0, 1.0, 3.625)];
        assert!(
            render_workers_table(&priced, 1, "http://localhost:9000").contains("3.625"),
            "a real fraction survives"
        );
    }

    fn with_estimate(
        mut w: serde_json::Value,
        observations: f64,
        median_service_ms: Option<f64>,
    ) -> serde_json::Value {
        w["estimate"] = serde_json::json!({
            "observations": observations,
            "median_service_ms": median_service_ms,
            "log_sd": null,
        });
        w
    }

    /// Talking to an older broker (or a plain `zc ls` against a new one, since
    /// the estimate is opt-in), the payload carries no `estimate` field at
    /// all. That must degrade to exactly today's table — no EST/OBS column —
    /// not a column full of blanks.
    #[test]
    fn no_estimate_field_means_no_estimate_column() {
        let rows = staging_rows();
        let table = render_workers_table(&rows, rows.len() as u64, "http://localhost:9000");
        assert!(
            !table.contains("EST") && !table.contains("OBS"),
            "an older/plain response has nothing to show here:\n{table}"
        );
    }

    /// The whole point of the feature: a worker the broker has never measured
    /// must not print as `0` or as a confident-looking number. It has to be
    /// visibly a "nothing here yet" marker instead.
    #[test]
    fn never_measured_is_a_dash_not_a_zero() {
        let rows = vec![with_estimate(
            worker("w0", "zc://worker-a-3960", 2.0, 1.0, 3.6),
            0.0,
            None,
        )];
        let table = render_workers_table(&rows, 1, "http://localhost:9000");
        assert!(table.contains("EST"), "the column appears once requested");
        assert!(
            !table.contains(" 0ms") && !table.contains("0.0ms"),
            "never measured must not read as an instant, confident answer:\n{table}"
        );
        assert!(
            table.contains('—'),
            "never measured renders as the same dash used elsewhere for unknown: {table}"
        );
    }

    /// A measured worker shows its posterior median and how many observations
    /// back it — the two numbers an operator reads at a glance, per zc#267.
    #[test]
    fn a_measured_worker_shows_its_median_and_observation_count() {
        let rows = vec![with_estimate(
            worker("w0", "zc://worker-a-3960", 2.0, 1.0, 3.6),
            12.0,
            Some(82.4),
        )];
        let table = render_workers_table(&rows, 1, "http://localhost:9000");
        assert!(
            table.contains("82ms") || table.contains("82.4ms"),
            "{table}"
        );
        assert!(
            table.contains("12"),
            "observation count is visible: {table}"
        );
    }

    /// Adding the EST/OBS columns must not break the row/header alignment
    /// contract: every grid line is still the same width, and the table still
    /// fits comfortably on a normal terminal.
    #[test]
    fn estimate_columns_keep_rows_aligned_with_the_header() {
        let rows: Vec<serde_json::Value> = staging_rows()
            .into_iter()
            .enumerate()
            .map(|(i, w)| match i {
                0 => with_estimate(w, 0.0, None),
                _ => with_estimate(w, 12.0, Some(82.4)),
            })
            .collect();
        let table = render_workers_table(&rows, rows.len() as u64, "http://localhost:9000");
        let grid = grid(&table);
        let widths: Vec<usize> = grid.iter().map(|l| l.chars().count()).collect();
        assert!(
            widths.windows(2).all(|w| w[0] == w[1]),
            "every line of the grid is the same width once EST/OBS are added: {widths:?}\n{table}"
        );
        assert!(
            widths[0] <= 150,
            "still fits a wide terminal: {} columns\n{table}",
            widths[0]
        );
    }
}

#[cfg(test)]
mod mesh_listing_tests {
    use super::{render_mesh_listing, ListedBroker, Listing};

    fn plain(s: &str) -> String {
        let mut out = String::new();
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\u{1b}' {
                for e in chars.by_ref() {
                    if e == 'm' {
                        break;
                    }
                }
            } else {
                out.push(c);
            }
        }
        out
    }

    fn worker(name: &str, fp: &str, cpus: f64) -> serde_json::Value {
        serde_json::json!({
            "name": name,
            "node": format!("zc://node-{fp}"),
            "status": "healthy",
            "cpus_available": cpus,
        })
    }

    fn broker(fp: &str, name: &str, is_self: bool) -> ListedBroker {
        ListedBroker {
            fp: fp.to_string(),
            name: Some(name.to_string()),
            is_self,
        }
    }

    /// The hub knows every broker the mesh authorises; one broker knows only
    /// what it has discovered. Listing from the hub is the difference between
    /// "these are the brokers" and "these are the ones we happened to find".
    #[test]
    fn a_directory_listing_names_only_brokers_with_workers() {
        let brokers = vec![
            broker("aaa1", "zc-worker-i9-1", false),
            broker("bbb2", "CADICs-MacBook-Pro.local", true),
            broker("ccc3", "zc-broker-0", false),
        ];
        let workers = vec![
            worker("i9-w0", "aaa1", 20.0),
            worker("dd-w0", "bbb2", 10.0),
            worker("dd-w1", "bbb2", 10.0),
        ];
        let out = plain(&render_mesh_listing(
            &brokers,
            &workers,
            &Listing::Directory {
                unreachable: 1,
                offline: 116,
                as_of_secs: None,
            },
        ));

        assert!(out.contains("2 node(s) · 3 worker(s)"), "{out}");
        for fp in ["aaa1", "bbb2"] {
            assert!(
                out.contains(&format!("zc://node-{fp}")),
                "{fp} listed: {out}"
            );
        }
        assert!(
            out.contains("zc-worker-i9-1"),
            "names come from the hub: {out}"
        );
        assert!(out.contains("(this machine)"), "{out}");
        // Nothing to read or use: not listed, not counted.
        for gone in [
            "ccc3",
            "zc-broker-0",
            "no worker detail",
            "unreachable",
            "mesh endpoint",
        ] {
            assert!(!out.contains(gone), "{gone} shown: {out}");
        }
    }

    /// The table zakuro-ai.com shows under a node: one header, one row per
    /// worker, numbers right-aligned under their column.
    #[test]
    fn a_node_lists_its_workers_as_the_landing_page_table() {
        let brokers = vec![broker("4f2a9c1b8e7d0a35", "gpu-box", false)];
        let mut a = worker("gpu-04", "4f2a9c1b8e7d0a35", 32.0);
        a["gpus_total"] = serde_json::json!(4);
        a["memory_total_gib"] = serde_json::json!(256.0);
        a["price_per_hour"] = serde_json::json!(3.6);
        let mut b = worker("gpu-07", "4f2a9c1b8e7d0a35", 16.0);
        b["gpus_total"] = serde_json::json!(2);
        b["memory_total_gib"] = serde_json::json!(128.0);
        b["price_per_hour"] = serde_json::json!(2.9);
        let out = plain(&render_mesh_listing(
            &brokers,
            &[a, b],
            &Listing::Directory {
                unreachable: 0,
                offline: 0,
                as_of_secs: None,
            },
        ));
        assert!(
            out.contains(
                "zc://node-4f2a9c1b8e7d0a35  gpu-box\n\
                 \x20   WORKER  STATUS  CPUs  GPUs   MEM  PRICE\n\
                 \x20   gpu-04  ready     32     4  256G    3.6\n\
                 \x20   gpu-07  ready     16     2  128G    2.9\n"
            ),
            "{out}"
        );
        assert!(out.contains("PRICE in zkcr/h"), "{out}");
    }

    /// `healthy` is the broker's word; the column asks whether a worker will
    /// take work. Every other status is the broker's own.
    #[test]
    fn statuses_read_ready_or_as_the_broker_says() {
        let mut d = worker("w1", "bbb2", 10.0);
        d["status"] = serde_json::json!("draining");
        let mut f = worker("w2", "bbb2", 10.0);
        f["price_per_hour"] = serde_json::json!(0.0);
        let out = plain(&render_mesh_listing(
            &[],
            &[d, f],
            &Listing::LocalOnly("hub unreachable".to_string()),
        ));
        assert!(out.contains("draining"), "{out}");
        assert!(out.contains("ready"), "{out}");
        assert!(out.contains("free"), "a zero price is free: {out}");
    }

    /// With the hub unreachable there is still something useful to print, and
    /// it has to say what it is rather than looking like the whole mesh.
    #[test]
    fn a_local_only_listing_says_so() {
        let workers = vec![worker("dd-w0", "bbb2", 10.0), worker("dd-w1", "bbb2", 10.0)];
        let out = plain(&render_mesh_listing(
            &[],
            &workers,
            &Listing::LocalOnly("hub unreachable".to_string()),
        ));
        assert!(out.contains("This machine:"), "{out}");
        assert!(out.contains("hub unreachable"), "says why: {out}");
        assert!(out.contains("zc://node-bbb2"), "{out}");
        assert!(out.contains("1 node(s) · 2 worker(s)"), "{out}");
        assert!(
            !out.contains("unreachable ·"),
            "no mesh-wide counts it cannot know: {out}"
        );
    }

    #[test]
    fn an_empty_mesh_is_not_a_panic() {
        let out = plain(&render_mesh_listing(
            &[],
            &[],
            &Listing::Directory {
                unreachable: 0,
                offline: 0,
                as_of_secs: None,
            },
        ));
        assert!(out.contains("No workers available on the mesh."), "{out}");
    }
}