gang 1.0.0

CLI for Ganglion — reach, observe, and act on ROS 2 robots behind hostile networks
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
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::OutputFormat;

// --- Operator config ---

/// Operator configuration loaded from `~/.gang/config.toml`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OperatorConfig {
    /// Default relay multiaddr when --relay is not specified and the peer
    /// registry entry has no relay_addrs.
    pub default_relay: Option<String>,

    /// Identity verification policy: "strict" (default), "tofu", or "none".
    #[serde(default = "default_host_key_policy")]
    pub host_key_policy: String,
}

fn default_host_key_policy() -> String {
    "strict".to_string()
}

impl OperatorConfig {
    /// Load config from `~/.gang/config.toml`. Returns defaults if file is missing.
    pub fn load() -> Self {
        let path = gang_core::identity::default_config_dir().join("config.toml");
        Self::load_from(&path)
    }

    /// Load config from a specific path. Returns defaults if file is missing.
    pub fn load_from(path: &Path) -> Self {
        if !path.exists() {
            return Self::default();
        }
        match std::fs::read_to_string(path) {
            Ok(contents) => toml::from_str(&contents).unwrap_or_default(),
            Err(_) => Self::default(),
        }
    }

    /// Save config to `~/.gang/config.toml`.
    pub fn save(&self) -> anyhow::Result<()> {
        let path = gang_core::identity::default_config_dir().join("config.toml");
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let toml_str = toml::to_string_pretty(self)?;
        std::fs::write(&path, toml_str)?;
        Ok(())
    }
}

/// `gang status` — show version, identity, and capability summary.
pub async fn status(format: &OutputFormat) -> anyhow::Result<()> {
    let version = env!("CARGO_PKG_VERSION");

    // Check identity
    let key_path = gang_core::identity::default_key_path();
    let identity_status = if key_path.exists() {
        match gang_core::identity::Keypair::load(&key_path) {
            Ok(kp) => format!("{}", kp.peer_id()),
            Err(_) => "present but unreadable".to_string(),
        }
    } else {
        "not generated (run `gang identity generate`)".to_string()
    };

    // Registry count
    let reg_dir = registry_dir();
    let registry_count = match gang_core::registry::Registry::open(&reg_dir) {
        Ok(reg) => reg.list().len(),
        Err(_) => 0,
    };

    // Peer count
    let peer_registry =
        gang_core::identity::PeerRegistry::load(&gang_core::identity::default_registry_path())
            .unwrap_or_default();
    let peer_count = peer_registry.list().count();

    // Config
    let config = OperatorConfig::load();
    let config_path = gang_core::identity::default_config_dir().join("config.toml");

    let available = [
        "identity show",
        "identity generate",
        "sign",
        "agent",
        "deploy",
        "run",
        "caps",
        "demo",
        "diagnose",
        "transport-stats",
        "test-archetype",
        "push",
        "fetch",
        "artifacts",
        "capability scaffold",
        "registry search",
        "registry install",
        "registry publish",
        "registry list",
        "registry info",
        "peer add/remove/list/show/rename",
        "config show/set/init/path",
        "completions",
        "relay",
        "status",
    ];

    let wip = ["logs", "list", "connect"];

    match format {
        OutputFormat::Json => {
            let info = serde_json::json!({
                "version": version,
                "identity": identity_status,
                "key_path": key_path.display().to_string(),
                "registry_capabilities": registry_count,
                "registered_peers": peer_count,
                "config_path": config_path.display().to_string(),
                "default_relay": config.default_relay,
                "host_key_policy": config.host_key_policy,
                "available_commands": available,
                "wip_commands": wip,
            });
            println!("{}", serde_json::to_string_pretty(&info)?);
        }
        OutputFormat::Text => {
            println!("Ganglion v{version}");
            println!();
            println!("Identity:   {identity_status}");
            println!("Key file:   {}", key_path.display());
            println!("Registry:   {} capability(ies) registered", registry_count);
            println!("Peers:      {} registered", peer_count);
            println!(
                "Config:     {}",
                if config_path.exists() {
                    config_path.display().to_string()
                } else {
                    "(not initialized — run `gang config init`)".to_string()
                }
            );
            if let Some(relay) = &config.default_relay {
                println!("Def. relay: {relay}");
            }
            println!();
            println!("Available commands:");
            for cmd in &available {
                println!("  gang {cmd}");
            }
            println!();
            println!("WIP commands (require relay connectivity):");
            for cmd in &wip {
                println!("  gang {cmd}  [WIP]");
            }
        }
    }

    Ok(())
}

/// `gang identity show`
pub async fn identity_show() -> anyhow::Result<()> {
    let key_path = gang_core::identity::default_key_path();
    if !key_path.exists() {
        eprintln!("No identity found. Run `gang identity generate` first.");
        eprintln!("Expected key at: {}", key_path.display());
        std::process::exit(1);
    }

    let keypair = gang_core::identity::Keypair::load(&key_path)?;
    println!("Peer ID:    {}", keypair.peer_id());
    println!(
        "Public key: {}",
        hex::encode(keypair.public_key().as_bytes())
    );
    println!("Key file:   {}", key_path.display());
    Ok(())
}

/// `gang identity generate`
pub async fn identity_generate(force: bool) -> anyhow::Result<()> {
    let key_path = gang_core::identity::default_key_path();
    if key_path.exists() && !force {
        eprintln!("Identity already exists at {}.", key_path.display());
        eprintln!("Use --force to overwrite.");
        std::process::exit(1);
    }

    let keypair = gang_core::identity::Keypair::generate();
    keypair.save(&key_path)?;
    println!("Generated new identity:");
    println!("  Peer ID:  {}", keypair.peer_id());
    println!("  Key file: {}", key_path.display());
    Ok(())
}

// --- Target resolution ---

/// Resolved target for a robot command.
#[allow(dead_code)] // relay_addr used when remote dispatch is wired (ADR-020 Phase 32)
pub struct ResolvedTarget {
    /// The full peer ID (if remote).
    pub peer_id: Option<gang_core::identity::PeerId>,
    /// Relay multiaddr (if remote).
    pub relay_addr: Option<String>,
    /// Human-readable name (if registered).
    pub name: Option<String>,
    /// Whether this target is local-only (no network).
    pub is_local: bool,
}

/// Resolve a robot target string through the resolution chain:
/// 1. Explicit --peer flag (bypasses everything)
/// 2. Registered name in PeerRegistry
/// 3. Abbreviated peer ID prefix match (Docker-style)
/// 4. Full peer ID (37 chars)
/// 5. Local fallback (/tmp/gang-agent-{robot})
pub fn resolve_target(
    robot: &str,
    explicit_peer: Option<&str>,
    explicit_relay: Option<&str>,
) -> anyhow::Result<ResolvedTarget> {
    use gang_core::identity::{PeerId, PeerRegistry, default_registry_path};

    // Load config for default_relay fallback
    let config = OperatorConfig::load();

    // Relay resolution helper: CLI flag > peer registry entry > config default
    let resolve_relay =
        |explicit: Option<&str>, registry_addrs: Option<&Vec<String>>| -> Option<String> {
            explicit
                .map(String::from)
                .or_else(|| registry_addrs.and_then(|addrs| addrs.first().cloned()))
                .or_else(|| config.default_relay.clone())
        };

    // 1. Explicit --peer flag
    if let Some(peer_str) = explicit_peer {
        return Ok(ResolvedTarget {
            peer_id: Some(PeerId::new(peer_str)),
            relay_addr: resolve_relay(explicit_relay, None),
            name: None,
            is_local: false,
        });
    }

    // Load registry for name and prefix lookups
    let registry_path = default_registry_path();
    let registry = PeerRegistry::load(&registry_path).unwrap_or_default();

    // 2. Registered name
    if let Some(entry) = registry.lookup(robot) {
        return Ok(ResolvedTarget {
            peer_id: Some(entry.peer_id.clone()),
            relay_addr: resolve_relay(explicit_relay, Some(&entry.relay_addrs)),
            name: Some(robot.to_string()),
            is_local: false,
        });
    }

    // 3. Abbreviated peer ID prefix (must start with "12D3-")
    if robot.starts_with("12D3-") && robot.len() < 37 {
        let matches = registry.lookup_by_prefix(robot);
        match matches.len() {
            0 => anyhow::bail!(
                "No peer found matching prefix '{robot}'. Use `gang peer list` to see registered peers."
            ),
            1 => {
                let (name, entry) = matches[0];
                return Ok(ResolvedTarget {
                    peer_id: Some(entry.peer_id.clone()),
                    relay_addr: resolve_relay(explicit_relay, Some(&entry.relay_addrs)),
                    name: Some(name.to_string()),
                    is_local: false,
                });
            }
            n => {
                let mut msg = format!("Ambiguous peer ID prefix '{robot}' matches {n} peers:\n");
                for (name, entry) in &matches {
                    msg.push_str(&format!("  {} ({})\n", entry.peer_id, name));
                }
                msg.push_str("Provide a longer prefix to disambiguate.");
                anyhow::bail!(msg);
            }
        }
    }

    // 4. Full peer ID
    if robot.starts_with("12D3-") && robot.len() == 37 {
        return Ok(ResolvedTarget {
            peer_id: Some(PeerId::new(robot)),
            relay_addr: resolve_relay(explicit_relay, None),
            name: None,
            is_local: false,
        });
    }

    // 5. Local fallback
    let local_path = PathBuf::from(format!("/tmp/gang-agent-{robot}"));
    if local_path.exists() {
        return Ok(ResolvedTarget {
            peer_id: None,
            relay_addr: None,
            name: Some(robot.to_string()),
            is_local: true,
        });
    }

    // Nothing matched
    anyhow::bail!(
        "Unknown robot '{robot}'. Not a registered peer name, peer ID, or local agent.\n\
         Register with: gang peer add {robot} <peer-id> --relay <multiaddr>"
    );
}

// --- Peer registry commands ---

/// `gang peer add`
pub async fn peer_add(
    name: &str,
    peer_id_str: &str,
    relay: Option<&str>,
    role_str: &str,
    format: &OutputFormat,
) -> anyhow::Result<()> {
    use gang_core::identity::{PeerEntry, PeerId, PeerRegistry, Role, default_registry_path};

    let peer_id = PeerId::new(peer_id_str);
    if !peer_id.as_str().starts_with("12D3-") || peer_id.as_str().len() != 37 {
        anyhow::bail!(
            "Invalid peer ID: '{}'. Expected format: 12D3-<32 hex chars>",
            peer_id_str
        );
    }

    let role = match role_str {
        "robot-agent" | "robot" => Role::RobotAgent,
        "operator" => Role::Operator,
        "relay" => Role::Relay,
        _ => anyhow::bail!(
            "Unknown role: '{}'. Use: robot-agent, operator, or relay",
            role_str
        ),
    };

    let registry_path = default_registry_path();
    let mut registry = PeerRegistry::load(&registry_path)?;

    let entry = PeerEntry {
        peer_id: peer_id.clone(),
        role,
        relay_addrs: relay.into_iter().map(String::from).collect(),
    };

    registry.register(name.to_string(), entry);
    registry.save(&registry_path)?;

    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({
                    "status": "registered",
                    "name": name,
                    "peer_id": peer_id.as_str(),
                    "role": role_str,
                })
            );
        }
        OutputFormat::Text => {
            println!("Registered peer '{name}':");
            println!("  Peer ID: {peer_id}");
            println!("  Role:    {role_str}");
            if let Some(r) = relay {
                println!("  Relay:   {r}");
            }
        }
    }
    Ok(())
}

/// `gang peer remove`
pub async fn peer_remove(name: &str, format: &OutputFormat) -> anyhow::Result<()> {
    use gang_core::identity::{PeerRegistry, default_registry_path};

    let registry_path = default_registry_path();
    let mut registry = PeerRegistry::load(&registry_path)?;

    if registry.lookup(name).is_none() {
        anyhow::bail!("No peer registered with name '{name}'");
    }

    registry.remove(name);
    registry.save(&registry_path)?;

    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::json!({"status": "removed", "name": name}));
        }
        OutputFormat::Text => {
            println!("Removed peer '{name}'");
        }
    }
    Ok(())
}

/// `gang peer list`
pub async fn peer_list(format: &OutputFormat) -> anyhow::Result<()> {
    use gang_core::identity::{PeerRegistry, default_registry_path};

    let registry_path = default_registry_path();
    let registry = PeerRegistry::load(&registry_path)?;

    let peers: Vec<_> = registry.list().collect();

    match format {
        OutputFormat::Json => {
            let entries: Vec<_> = peers
                .iter()
                .map(|(name, entry)| {
                    serde_json::json!({
                        "name": name,
                        "peer_id": entry.peer_id.as_str(),
                        "role": format!("{}", entry.role),
                        "relay_addrs": entry.relay_addrs,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&entries)?);
        }
        OutputFormat::Text => {
            if peers.is_empty() {
                println!("No peers registered. Use `gang peer add` to register a peer.");
                return Ok(());
            }

            let header = format!(
                "{:<16} {:<16} {:<14} {}",
                "NAME", "PEER ID", "ROLE", "RELAY"
            );
            println!("{header}");
            for (name, entry) in &peers {
                let abbrev = if entry.peer_id.as_str().len() > 16 {
                    &entry.peer_id.as_str()[..16]
                } else {
                    entry.peer_id.as_str()
                };
                let relay = entry
                    .relay_addrs
                    .first()
                    .map(|s| s.as_str())
                    .unwrap_or("(none)");
                println!("{:<16} {:<16} {:<14} {}", name, abbrev, entry.role, relay);
            }
        }
    }
    Ok(())
}

/// `gang peer show`
pub async fn peer_show(name: &str, format: &OutputFormat) -> anyhow::Result<()> {
    use gang_core::identity::{PeerRegistry, default_registry_path};

    let registry_path = default_registry_path();
    let registry = PeerRegistry::load(&registry_path)?;

    let entry = registry
        .lookup(name)
        .ok_or_else(|| anyhow::anyhow!("No peer registered with name '{name}'"))?;

    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({
                    "name": name,
                    "peer_id": entry.peer_id.as_str(),
                    "role": format!("{}", entry.role),
                    "relay_addrs": entry.relay_addrs,
                })
            );
        }
        OutputFormat::Text => {
            println!("Peer '{name}':");
            println!("  Peer ID:  {}", entry.peer_id);
            println!("  Role:     {}", entry.role);
            if entry.relay_addrs.is_empty() {
                println!("  Relay:    (none)");
            } else {
                for addr in &entry.relay_addrs {
                    println!("  Relay:    {addr}");
                }
            }
        }
    }
    Ok(())
}

/// `gang peer rename`
pub async fn peer_rename(
    old_name: &str,
    new_name: &str,
    format: &OutputFormat,
) -> anyhow::Result<()> {
    use gang_core::identity::{PeerRegistry, default_registry_path};

    let registry_path = default_registry_path();
    let mut registry = PeerRegistry::load(&registry_path)?;

    let entry = registry
        .remove(old_name)
        .ok_or_else(|| anyhow::anyhow!("No peer registered with name '{old_name}'"))?;

    registry.register(new_name.to_string(), entry);
    registry.save(&registry_path)?;

    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({"status": "renamed", "old_name": old_name, "new_name": new_name})
            );
        }
        OutputFormat::Text => {
            println!("Renamed peer '{old_name}' → '{new_name}'");
        }
    }
    Ok(())
}

/// `gang peer trust-reset`
pub async fn peer_trust_reset(name: &str, format: &OutputFormat) -> anyhow::Result<()> {
    use gang_core::identity::{PeerRegistry, default_registry_path, default_trust_store_path};
    use gang_core::manifest::TrustStore;

    let registry_path = default_registry_path();
    let registry = PeerRegistry::load(&registry_path)?;

    let entry = registry
        .lookup(name)
        .ok_or_else(|| anyhow::anyhow!("No peer registered with name '{name}'"))?;

    let trust_path = default_trust_store_path();
    let mut trust_store = TrustStore::load(&trust_path)?;
    trust_store.remove(&entry.peer_id);
    trust_store.save(&trust_path)?;

    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({"status": "trust_reset", "name": name, "peer_id": entry.peer_id.as_str()})
            );
        }
        OutputFormat::Text => {
            println!("Trust reset for peer '{name}' ({}).", entry.peer_id);
            println!("The next connection will prompt for identity verification.");
        }
    }
    Ok(())
}

// --- End peer registry commands ---

// --- Config commands ---

/// `gang config show`
pub async fn config_show(format: &OutputFormat) -> anyhow::Result<()> {
    let config = OperatorConfig::load();
    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&config)?);
        }
        OutputFormat::Text => {
            let path = gang_core::identity::default_config_dir().join("config.toml");
            println!("Config file: {}", path.display());
            println!();
            println!(
                "default_relay    = {}",
                config.default_relay.as_deref().unwrap_or("(not set)")
            );
            println!("host_key_policy  = {}", config.host_key_policy);
        }
    }
    Ok(())
}

/// `gang config set`
pub async fn config_set(key: &str, value: &str, format: &OutputFormat) -> anyhow::Result<()> {
    let mut config = OperatorConfig::load();
    match key {
        "default_relay" => {
            if value == "none" || value.is_empty() {
                config.default_relay = None;
            } else {
                config.default_relay = Some(value.to_string());
            }
        }
        "host_key_policy" => {
            if !["strict", "tofu", "none"].contains(&value) {
                anyhow::bail!(
                    "Invalid host_key_policy '{value}'. Valid options: strict, tofu, none"
                );
            }
            config.host_key_policy = value.to_string();
        }
        _ => {
            anyhow::bail!("Unknown config key '{key}'. Valid keys: default_relay, host_key_policy")
        }
    }
    config.save()?;
    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({"status": "set", "key": key, "value": value})
            );
        }
        OutputFormat::Text => println!("Set {key} = {value}"),
    }
    Ok(())
}

/// `gang config init`
pub async fn config_init(force: bool, format: &OutputFormat) -> anyhow::Result<()> {
    let path = gang_core::identity::default_config_dir().join("config.toml");
    if path.exists() && !force {
        anyhow::bail!(
            "Config file already exists at {}. Use --force to overwrite.",
            path.display()
        );
    }

    let default_config = OperatorConfig::default();
    default_config.save()?;

    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({"status": "initialized", "path": path.display().to_string()})
            );
        }
        OutputFormat::Text => {
            println!("Initialized config at {}", path.display());
            println!("Edit the file or use `gang config set <key> <value>`.");
        }
    }
    Ok(())
}

/// `gang config path`
pub async fn config_path() -> anyhow::Result<()> {
    let path = gang_core::identity::default_config_dir().join("config.toml");
    println!("{}", path.display());
    Ok(())
}

// --- End config commands ---

// --- Identity verification (SSH-style TOFU) ---

/// Result of verifying a remote peer's identity.
#[allow(dead_code)] // Called by remote dispatch when connections are wired (ADR-020 Phase 32)
pub enum HostKeyVerification {
    /// Peer is already trusted and key matches.
    Trusted,
    /// Peer was unknown but has been accepted (TOFU).
    Accepted,
    /// Identity verification is disabled.
    Skipped,
}

/// Compute an SSH-style fingerprint from a public key.
fn key_fingerprint(public_key: &[u8]) -> String {
    let hash = blake3::hash(public_key);
    format!("BLAKE3:{}", &hash.to_hex()[..32])
}

/// Verify the remote peer's public key using the configured host key policy.
///
/// - `strict`: TOFU on first connect (prompts interactively), hard fail on key change.
/// - `tofu`: auto-accept new keys without prompting, hard fail on key change.
/// - `none`: no verification (prints warning).
#[allow(dead_code)]
pub fn verify_host_key(
    peer_id: &gang_core::identity::PeerId,
    remote_public_key: &[u8],
    peer_name: Option<&str>,
) -> anyhow::Result<HostKeyVerification> {
    use gang_core::identity::default_trust_store_path;
    use gang_core::manifest::{TrustStore, TrustedPeer};

    let config = OperatorConfig::load();
    let trust_path = default_trust_store_path();
    let mut trust_store = TrustStore::load(&trust_path)?;

    match config.host_key_policy.as_str() {
        "none" => {
            eprintln!("WARNING: Host key verification is disabled (host_key_policy = \"none\").");
            eprintln!("This is insecure and should only be used for development/testing.");
            Ok(HostKeyVerification::Skipped)
        }
        policy @ ("strict" | "tofu") => {
            if let Some(stored_key) = trust_store.get_public_key(peer_id) {
                // Known peer — verify key matches
                if stored_key == remote_public_key {
                    return Ok(HostKeyVerification::Trusted);
                }

                // Key mismatch!
                let display_name = peer_name
                    .map(|n| format!("'{n}' ({})", peer_id))
                    .unwrap_or_else(|| peer_id.to_string());
                let idx = trust_store.index_of(peer_id).unwrap_or(0);

                eprintln!("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                eprintln!("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!    @");
                eprintln!("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                eprintln!("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
                eprintln!("The Ed25519 host key for robot {display_name} has changed.");
                eprintln!(
                    "Fingerprint for the new key: {}",
                    key_fingerprint(remote_public_key)
                );
                eprintln!(
                    "Add correct host key in {} to get rid of this message.",
                    trust_path.display()
                );
                eprintln!("Offending key stored at index {idx}.");
                eprintln!("Robot key verification failed.");

                let reset_hint = if let Some(name) = peer_name {
                    format!("`gang peer trust-reset {name}`")
                } else {
                    format!(
                        "remove the entry for {} from {}",
                        peer_id,
                        trust_path.display()
                    )
                };
                anyhow::bail!(
                    "Host key verification failed for {display_name}. \
                     Run {reset_hint} to clear the old key, then reconnect."
                );
            }

            // Unknown peer — TOFU
            let fingerprint = key_fingerprint(remote_public_key);

            if policy == "strict" {
                eprintln!(
                    "The authenticity of robot '{}' can't be established.",
                    peer_id
                );
                eprintln!("Ed25519 key fingerprint is {fingerprint}.");

                // Read from stdin for interactive prompt
                eprint!("Are you sure you want to continue connecting (yes/no)? ");
                let mut input = String::new();
                std::io::stdin().read_line(&mut input)?;
                let answer = input.trim().to_lowercase();
                if answer != "yes" && answer != "y" {
                    anyhow::bail!("Host key verification aborted by user.");
                }
            } else {
                // tofu — auto-accept
                eprintln!(
                    "Auto-accepted host key for {} (fingerprint: {fingerprint}).",
                    peer_id
                );
            }

            // Store the key
            let name = peer_name.unwrap_or("unknown").to_string();
            trust_store.add(TrustedPeer {
                peer_id: peer_id.clone(),
                name,
                public_key: remote_public_key.to_vec(),
            });
            trust_store.save(&trust_path)?;

            eprintln!(
                "Warning: Permanently added '{}' ({fingerprint}) to the list of known robots.",
                peer_id
            );

            Ok(HostKeyVerification::Accepted)
        }
        other => {
            anyhow::bail!(
                "Unknown host_key_policy '{other}'. Valid options: strict, tofu, none. \
                 Set with: gang config set host_key_policy <policy>"
            );
        }
    }
}

// --- End identity verification ---

/// `gang sign`
pub async fn sign(
    wasm_path: &str,
    key_path: Option<&str>,
    name: Option<&str>,
    version: &str,
) -> anyhow::Result<()> {
    use gang_core::capability::CapabilityGroup;
    use gang_core::manifest::{ComponentManifest, ResourceLimits, SignedManifest};

    let key_path = key_path
        .map(PathBuf::from)
        .unwrap_or_else(gang_core::identity::default_key_path);

    if !key_path.exists() {
        anyhow::bail!(
            "Key not found at {}. Run `gang identity generate` first.",
            key_path.display()
        );
    }

    let wasm_path = Path::new(wasm_path);
    if !wasm_path.exists() {
        anyhow::bail!("Component not found: {}", wasm_path.display());
    }

    let keypair = gang_core::identity::Keypair::load(&key_path)?;
    let component_bytes = std::fs::read(wasm_path)?;
    let component_hash = blake3::hash(&component_bytes).to_hex().to_string();

    let name = name.map(String::from).unwrap_or_else(|| {
        wasm_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string()
    });

    let manifest = ComponentManifest {
        schema_version: gang_core::manifest::MANIFEST_SCHEMA_VERSION.into(),
        name: name.clone(),
        version: version.into(),
        declared_capabilities: vec![
            CapabilityGroup::DiagnosticsCollect {
                version: "1.0".into(),
            },
            CapabilityGroup::LogStream {
                version: "1.0".into(),
                patterns: vec!["**".into()],
            },
        ],
        author_peer_id: keypair.peer_id(),
        component_hash: component_hash.clone(),
        limits: ResourceLimits::default(),
        language: gang_core::registry::CapabilityLanguage::Rust,
        description: String::new(),
        tags: vec![],
        min_ganglion_version: None,
    };

    let signed = SignedManifest::sign(&manifest, &keypair)?;
    let manifest_path = wasm_path.with_extension("manifest.cbor");
    let cbor = signed.to_cbor()?;
    std::fs::write(&manifest_path, &cbor)?;

    println!("Signed component: {}", wasm_path.display());
    println!("  Name:     {name}");
    println!("  Version:  {version}");
    println!("  Manifest: {}", manifest_path.display());
    println!("  Author:   {}", keypair.peer_id());
    println!("  Hash:     {component_hash}");
    Ok(())
}

/// `gang agent` — run the robot agent.
pub async fn agent(
    _config: Option<&str>,
    data_dir: &str,
    relay: Option<&str>,
) -> anyhow::Result<()> {
    use gang_ros::agent::{AgentConfig, RobotAgent};
    use gang_ros::filesystem::FsRule;
    use std::sync::Arc;

    let data_dir = PathBuf::from(data_dir);
    std::fs::create_dir_all(&data_dir)?;

    let config = AgentConfig {
        key_path: data_dir.join("identity.key"),
        policy_path: None, // permissive for dev
        trust_store_path: data_dir.join("trusted_peers.json"),
        capabilities_dir: data_dir.join("capabilities"),
        audit_log_path: data_dir.join("audit.log"),
        audit_max_size_bytes: 50 * 1024 * 1024,
        fs_allowed_patterns: vec![FsRule {
            pattern: format!("{}/**", data_dir.display()),
            read: true,
            write: true,
        }],
        log_allowed_sources: vec!["**".into()],
    };

    let agent = Arc::new(RobotAgent::new(config)?);
    let peer_id = agent.peer_id().clone();

    println!("Robot agent started:");
    println!("  Peer ID:  {peer_id}");
    println!("  Data dir: {}", data_dir.display());
    println!("  Policy:   permissive (dev mode)");

    if let Some(relay_addr) = relay {
        println!("  Relay:    {relay_addr}");
        println!("  Mode:     remote (listening on /ganglion/control/1.0)");
        println!();
        println!("Register on operator machine:");
        println!("  gang peer add my-robot {peer_id} --relay {relay_addr}");
        println!();
        println!("Starting transport...");

        // Create libp2p transport with agent identity
        let transport_config = gang_libp2p::Libp2pConfig {
            key_path: data_dir.join("identity.key"),
            relay_addrs: vec![relay_addr.to_string()],
            ..Default::default()
        };

        let transport = gang_libp2p::Libp2pTransportAdapter::new(transport_config).await?;

        // Register the control protocol handler
        agent.serve(&transport).await?;

        // Dial the relay to establish a circuit reservation
        transport
            .dial_multiaddr(relay_addr)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to connect to relay {relay_addr}: {e}"))?;

        println!("Connected to relay. Waiting for operator connections...");
        println!("Press Ctrl+C to stop.");

        // Run the event loop alongside Ctrl+C
        tokio::select! {
            result = transport.run_event_loop() => {
                if let Err(e) = result {
                    eprintln!("Transport event loop error: {e}");
                }
            }
            _ = tokio::signal::ctrl_c() => {
                println!("\nAgent stopped.");
            }
        }
    } else {
        println!("  Mode:     local (no relay, use `gang deploy` for local testing)");
        println!();
        println!("Press Ctrl+C to stop.");

        tokio::signal::ctrl_c().await?;
        println!("\nAgent stopped.");
    }

    Ok(())
}

/// `gang deploy` — deploy a capability to a robot.
pub async fn deploy(
    robot: &str,
    wasm_path: &str,
    manifest_path: Option<&str>,
    explicit_peer: Option<&str>,
    explicit_relay: Option<&str>,
    format: &OutputFormat,
) -> anyhow::Result<()> {
    use gang_ros::agent::{AgentConfig, RobotAgent};
    use gang_ros::filesystem::FsRule;

    let wasm_path = Path::new(wasm_path);
    if !wasm_path.exists() {
        anyhow::bail!("Component not found: {}", wasm_path.display());
    }

    // Auto-detect manifest path
    let manifest_path = manifest_path
        .map(PathBuf::from)
        .unwrap_or_else(|| wasm_path.with_extension("manifest.cbor"));

    if !manifest_path.exists() {
        anyhow::bail!(
            "Manifest not found: {}\nSign the component first: gang sign {}",
            manifest_path.display(),
            wasm_path.display()
        );
    }

    let component_bytes = std::fs::read(wasm_path)?;
    let manifest_cbor = std::fs::read(&manifest_path)?;

    let target = resolve_target(robot, explicit_peer, explicit_relay)?;

    if !target.is_local {
        // Remote dispatch — will be implemented when agent serve loop is ready (Phase 32).
        let peer_id = target.peer_id.as_ref().unwrap();
        let display_name = target.name.as_deref().unwrap_or(peer_id.as_str());
        anyhow::bail!(
            "Remote deploy to '{display_name}' ({peer_id}) is not yet implemented.\n\
             The transport infrastructure is ready but the agent serve loop (ADR-020 Phase 32) \n\
             must be completed first. Use local mode for now:\n\
             \n\
             gang deploy {robot} {}",
            wasm_path.display()
        );
    }

    // Local agent path
    let data_dir = PathBuf::from(format!("/tmp/gang-agent-{robot}"));
    std::fs::create_dir_all(&data_dir)?;

    let config = AgentConfig {
        key_path: data_dir.join("identity.key"),
        policy_path: None,
        trust_store_path: data_dir.join("trusted_peers.json"),
        capabilities_dir: data_dir.join("capabilities"),
        audit_log_path: data_dir.join("audit.log"),
        audit_max_size_bytes: 50 * 1024 * 1024,
        fs_allowed_patterns: vec![FsRule {
            pattern: format!("{}/**", data_dir.display()),
            read: true,
            write: true,
        }],
        log_allowed_sources: vec!["**".into()],
    };

    let agent = RobotAgent::new(config)?;
    let operator_kp =
        gang_core::identity::Keypair::load_or_generate(&gang_core::identity::default_key_path())?;

    let name = agent
        .deploy_capability(&manifest_cbor, &component_bytes, &operator_kp.peer_id())
        .await?;

    match format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::json!({
                    "status": "deployed",
                    "name": name,
                    "robot": robot,
                })
            );
        }
        OutputFormat::Text => {
            println!("Deployed '{name}' to robot '{robot}'");
        }
    }

    Ok(())
}

/// `gang run` — invoke a capability on a robot.
pub async fn run(
    robot: &str,
    cap_name: &str,
    args: &[String],
    explicit_peer: Option<&str>,
    explicit_relay: Option<&str>,
    format: &OutputFormat,
) -> anyhow::Result<()> {
    use gang_ros::agent::{AgentConfig, RobotAgent};
    use gang_ros::filesystem::FsRule;

    let target = resolve_target(robot, explicit_peer, explicit_relay)?;

    if !target.is_local {
        let peer_id = target.peer_id.as_ref().unwrap();
        let display_name = target.name.as_deref().unwrap_or(peer_id.as_str());
        anyhow::bail!(
            "Remote run on '{display_name}' ({peer_id}) is not yet implemented.\n\
             The transport infrastructure is ready but the agent serve loop (ADR-020 Phase 32) \n\
             must be completed first. Use local mode for now:\n\
             \n\
             gang run {robot} {cap_name}"
        );
    }

    let data_dir = PathBuf::from(format!("/tmp/gang-agent-{robot}"));
    if !data_dir.exists() {
        anyhow::bail!(
            "No agent data found for robot '{robot}' at {}\n\
             Deploy a capability first: gang deploy {robot} <wasm-path>",
            data_dir.display()
        );
    }

    let config = AgentConfig {
        key_path: data_dir.join("identity.key"),
        policy_path: None,
        trust_store_path: data_dir.join("trusted_peers.json"),
        capabilities_dir: data_dir.join("capabilities"),
        audit_log_path: data_dir.join("audit.log"),
        audit_max_size_bytes: 50 * 1024 * 1024,
        fs_allowed_patterns: vec![FsRule {
            pattern: format!("{}/**", data_dir.display()),
            read: true,
            write: true,
        }],
        log_allowed_sources: vec!["**".into()],
    };

    let agent = RobotAgent::new(config)?;
    let operator_kp =
        gang_core::identity::Keypair::load_or_generate(&gang_core::identity::default_key_path())?;

    let output = agent
        .invoke_capability(cap_name, args, &operator_kp.peer_id())
        .await?;

    match format {
        OutputFormat::Json => {
            // Output is already JSON
            let val: serde_json::Value = serde_json::from_slice(&output)?;
            println!("{}", serde_json::to_string_pretty(&val)?);
        }
        OutputFormat::Text => {
            let val: serde_json::Value = serde_json::from_slice(&output)?;
            print_diagnostics(&val);
        }
    }

    Ok(())
}

/// `gang caps` — list installed capabilities.
pub async fn caps(
    robot: &str,
    explicit_peer: Option<&str>,
    explicit_relay: Option<&str>,
    format: &OutputFormat,
) -> anyhow::Result<()> {
    use gang_ros::agent::{AgentConfig, RobotAgent};

    let target = resolve_target(robot, explicit_peer, explicit_relay)?;

    if !target.is_local {
        let peer_id = target.peer_id.as_ref().unwrap();
        let display_name = target.name.as_deref().unwrap_or(peer_id.as_str());
        anyhow::bail!(
            "Remote caps on '{display_name}' ({peer_id}) is not yet implemented.\n\
             The agent serve loop (ADR-020 Phase 32) must be completed first."
        );
    }

    let data_dir = PathBuf::from(format!("/tmp/gang-agent-{robot}"));
    if !data_dir.exists() {
        anyhow::bail!("No agent data found for robot '{robot}'");
    }

    let config = AgentConfig {
        key_path: data_dir.join("identity.key"),
        policy_path: None,
        trust_store_path: data_dir.join("trusted_peers.json"),
        capabilities_dir: data_dir.join("capabilities"),
        audit_log_path: data_dir.join("audit.log"),
        audit_max_size_bytes: 50 * 1024 * 1024,
        fs_allowed_patterns: vec![],
        log_allowed_sources: vec![],
    };

    let agent = RobotAgent::new(config)?;
    let caps = agent.list_capabilities().await;

    match format {
        OutputFormat::Json => {
            let list: Vec<serde_json::Value> = caps
                .iter()
                .map(|c| {
                    serde_json::json!({
                        "name": c.name,
                        "version": c.version,
                        "author": c.author_peer_id.as_str(),
                        "capabilities": c.declared_capabilities.iter()
                            .map(|g| g.qualified_name())
                            .collect::<Vec<_>>(),
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&list)?);
        }
        OutputFormat::Text => {
            if caps.is_empty() {
                println!("No capabilities installed on '{robot}'");
            } else {
                println!("Capabilities on '{robot}':");
                for cap in &caps {
                    println!(
                        "  {} v{} (by {})",
                        cap.name, cap.version, cap.author_peer_id
                    );
                    for group in &cap.declared_capabilities {
                        println!("    - {}", group.qualified_name());
                    }
                }
            }
        }
    }

    Ok(())
}

/// `gang demo` — self-contained local demo.
pub async fn demo(format: &OutputFormat) -> anyhow::Result<()> {
    use gang_core::capability::CapabilityGroup;
    use gang_core::manifest::{ComponentManifest, ResourceLimits, SignedManifest};
    use gang_ros::agent::{AgentConfig, RobotAgent};
    use gang_ros::filesystem::FsRule;

    println!("=== Ganglion v0.1 Demo ===");
    println!();

    // 1. Generate identity if needed
    let key_path = gang_core::identity::default_key_path();
    let keypair = gang_core::identity::Keypair::load_or_generate(&key_path)?;
    println!("Operator identity: {}", keypair.peer_id());

    // 2. Create a simulated robot agent
    let data_dir = PathBuf::from("/tmp/gang-demo");
    if data_dir.exists() {
        std::fs::remove_dir_all(&data_dir)?;
    }
    std::fs::create_dir_all(&data_dir)?;

    let agent_config = AgentConfig {
        key_path: data_dir.join("robot.key"),
        policy_path: None,
        trust_store_path: data_dir.join("trusted_peers.json"),
        capabilities_dir: data_dir.join("capabilities"),
        audit_log_path: data_dir.join("audit.log"),
        audit_max_size_bytes: 50 * 1024 * 1024,
        fs_allowed_patterns: vec![FsRule {
            pattern: format!("{}/**", data_dir.display()),
            read: true,
            write: true,
        }],
        log_allowed_sources: vec!["**".into()],
    };

    let agent = RobotAgent::new(agent_config)?;
    println!("Robot agent:       {}", agent.peer_id());
    println!();

    // 3. Create and sign a diagnostics capability
    println!("--- Signing diagnostics capability ---");
    let component_bytes = b"gang-capability-diagnostics-v0.1.0-demo";
    let component_hash = blake3::hash(component_bytes).to_hex().to_string();

    let manifest = ComponentManifest {
        schema_version: gang_core::manifest::MANIFEST_SCHEMA_VERSION.into(),
        name: "diagnostics".into(),
        version: "0.1.0".into(),
        declared_capabilities: vec![
            CapabilityGroup::DiagnosticsCollect {
                version: "1.0".into(),
            },
            CapabilityGroup::LogStream {
                version: "1.0".into(),
                patterns: vec!["**".into()],
            },
        ],
        author_peer_id: keypair.peer_id(),
        component_hash,
        limits: ResourceLimits::default(),
        language: gang_core::registry::CapabilityLanguage::Rust,
        description: "System diagnostics".into(),
        tags: vec!["diagnostics".into()],
        min_ganglion_version: None,
    };

    let signed = SignedManifest::sign(&manifest, &keypair)?;
    let manifest_cbor = signed.to_cbor()?;
    println!("  Component signed by {}", keypair.peer_id());
    println!();

    // 4. Deploy
    println!("--- Deploying to robot ---");
    let name = agent
        .deploy_capability(&manifest_cbor, component_bytes, &keypair.peer_id())
        .await?;
    println!("  Deployed: {name}");
    println!();

    // 5. List capabilities
    println!("--- Installed capabilities ---");
    let caps = agent.list_capabilities().await;
    for cap in &caps {
        println!("  {} v{} ({})", cap.name, cap.version, cap.author_peer_id);
    }
    println!();

    // 6. Invoke
    println!("--- Invoking diagnostics ---");
    let output = agent
        .invoke_capability("diagnostics", &[], &keypair.peer_id())
        .await?;

    let val: serde_json::Value = serde_json::from_slice(&output)?;

    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&val)?);
        }
        OutputFormat::Text => {
            print_diagnostics(&val);
        }
    }

    println!();
    println!("--- Audit log ---");
    let audit_log = gang_core::audit::AuditLog::new(data_dir.join("audit.log"), 50 * 1024 * 1024);
    let records = audit_log.read_all()?;
    for record in &records {
        println!(
            "  {} invoked '{}' v{} at {} -> {:?}",
            record.operator_peer_id,
            record.component_name,
            record.component_version,
            record.started_at.format("%H:%M:%S"),
            record.exit_status,
        );
    }

    println!();
    println!("=== Demo complete ===");
    println!("Data stored at: {}", data_dir.display());

    // Cleanup
    std::fs::remove_dir_all(&data_dir)?;

    Ok(())
}

/// `gang test-archetype`
pub async fn test_archetype(archetype: &str) -> anyhow::Result<()> {
    let valid = [
        "open-warehouse",
        "nat-office",
        "enterprise-dmz",
        "mobile-cgnat",
    ];
    if !valid.contains(&archetype) {
        anyhow::bail!(
            "Unknown archetype: {archetype}\nValid archetypes: {}",
            valid.join(", ")
        );
    }

    // Check Docker is available
    let docker_check = std::process::Command::new("docker")
        .args(["info"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    match docker_check {
        Ok(s) if s.success() => {}
        _ => {
            anyhow::bail!(
                "Docker is required for test-archetype but is not available.\n\
                 Install Docker and try again."
            );
        }
    }

    // Check docker compose is available
    let compose_check = std::process::Command::new("docker")
        .args(["compose", "version"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    match compose_check {
        Ok(s) if s.success() => {}
        _ => {
            anyhow::bail!(
                "docker compose is required but not available.\n\
                 Install the Docker Compose plugin and try again."
            );
        }
    }

    println!("============================================");
    println!("  Ganglion Test Harness: {archetype}");
    println!("============================================");
    println!();

    // Describe what this archetype simulates
    match archetype {
        "open-warehouse" => {
            println!("Scenario: Flat L2, no NAT, permissive DHCP");
            println!("  - Direct TCP/QUIC connection between operator and robot");
            println!("  - Multicast works, no relay needed");
        }
        "nat-office" => {
            println!("Scenario: Single consumer NAT, no inbound ports");
            println!("  - Robot dials out to relay");
            println!("  - Operator connects via relay, DCUtR upgrade attempted");
        }
        "enterprise-dmz" => {
            println!("Scenario: VLAN isolation, restricted outbound ports");
            println!("  - TLS inspection proxy, TCP 443 outbound only");
            println!("  - Robot connects through firewall to relay");
        }
        "mobile-cgnat" => {
            println!("Scenario: Symmetric NAT, CGNAT, IP rotation");
            println!("  - Relay-only connectivity (DCUtR fails on symmetric NAT)");
            println!("  - Simulated cellular conditions: jitter, packet loss");
        }
        _ => unreachable!(),
    }
    println!();

    // Locate the test-harness directory relative to the binary or CWD.
    let scenario_dir = find_scenario_dir(archetype)?;
    let compose_file = scenario_dir.join("docker-compose.yml");

    if !compose_file.exists() {
        anyhow::bail!(
            "docker-compose.yml not found at {}\n\
             Make sure you're running from the Ganglion repo root.",
            compose_file.display()
        );
    }

    let project_name = format!("ganglion-{archetype}");
    let compose_path = compose_file.to_string_lossy().to_string();

    // Tear down any leftover from previous runs
    let _ = std::process::Command::new("docker")
        .args([
            "compose",
            "-p",
            &project_name,
            "-f",
            &compose_path,
            "down",
            "-v",
            "--remove-orphans",
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    // Build
    println!("Building container images...");
    let build_status = std::process::Command::new("docker")
        .args(["compose", "-p", &project_name, "-f", &compose_path, "build"])
        .status()?;

    if !build_status.success() {
        anyhow::bail!("Docker build failed. Check output above.");
    }

    // Start
    println!();
    println!("Starting {archetype} scenario...");
    let up_status = std::process::Command::new("docker")
        .args([
            "compose",
            "-p",
            &project_name,
            "-f",
            &compose_path,
            "up",
            "-d",
        ])
        .status()?;

    if !up_status.success() {
        // Clean up on failure
        let _ = std::process::Command::new("docker")
            .args([
                "compose",
                "-p",
                &project_name,
                "-f",
                &compose_path,
                "down",
                "-v",
                "--remove-orphans",
            ])
            .status();
        anyhow::bail!("Failed to start scenario. Check output above.");
    }

    // Wait for stabilization
    println!("Waiting for services to stabilize...");
    tokio::time::sleep(std::time::Duration::from_secs(5)).await;

    // Show service status
    println!();
    let _ = std::process::Command::new("docker")
        .args(["compose", "-p", &project_name, "-f", &compose_path, "ps"])
        .status();

    // Run connectivity checks
    println!();
    println!("=== Connectivity checks ===");
    run_archetype_checks(archetype, &project_name, &compose_path);

    // Show logs
    println!();
    println!("=== Service logs (last 20 lines) ===");
    let _ = std::process::Command::new("docker")
        .args([
            "compose",
            "-p",
            &project_name,
            "-f",
            &compose_path,
            "logs",
            "--tail",
            "20",
        ])
        .status();

    println!();
    println!("============================================");
    println!("  Scenario {archetype} is running");
    println!("============================================");
    println!();
    println!("Inspect manually:");
    println!("  docker compose -p {project_name} -f {compose_path} exec robot bash");
    println!("  docker compose -p {project_name} -f {compose_path} logs -f");
    println!();
    println!("Tear down:");
    println!("  docker compose -p {project_name} -f {compose_path} down -v");

    Ok(())
}

/// Run archetype-specific network connectivity checks.
fn run_archetype_checks(archetype: &str, project_name: &str, compose_path: &str) {
    let docker_exec = |service: &str, cmd: &[&str]| -> bool {
        let mut args = vec![
            "compose",
            "-p",
            project_name,
            "-f",
            compose_path,
            "exec",
            "-T",
            service,
        ];
        args.extend_from_slice(cmd);
        std::process::Command::new("docker")
            .args(&args)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    };

    match archetype {
        "open-warehouse" => {
            let ok = docker_exec("operator", &["ping", "-c", "2", "-W", "2", "172.20.0.20"]);
            println!(
                "  operator -> robot (direct):  {}",
                if ok { "OK" } else { "FAIL" }
            );
            let ok = docker_exec("robot", &["ping", "-c", "2", "-W", "2", "172.20.0.10"]);
            println!(
                "  robot -> relay (direct):     {}",
                if ok { "OK" } else { "FAIL" }
            );
        }
        "nat-office" => {
            let ok = docker_exec("robot", &["ping", "-c", "2", "-W", "2", "192.168.1.1"]);
            println!(
                "  robot -> NAT gateway:        {}",
                if ok { "OK" } else { "FAIL" }
            );
            let ok = docker_exec("operator", &["ping", "-c", "2", "-W", "2", "192.168.2.1"]);
            println!(
                "  operator -> NAT gateway:     {}",
                if ok { "OK" } else { "FAIL" }
            );
        }
        "enterprise-dmz" => {
            let ok = docker_exec("robot", &["ping", "-c", "2", "-W", "2", "172.16.10.1"]);
            println!(
                "  robot -> firewall:           {}",
                if ok { "OK" } else { "FAIL" }
            );
            let ok = docker_exec("operator", &["ping", "-c", "2", "-W", "2", "10.1.0.10"]);
            println!(
                "  operator -> relay (direct):  {}",
                if ok { "OK" } else { "FAIL" }
            );
        }
        "mobile-cgnat" => {
            let ok = docker_exec("robot", &["ping", "-c", "2", "-W", "2", "10.64.0.1"]);
            println!(
                "  robot -> inner NAT:          {}",
                if ok { "OK" } else { "FAIL" }
            );
            let ok = docker_exec("operator", &["ping", "-c", "2", "-W", "2", "10.2.0.10"]);
            println!(
                "  operator -> relay (direct):  {}",
                if ok { "OK" } else { "FAIL" }
            );
        }
        _ => {}
    }
}

/// Find the test-harness scenario directory by searching upward from CWD.
fn find_scenario_dir(archetype: &str) -> anyhow::Result<std::path::PathBuf> {
    let cwd = std::env::current_dir()?;
    for ancestor in cwd.ancestors() {
        let candidate = ancestor.join("test-harness").join(archetype);
        if candidate.is_dir() {
            return Ok(candidate);
        }
    }
    anyhow::bail!(
        "Could not find test-harness/{archetype} directory.\n\
         Run this command from within the Ganglion repository."
    )
}

/// Pretty-print diagnostics output for human consumption.
fn print_diagnostics(val: &serde_json::Value) {
    if let Some(sys) = val.get("system_info") {
        println!("System Information:");
        if let Some(h) = sys.get("hostname").and_then(|v| v.as_str()) {
            println!("  Hostname:  {h}");
        }
        if let Some(os) = sys.get("os").and_then(|v| v.as_str()) {
            let ver = sys.get("os_version").and_then(|v| v.as_str()).unwrap_or("");
            println!("  OS:        {os} {ver}");
        }
        if let Some(arch) = sys.get("arch").and_then(|v| v.as_str()) {
            println!("  Arch:      {arch}");
        }
        if let Some(cpus) = sys.get("cpu_count").and_then(|v| v.as_u64()) {
            println!("  CPUs:      {cpus}");
        }
        if let Some(mem) = sys.get("memory_total_bytes").and_then(|v| v.as_u64()) {
            if mem > 0 {
                println!("  Memory:    {} GB", mem / (1024 * 1024 * 1024));
            }
        }
        if let Some(uptime) = sys.get("uptime_secs").and_then(|v| v.as_u64()) {
            let hours = uptime / 3600;
            let mins = (uptime % 3600) / 60;
            println!("  Uptime:    {hours}h {mins}m");
        }
        if let Some(ver) = sys.get("ganglion_version").and_then(|v| v.as_str()) {
            println!("  Ganglion:  v{ver}");
        }
        println!();
    }

    if let Some(net) = val.get("network") {
        if let Some(interfaces) = net.get("interfaces").and_then(|v| v.as_array()) {
            println!("Network Interfaces:");
            for iface in interfaces {
                let name = iface.get("name").and_then(|v| v.as_str()).unwrap_or("?");
                let up = iface
                    .get("is_up")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let status = if up { "UP" } else { "DOWN" };
                let addrs = iface
                    .get("addresses")
                    .and_then(|v| v.as_array())
                    .map(|a| {
                        a.iter()
                            .filter_map(|v| v.as_str())
                            .collect::<Vec<_>>()
                            .join(", ")
                    })
                    .unwrap_or_default();
                println!("  {name} ({status}): {addrs}");
            }
            println!();
        }
    }

    if let Some(procs) = val.get("processes").and_then(|v| v.as_array()) {
        println!("Processes: {} running", procs.len());
        // Show top 5 by CPU
        let mut sorted: Vec<&serde_json::Value> = procs.iter().collect();
        sorted.sort_by(|a, b| {
            let cpu_a = a.get("cpu_percent").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let cpu_b = b.get("cpu_percent").and_then(|v| v.as_f64()).unwrap_or(0.0);
            cpu_b
                .partial_cmp(&cpu_a)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        for proc in sorted.iter().take(5) {
            let name = proc.get("name").and_then(|v| v.as_str()).unwrap_or("?");
            let pid = proc.get("pid").and_then(|v| v.as_u64()).unwrap_or(0);
            let cpu = proc
                .get("cpu_percent")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0);
            println!("  PID {pid}: {cpu:.1}% CPU — {name}");
        }
        println!();
    }

    if let Some(logs) = val.get("log_sources").and_then(|v| v.as_array()) {
        println!("Log Sources:");
        for source in logs {
            let name = source.get("name").and_then(|v| v.as_str()).unwrap_or("?");
            let stype = source
                .get("source_type")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            println!("  {name} ({stype})");
        }
    }
}

/// `gang diagnose` — detect network archetype and recommend transport config.
pub async fn diagnose(robot: Option<&str>, format: &crate::OutputFormat) -> anyhow::Result<()> {
    use gang_ros::archetype;

    if let Some(robot_name) = robot {
        println!("Diagnosing network for robot: {robot_name}");
        println!("(Remote diagnosis requires active connection — running local probes instead)");
        println!();
    }

    println!("Running network probes...");
    println!();

    let result = archetype::detect_archetype();

    match format {
        crate::OutputFormat::Json => {
            let json = serde_json::to_string_pretty(&result)?;
            println!("{json}");
        }
        crate::OutputFormat::Text => {
            println!("============================================");
            println!("  Network Archetype Detection");
            println!("============================================");
            println!();
            println!(
                "  Detected:    {} ({:.0}% confidence)",
                result.archetype,
                result.confidence * 100.0
            );
            println!();

            println!("Probes:");
            for probe in &result.probes {
                let status = if probe.success { "" } else { "" };
                println!("  {status} {}: {}", probe.probe_name, probe.detail);
            }
            println!();

            println!("Recommendations:");
            for rec in &result.recommendations {
                println!("{rec}");
            }
        }
    }

    Ok(())
}

/// `gang transport-stats` — show per-transport statistics for a peer.
pub async fn transport_stats(robot: &str, format: &crate::OutputFormat) -> anyhow::Result<()> {
    // For now, show simulated stats since we don't have a live connection.
    // In full implementation, this queries the transport adapter for the
    // connected peer's stats.

    println!("Transport statistics for: {robot}");
    println!("(Requires active connection — showing example output)");
    println!();

    let example_stats = gang_core::transport::TransportStats {
        transport: "quic".into(),
        via_relay: false,
        connect_time_ms: 145,
        messages_sent: 42,
        messages_received: 38,
        bytes_sent: 12_480,
        bytes_received: 156_320,
        last_rtt_ms: Some(23),
        dcutr_attempted: true,
        dcutr_succeeded: true,
        uptime_secs: 3600,
        reconnections: 0,
    };

    match format {
        crate::OutputFormat::Json => {
            let json = serde_json::to_string_pretty(&example_stats)?;
            println!("{json}");
        }
        crate::OutputFormat::Text => {
            println!("  Transport:       {}", example_stats.transport);
            println!("  Via relay:       {}", example_stats.via_relay);
            println!("  Connect time:    {}ms", example_stats.connect_time_ms);
            println!(
                "  Messages:        {} sent, {} received",
                example_stats.messages_sent, example_stats.messages_received
            );
            println!(
                "  Bytes:           {} sent, {} received",
                format_bytes(example_stats.bytes_sent),
                format_bytes(example_stats.bytes_received)
            );
            if let Some(rtt) = example_stats.last_rtt_ms {
                println!("  Last RTT:        {rtt}ms");
            }
            println!(
                "  DCUtR:           attempted={}, succeeded={}",
                example_stats.dcutr_attempted, example_stats.dcutr_succeeded
            );
            println!(
                "  Uptime:          {}",
                format_duration(example_stats.uptime_secs)
            );
            println!("  Reconnections:   {}", example_stats.reconnections);
        }
    }

    Ok(())
}

fn format_bytes(bytes: u64) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1} MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1_024 {
        format!("{:.1} KB", bytes as f64 / 1_024.0)
    } else {
        format!("{bytes} B")
    }
}

/// `gang fetch <cid>` — retrieve an artifact by CID.
pub async fn fetch_artifact(
    cid_str: &str,
    output: Option<&str>,
    _format: &crate::OutputFormat,
) -> anyhow::Result<()> {
    use gang_core::artifacts::{ArtifactStore, ArtifactStoreConfig, Cid};

    let store_dir = artifact_store_dir();
    let mut store = ArtifactStore::open(ArtifactStoreConfig {
        store_dir,
        ..Default::default()
    })?;

    let cid = Cid::parse(cid_str);
    if !store.contains(&cid) {
        anyhow::bail!(
            "Artifact {cid_str} not found in local store.\n\
             Remote fetch from peers is not yet implemented."
        );
    }

    let data = store.retrieve(&cid)?;
    let meta = store.meta(&cid);

    match output {
        Some(path) => {
            std::fs::write(path, &data)?;
            println!("Wrote {} bytes to {path}", data.len());
        }
        None => {
            let filename = meta
                .and_then(|m| m.filename.as_deref())
                .unwrap_or("artifact.bin");
            std::fs::write(filename, &data)?;
            println!("Wrote {} bytes to {filename}", data.len());
        }
    }

    Ok(())
}

/// `gang push <path>` — publish a local file to the content store.
pub async fn push_artifact(
    path: &str,
    content_type: Option<&str>,
    format: &crate::OutputFormat,
) -> anyhow::Result<()> {
    use gang_core::artifacts::{ArtifactStore, ArtifactStoreConfig};

    let store_dir = artifact_store_dir();
    let mut store = ArtifactStore::open(ArtifactStoreConfig {
        store_dir,
        ..Default::default()
    })?;

    let data = std::fs::read(path)?;
    let filename = Path::new(path).file_name().and_then(|n| n.to_str());

    let cid = store.store(&data, filename, None, content_type)?;

    match format {
        crate::OutputFormat::Json => {
            let info = serde_json::json!({
                "cid": cid.as_str(),
                "size": data.len(),
                "filename": filename,
            });
            println!("{}", serde_json::to_string_pretty(&info)?);
        }
        crate::OutputFormat::Text => {
            println!("Published artifact:");
            println!("  CID:      {cid}");
            println!("  Size:     {}", format_bytes(data.len() as u64));
            if let Some(name) = filename {
                println!("  Filename: {name}");
            }
        }
    }

    Ok(())
}

/// `gang artifacts` — list locally-stored artifacts.
pub async fn list_artifacts(format: &crate::OutputFormat) -> anyhow::Result<()> {
    use gang_core::artifacts::{ArtifactStore, ArtifactStoreConfig};

    let store_dir = artifact_store_dir();
    let store = ArtifactStore::open(ArtifactStoreConfig {
        store_dir,
        ..Default::default()
    })?;

    let artifacts = store.list();

    match format {
        crate::OutputFormat::Json => {
            let json = serde_json::to_string_pretty(&artifacts)?;
            println!("{json}");
        }
        crate::OutputFormat::Text => {
            if artifacts.is_empty() {
                println!("No artifacts stored locally.");
            } else {
                println!(
                    "Stored artifacts ({}, {}):",
                    artifacts.len(),
                    format_bytes(store.total_bytes())
                );
                println!();
                for meta in &artifacts {
                    let name = meta.filename.as_deref().unwrap_or("(unnamed)");
                    let chunks = if meta.chunk_count > 1 {
                        format!(" ({} chunks)", meta.chunk_count)
                    } else {
                        String::new()
                    };
                    println!("  {}{}{}", meta.cid, format_bytes(meta.size), chunks);
                    println!("    Filename: {name}");
                    if let Some(origin) = &meta.origin_peer {
                        println!("    Origin:   {origin}");
                    }
                }
            }
        }
    }

    Ok(())
}

/// Default artifact store directory.
fn artifact_store_dir() -> PathBuf {
    dirs::data_local_dir()
        .unwrap_or_else(|| PathBuf::from("/tmp"))
        .join("gang")
        .join("artifacts")
}

/// `gang capability scaffold <name> --language <lang>`
pub async fn capability_scaffold(
    name: &str,
    language: &str,
    output_dir: Option<&str>,
) -> anyhow::Result<()> {
    let base = output_dir
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    let project_dir = base.join(name);

    if project_dir.exists() {
        anyhow::bail!("directory {} already exists", project_dir.display());
    }

    std::fs::create_dir_all(&project_dir)?;

    match language {
        "rust" => scaffold_rust(name, &project_dir)?,
        "cpp" | "c++" => scaffold_cpp(name, &project_dir)?,
        "python" | "py" => scaffold_python(name, &project_dir)?,
        "go" | "golang" => scaffold_go(name, &project_dir)?,
        _ => anyhow::bail!("unsupported language: {language}. Supported: rust, cpp, python, go"),
    }

    // Copy WIT interface to project
    let wit_dir = project_dir.join("wit");
    std::fs::create_dir_all(&wit_dir)?;
    std::fs::write(
        wit_dir.join("README.md"),
        "Copy ganglion.wit from the Ganglion repository into this directory.\n\
         See: https://github.com/tafy-labs/ganglion/tree/main/crates/gang-wasm-host/wit\n",
    )?;

    println!(
        "Scaffolded {} capability at {}",
        language,
        project_dir.display()
    );
    println!("\nNext steps:");
    println!("  1. Copy ganglion.wit into {}/wit/", name);
    println!("  2. Implement your capability logic");
    println!("  3. Build: see docs/CAPABILITY_AUTHOR_GUIDE.md");
    println!("  4. Sign: gang sign {name}.component.wasm --name {name} --version 0.1.0");
    Ok(())
}

fn scaffold_rust(name: &str, dir: &Path) -> anyhow::Result<()> {
    let src_dir = dir.join("src");
    std::fs::create_dir_all(&src_dir)?;

    let crate_name = name.replace('-', "_");

    std::fs::write(
        dir.join("Cargo.toml"),
        format!(
            r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
"#
        ),
    )?;

    std::fs::write(
        src_dir.join("lib.rs"),
        format!(
            r#"//! {name} — a Ganglion capability.
//!
//! Build: cargo build --target wasm32-wasip2 --release
//! Component: wasm-tools component new target/wasm32-wasip2/release/{crate_name}.wasm -o {name}.component.wasm
//! Sign: gang sign {name}.component.wasm --name {name} --version 0.1.0

use serde::Serialize;

#[derive(Serialize)]
struct Output {{
    status: String,
    message: String,
}}

/// Entry point called by the Ganglion runtime.
pub fn run(args: Vec<String>) -> Result<Vec<u8>, String> {{
    let output = Output {{
        status: "ok".into(),
        message: format!("{name} invoked with {{}} arg(s)", args.len()),
    }};
    serde_json::to_vec(&output).map_err(|e| e.to_string())
}}

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

    #[test]
    fn run_returns_ok() {{
        let result = run(vec!["test".into()]).unwrap();
        let output: Output = serde_json::from_slice(&result).unwrap();
        assert_eq!(output.status, "ok");
    }}
}}
"#
        ),
    )?;

    std::fs::write(
        dir.join("Makefile"),
        format!(
            r#".PHONY: build component sign clean

build:
	cargo build --target wasm32-wasip2 --release

component: build
	wasm-tools component new target/wasm32-wasip2/release/{crate_name}.wasm \
		-o {name}.component.wasm

sign: component
	gang sign {name}.component.wasm --name {name} --version 0.1.0

test:
	cargo test

clean:
	cargo clean
	rm -f {name}.component.wasm {name}.manifest.cbor
"#
        ),
    )?;

    Ok(())
}

fn scaffold_cpp(name: &str, dir: &Path) -> anyhow::Result<()> {
    let src_dir = dir.join("src");
    std::fs::create_dir_all(&src_dir)?;

    std::fs::write(
        src_dir.join("main.cpp"),
        format!(
            r#"// {name} — a Ganglion capability (C++)
//
// Build with wasi-sdk:
//   make component

#include <cstdio>
#include <cstring>

// Entry point — called by the Ganglion runtime
extern "C" int run(int argc, const char* argv[]) {{
    printf("{{\\"status\\":\\"ok\\",\\"message\\":\\"{name} invoked with %d arg(s)\\"}}\\n", argc);
    return 0;
}}
"#
        ),
    )?;

    std::fs::write(
        dir.join("Makefile"),
        format!(
            r#"WASI_SDK ?= $(WASI_SDK_PATH)
CC = $(WASI_SDK)/bin/clang++

.PHONY: build component sign clean

build: src/main.cpp
	$(CC) -o {name}.wasm src/main.cpp --target=wasm32-wasip2 -O2

component: build
	wasm-tools component new {name}.wasm -o {name}.component.wasm

sign: component
	gang sign {name}.component.wasm --name {name} --version 0.1.0

clean:
	rm -f {name}.wasm {name}.component.wasm {name}.manifest.cbor
"#
        ),
    )?;

    Ok(())
}

fn scaffold_python(name: &str, dir: &Path) -> anyhow::Result<()> {
    std::fs::write(
        dir.join("app.py"),
        format!(
            r#"\"\"\"
{name} — a Ganglion capability (Python).

Build: componentize-py -d wit/ganglion.wit -w ganglion-capability componentize app -o {name}.component.wasm
Sign:  gang sign {name}.component.wasm --name {name} --version 0.1.0
\"\"\"

import json


def run(args: list[str]) -> bytes:
    \"\"\"Entry point called by the Ganglion runtime.\"\"\"
    result = {{
        "status": "ok",
        "message": f"{name} invoked with {{len(args)}} arg(s)",
        "args": args,
    }}
    return json.dumps(result).encode()
"#
        ),
    )?;

    std::fs::write(
        dir.join("Makefile"),
        format!(
            r#".PHONY: component sign clean

component:
	componentize-py -d wit/ganglion.wit -w ganglion-capability componentize app -o {name}.component.wasm

sign: component
	gang sign {name}.component.wasm --name {name} --version 0.1.0

clean:
	rm -f {name}.component.wasm {name}.manifest.cbor
"#
        ),
    )?;

    Ok(())
}

fn scaffold_go(name: &str, dir: &Path) -> anyhow::Result<()> {
    let mod_name = name.replace('-', "");

    std::fs::write(
        dir.join("main.go"),
        format!(
            r#"// {name} — a Ganglion capability (Go/TinyGo).
//
// Build: tinygo build -o {name}.wasm -target=wasip2 .
// Component: wasm-tools component new {name}.wasm -o {name}.component.wasm
// Sign: gang sign {name}.component.wasm --name {name} --version 0.1.0

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type Result struct {{
	Status  string `json:"status"`
	Message string `json:"message"`
}}

func main() {{
	result := Result{{
		Status:  "ok",
		Message: fmt.Sprintf("{name} invoked with %d arg(s)", len(os.Args)-1),
	}}
	data, _ := json.Marshal(result)
	fmt.Println(string(data))
}}
"#
        ),
    )?;

    std::fs::write(
        dir.join("go.mod"),
        format!("module github.com/tafy-labs/{mod_name}\n\ngo 1.22\n"),
    )?;

    std::fs::write(
        dir.join("Makefile"),
        format!(
            r#".PHONY: build component sign clean

build:
	tinygo build -o {name}.wasm -target=wasip2 .

component: build
	wasm-tools component new {name}.wasm -o {name}.component.wasm

sign: component
	gang sign {name}.component.wasm --name {name} --version 0.1.0

clean:
	rm -f {name}.wasm {name}.component.wasm {name}.manifest.cbor
"#
        ),
    )?;

    Ok(())
}

/// Default registry directory.
fn registry_dir() -> PathBuf {
    dirs::data_local_dir()
        .unwrap_or_else(|| PathBuf::from("/tmp"))
        .join("gang")
        .join("registry")
}

/// `gang registry search <query>`
pub async fn registry_search(query: &str, _format: &OutputFormat) -> anyhow::Result<()> {
    let reg = gang_core::registry::Registry::open(&registry_dir())?;
    let results = reg.search(query);

    if results.is_empty() {
        println!("No capabilities found matching \"{query}\".");
        return Ok(());
    }

    println!("Found {} result(s) for \"{}\":\n", results.len(), query);
    for r in &results {
        println!("  {} v{}", r.name, r.latest_version);
        println!("    {}", r.description);
        println!(
            "    Language: {}  Author: {}...{}",
            r.language,
            &r.author[..8.min(r.author.len())],
            &r.author[r.author.len().saturating_sub(4)..]
        );
        if !r.tags.is_empty() {
            println!("    Tags: {}", r.tags.join(", "));
        }
        println!();
    }
    Ok(())
}

/// `gang registry install <name>`
pub async fn registry_install(
    name: &str,
    version: Option<&str>,
    _format: &OutputFormat,
) -> anyhow::Result<()> {
    let reg = gang_core::registry::Registry::open(&registry_dir())?;

    let entry = if let Some(ver) = version {
        reg.get(name)
            .and_then(|versions| versions.iter().find(|e| e.version == ver))
    } else {
        reg.get_latest(name)
    };

    match entry {
        Some(entry) => {
            println!("Installing {} v{} ...", entry.name, entry.version);
            println!("  Component CID: {}", entry.component_cid);
            println!("  Manifest CID:  {}", entry.manifest_cid);
            println!("  Language:       {}", entry.language);
            // Actual fetch would use the artifact store to retrieve by CID
            println!("\nNote: network fetch not yet implemented.");
            println!(
                "Use `gang fetch {}` to retrieve the component.",
                entry.component_cid
            );
        }
        None => {
            let msg = if let Some(ver) = version {
                format!("{}@{} not found in registry.", name, ver)
            } else {
                format!("{} not found in registry.", name)
            };
            eprintln!("{msg}");
            eprintln!("Use `gang registry search` to discover available capabilities.");
        }
    }
    Ok(())
}

/// `gang registry publish <wasm_path>`
pub async fn registry_publish(
    wasm_path: &str,
    description: Option<&str>,
    tags: Option<&[String]>,
    _format: &OutputFormat,
) -> anyhow::Result<()> {
    let path = Path::new(wasm_path);
    if !path.exists() {
        anyhow::bail!("file not found: {wasm_path}");
    }

    // Read the component and compute CID
    let data = std::fs::read(path)?;
    let component_cid = gang_core::artifacts::Cid::from_bytes(&data);

    // Read the manifest and compute its CID
    let manifest_path = path.with_extension("manifest.cbor");
    let manifest_cid = if manifest_path.exists() {
        let manifest_bytes = std::fs::read(&manifest_path)?;
        gang_core::artifacts::Cid::from_bytes(&manifest_bytes)
    } else {
        // No manifest found; compute CID from the component bytes as fallback
        gang_core::artifacts::Cid::from_bytes(&data)
    };

    // Derive name from filename
    let name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("unknown")
        .to_string();

    // Load identity for author
    let key_path = gang_core::identity::default_key_path();
    let author = if key_path.exists() {
        let kp = gang_core::identity::Keypair::load(&key_path)?;
        kp.peer_id().as_str().to_string()
    } else {
        "unknown".to_string()
    };

    let entry = gang_core::registry::RegistryEntry {
        name: name.clone(),
        version: "0.1.0".into(),
        description: description.unwrap_or("A Ganglion capability").into(),
        author_peer_id: author,
        language: gang_core::registry::CapabilityLanguage::Rust,
        component_cid: component_cid.clone(),
        manifest_cid,
        declared_capabilities: vec![],
        published_at: chrono::Utc::now().to_rfc3339(),
        tags: tags.map(|t| t.to_vec()).unwrap_or_default(),
        min_ganglion_version: Some("0.4.0".into()),
    };

    let mut reg = gang_core::registry::Registry::open(&registry_dir())?;
    reg.publish(entry)?;

    println!("Published {} to local registry.", name);
    println!("  Component CID: {}", component_cid);
    println!("  Registry path: {}", registry_dir().display());
    Ok(())
}

/// `gang registry list`
pub async fn registry_list(_format: &OutputFormat) -> anyhow::Result<()> {
    let reg = gang_core::registry::Registry::open(&registry_dir())?;
    let list = reg.list();

    if list.is_empty() {
        println!("No capabilities in local registry.");
        println!("Use `gang registry publish` to add a capability.");
        return Ok(());
    }

    println!("{} capability(ies) in registry:\n", list.len());
    for r in &list {
        println!("  {} v{} [{}]", r.name, r.latest_version, r.language);
        println!("    {}", r.description);
    }
    Ok(())
}

/// `gang registry info <name>`
pub async fn registry_info(name: &str, _format: &OutputFormat) -> anyhow::Result<()> {
    let reg = gang_core::registry::Registry::open(&registry_dir())?;

    match reg.get(name) {
        Some(versions) => {
            println!("Capability: {name}\n");
            for entry in versions {
                println!("  v{}", entry.version);
                println!("    Description:   {}", entry.description);
                println!("    Author:        {}", entry.author_peer_id);
                println!("    Language:       {}", entry.language);
                println!("    Published:     {}", entry.published_at);
                println!("    Component CID: {}", entry.component_cid);
                if !entry.declared_capabilities.is_empty() {
                    println!(
                        "    Capabilities:  {}",
                        entry.declared_capabilities.join(", ")
                    );
                }
                if !entry.tags.is_empty() {
                    println!("    Tags:          {}", entry.tags.join(", "));
                }
                if let Some(min_ver) = &entry.min_ganglion_version {
                    println!("    Min Ganglion:  {min_ver}");
                }
                println!();
            }
        }
        None => {
            eprintln!("{name} not found in registry.");
        }
    }
    Ok(())
}

/// `gang relay` — run a circuit relay v2 server.
pub async fn relay(
    listen_addrs: Option<Vec<String>>,
    port: u16,
    metrics_port: u16,
) -> anyhow::Result<()> {
    use gang_libp2p::Libp2pConfig;

    // Load or generate identity
    let key_path = gang_core::identity::default_key_path();
    let keypair = gang_core::identity::Keypair::load_or_generate(&key_path)?;
    let peer_id = keypair.peer_id();

    // Build listen addresses from explicit addrs or port shorthand
    let addrs = match listen_addrs {
        Some(addrs) if !addrs.is_empty() => addrs,
        _ => vec![
            format!("/ip4/0.0.0.0/tcp/{port}"),
            format!("/ip4/0.0.0.0/udp/{port}/quic-v1"),
        ],
    };

    let config = Libp2pConfig {
        key_path,
        listen_addrs: addrs.clone(),
        relay_server: true,
        ..Default::default()
    };

    println!("Ganglion Relay Server");
    println!("====================");
    println!();
    println!("Peer ID:      {peer_id}");
    println!("Relay mode:   server");
    println!("Metrics port: {metrics_port} (not yet active)");
    println!();
    println!("Listen addresses:");
    for addr in &addrs {
        println!("  {addr}");
    }
    println!();

    // Print the relay multiaddr that clients should use
    println!("Relay multiaddrs (for client config):");
    for addr in &addrs {
        println!("  {addr}/p2p/{peer_id}");
    }
    println!();

    // Create the transport adapter and run
    let adapter = gang_libp2p::Libp2pTransportAdapter::new(config).await?;

    println!("Relay is running. Press Ctrl+C to stop.");
    println!();

    // Run the event loop until interrupted
    tokio::select! {
        result = adapter.run_event_loop() => {
            if let Err(e) = result {
                eprintln!("Event loop error: {e}");
            }
        }
        _ = tokio::signal::ctrl_c() => {
            println!("\nRelay stopped.");
        }
    }

    Ok(())
}

fn format_duration(secs: u64) -> String {
    if secs >= 3600 {
        let h = secs / 3600;
        let m = (secs % 3600) / 60;
        format!("{h}h {m}m")
    } else if secs >= 60 {
        let m = secs / 60;
        let s = secs % 60;
        format!("{m}m {s}s")
    } else {
        format!("{secs}s")
    }
}