hopper-cli 0.5.0

Command-line tooling for Hopper account inspection, schema export, and migration planning
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
//! # Hopper CLI
//!
//! Command-line tool for inspecting Hopper accounts, comparing layout
//! schemas, generating migration plans, and exporting schema metadata.
//!
//! ## Command Families
//!
//! ```text
//! hopper schema export --anchor-idl <manifest> --program-id <id>  Export current Solana/Anchor IDL
//! hopper schema validate <manifest-json>            Validate a manifest
//! hopper schema diff <old> <new>                    Field-level diff
//!
//! hopper compile --emit <rust|ts|kt|py|go|c|rust-client|idl|codama|schema|manifest> [<manifest>|--package <name>|--program-id ...]
//!                                                     Emit lowered Rust, client SDKs, IDL JSON, Codama, or manifest
//!
//! hopper verify [<manifest>] [<.so>]                  Verify manifest integrity and ELF interface binding
//! hopper verify --package <name>                      Infer manifest and SBF binary from a workspace package
//! hopper publish-check --package <name>                Run release/source gates before publishing
//! hopper publish-idl --manifest <p> --program-id <id> [--dry-run]  Publish Solana IDL v0.1.0 to the metadata PDA
//! hopper solana-check [--all]                          Verify Hopper program crates are SBF-shaped
//!
//! hopper inspect <hex-data>                         Decode account header
//! hopper inspect layout <manifest> <hex-data>       Decode fields using a program manifest
//! hopper inspect segments <hex-data>                Decode segment map
//! hopper inspect receipt <hex-data>                 Decode a state receipt
//!
//! hopper explain <hex-data>                         Human-readable headered-account explanation
//! hopper explain account <hex-data>                  Explicit headered-account explanation
//! hopper explain receipt <hex-data>                  Explain a receipt in plain English
//! hopper explain compat <old> <new>                  Explain compatibility
//! hopper explain policy <policy-pack>                Explain a named policy pack
//! hopper explain layout <manifest>                   Explain layout fields and fingerprint
//! hopper explain program <manifest>                  Explain entire program pipeline
//! hopper explain instruction <manifest> <tag|name>    Explain one instruction's accounts and policy
//!
//! hopper compat <old> <new>                         Compatibility report
//! hopper compat --why <old> <new>                   Compatibility with explanations
//!
//! hopper plan <old> <new>                           Generate migration plan
//!
//! hopper receipt <hex-data>                         Decode and display receipt
//!
//! hopper manager <subcommand> ..                   Program management
//!
//! hopper fetch <program-id>                          Fetch an application-provisioned legacy manifest PDA
//!
//! hopper init [path]                                 Create a Hopper project (wizard if path omitted)
//! hopper add [-i|-s|-e <name>]                       Scaffold an instruction, state, or error
//! hopper build [--host|--sbf]                        Build the current project
//! hopper test                                        Run host-side tests for the current project
//! hopper deploy                                      Build and deploy the current SBF program
//! hopper dump                                        Disassemble the current SBF artifact
//! hopper clean [-a|--all]                            Remove build artefacts (preserves keypairs)
//! hopper profile bench                               Run the primitive benchmark lab
//! hopper keys new|sync|pda|list|print                 Keypair and PDA helpers
//! hopper config get|set|list|reset|path               Global configuration store
//! hopper lint                                        Run Hopper project diagnostics
//! hopper fuzz generate --program <manifest>          Generate seeded adversarial cases
//! hopper fuzz check --program <manifest>             Fail when cases drift from the manifest
//! hopper fuzz run --program <manifest> --adapter <exe> Execute cases through a program adapter
//! hopper lint zc                                     Run zero-copy source diagnostics
//! hopper contention <manifest>                       Declared write-lock and signature footprint
//! hopper expand                                      Show lowered macro output
//! hopper tx explain <signature>                       Fetch and explain an on-chain transaction
//! hopper tx send --program <id> --account ... --data <hex>  Generic instruction sender (no Node)
//! hopper tx simulate|submit <tx-base64>                Pre-built transaction helpers
//! hopper doctor                                      Check toolchain and workspace health
//! hopper completions <shell>                          Emit shell completions
//! hopper version                                      Print CLI version info
//!
//! hopper interactive <manifest>                      Interactive terminal explorer
//!
//! hopper client gen --ts <manifest>                 Generate TypeScript client
//! hopper client gen --kt <manifest>                 Generate Kotlin client
//! hopper client gen --py <manifest>                 Generate Python client
//! hopper client gen --go <manifest>                 Generate Go client
//! hopper client gen --c <manifest>                  Generate C client header
//! hopper actions gen --program <manifest> --out api/actions
//! hopper mobile gen --program <manifest> --target kotlin|react-native
//! hopper test-gen security --program <manifest>
//! ```
//!
//! Hex data is passed as a hex string (no 0x prefix).
//! Manifest arguments accept inline JSON or `@path/to/file.json`.

use hopper_schema::accounts::{AccountLifecycle, ContextAccountDescriptor, ContextDescriptor};
use hopper_schema::c_client::CClientGen;
use hopper_schema::clientgen::{KtClientGen, TsClientGen};
use hopper_schema::go_client::GoClientGen;
use hopper_schema::python_client::PyClientGen;
use hopper_schema::{
    compare_fields,
    decode_account_fields,
    decode_header,
    decode_segments,
    // Manager types
    AccountEntry,
    ArgDescriptor,
    // Receipt types (re-exported from hopper-core)
    CompatImpact,
    CompatibilityPair,
    CompatibilityVerdict,
    DecodedHeader,
    DecodedReceipt,
    EventDescriptor,
    FieldCompat,
    FieldDescriptor,
    FieldIntent,
    InstructionDescriptor,
    LayoutFingerprint,
    LayoutManifest,
    LayoutMetadata,
    MigrationAction,
    MigrationPlan,
    MigrationPolicy,
    Phase,
    PolicyDescriptor,
    ProgramManifest,
    SegmentMigrationReport,
    SegmentRoleHint,
    WriteRange,
};
use std::env;
use std::path::PathBuf;
use std::process;

mod bench;
mod cmd;
mod config;
mod interactive;
mod rpc;
mod style;
mod workspace;

/// Decode a Hopper header or exit with a diagnostic message.
fn require_header(data: &[u8]) -> DecodedHeader {
    match decode_header(data) {
        Some(h) => h,
        None => {
            eprintln!(
                "Failed to decode Hopper header (data too short: {} bytes).",
                data.len()
            );
            process::exit(1);
        }
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        print_usage();
        process::exit(1);
    }

    // Resolve the colour preference once, ahead of any command output.
    // Order: `ui.color = false` in the global config wins over the
    // auto-detect in `style::*`. The `NO_COLOR` env var and the TTY
    // probe are handled inside `style::auto_detect`, so we only have
    // to override here when the user has explicitly opted out via
    // their saved preferences.
    if !config::GlobalConfig::load().ui.color {
        style::init(false);
    }

    match args[1].as_str() {
        // Command families
        "schema" => cmd_schema_family(&args[2..]),
        "compile" => cmd_compile(&args[2..]),
        "inspect" => cmd_inspect_family(&args[2..]),
        "explain" => cmd_explain_family(&args[2..]),
        "client" => cmd_client_family(&args[2..]),
        "profile" => cmd::profile::cmd_profile(&args[2..]),

        // On-chain fetch
        "fetch" => cmd_fetch(&args[2..]),

        // Lifecycle
        "init" => cmd::lifecycle::cmd_init(&args[2..]),
        "add" => cmd::add::cmd_add(&args[2..]),
        "build" => cmd::lifecycle::cmd_build(&args[2..]),
        "test" => cmd::lifecycle::cmd_test(&args[2..]),
        "deploy" => cmd::lifecycle::cmd_deploy(&args[2..]),
        "upgrade" => cmd::lifecycle::cmd_upgrade(&args[2..]),
        "close" => cmd::lifecycle::cmd_close(&args[2..]),
        "buffers" => cmd::buffers::cmd_buffers(&args[2..]),
        "migrate" => cmd::lifecycle::cmd_migrate(&args[2..]),
        "dump" => cmd::lifecycle::cmd_dump(&args[2..]),
        "clean" => cmd::clean::cmd_clean(&args[2..]),
        "verify" => cmd::verify::cmd_verify(&args[2..]),
        "publish-check" => cmd::publish_check::cmd_publish_check(&args[2..]),
        "audit-check" => cmd::audit_check::cmd_audit_check(&args[2..]),
        "publish-idl" => cmd::publish_idl::cmd_publish_idl(&args[2..]),
        "publish-security" => cmd::publish_security::cmd_publish_security(&args[2..]),
        "publish-manifest" => cmd::publish_manifest::cmd_publish_manifest(&args[2..]),
        "solana-check" => cmd::solana_check::cmd_solana_check(&args[2..]),

        // DX and tooling
        "keys" => cmd::keys::cmd_keys(&args[2..]),
        "config" => cmd::config::cmd_config(&args[2..]),
        "lint" => cmd::lint::cmd_lint(&args[2..]),
        "fuzz" => cmd::fuzz::cmd_fuzz(&args[2..], load_program_manifest),
        "contention" => cmd::contention::cmd_contention(&args[2..], load_program_manifest),
        "expand" => cmd::expand::cmd_expand(&args[2..]),
        "tx" => cmd_tx_family(&args[2..]),
        "doctor" => cmd::doctor::cmd_doctor(&args[2..]),
        "feature-gate" | "feature-gates" => cmd::feature_gate::cmd_feature_gate(&args[2..]),
        "completions" => cmd::meta::cmd_completions(&args[2..]),
        "version" | "--version" | "-V" => cmd::meta::cmd_version(&args[2..]),
        "actions" => cmd::actions::cmd_actions(&args[2..]),
        "mobile" => cmd::mobile::cmd_mobile(&args[2..]),
        "test-gen" => cmd::test_gen::cmd_test_gen(&args[2..]),

        // Direct commands (backward compatible)
        "decode" => cmd_inspect(&args[2..]),
        "segments" => cmd_segments(&args[2..]),
        "receipt" => cmd_receipt(&args[2..]),
        "compat" => cmd_compat(&args[2..]),
        "diff" => cmd_diff(&args[2..]),
        "plan" => cmd_plan(&args[2..]),
        "schema-export" => cmd_schema_export(),
        "manager" => cmd_manager(&args[2..]),
        "interactive" | "ui" => cmd_interactive(&args[2..]),
        "help" | "--help" | "-h" => print_usage(),
        other => {
            eprintln!("Unknown command: {}", other);
            print_usage();
            process::exit(1);
        }
    }
}

// ---------------------------------------------------------------------------
// Command Family Routers
// ---------------------------------------------------------------------------

fn cmd_schema_family(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper schema <subcommand>");
        eprintln!();
        eprintln!("Subcommands:");
        eprintln!(
            "  export [--manifest|--idl|--codama]  Export schema; --anchor-idl also requires --program-id"
        );
        eprintln!("  validate <manifest-json>            Validate a program manifest");
        eprintln!("  diff <old-json> <new-json>          Field-level diff between versions");
        process::exit(1);
    }
    match args[0].as_str() {
        "export" => cmd_schema_export_family(&args[1..]),
        "validate" => cmd_schema_validate(&args[1..]),
        "diff" => cmd_diff(&args[1..]),
        other => {
            eprintln!("Unknown schema subcommand: {}", other);
            process::exit(1);
        }
    }
}

fn cmd_inspect_family(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper inspect <hex-data|subcommand>");
        eprintln!();
        eprintln!("  hopper inspect <hex-data>            Decode account header");
        eprintln!("  hopper inspect layout <manifest> <hex-data>  Decode fields using a manifest");
        eprintln!("  hopper inspect segments <hex-data>   Decode segment map");
        eprintln!("  hopper inspect receipt <hex-data>    Decode a state receipt");
        process::exit(1);
    }
    match args[0].as_str() {
        "layout" => cmd_inspect_layout(&args[1..]),
        "segments" => cmd_segments(&args[1..]),
        "receipt" => cmd_receipt(&args[1..]),
        _ => cmd_inspect(args), // treat first arg as hex data
    }
}

fn cmd_explain_family(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain <hex-data|subcommand>");
        eprintln!();
        eprintln!(
            "  hopper explain <hex-data>            Human-readable headered-account explanation"
        );
        eprintln!("  hopper explain account <hex-data>    Explicit headered-account explanation");
        eprintln!("  hopper explain receipt <hex-data>    Explain a receipt in plain English");
        eprintln!("  hopper explain compat <old> <new>    Explain compatibility report");
        eprintln!("  hopper explain policy <pack-name>    Explain a named policy pack");
        eprintln!("  hopper explain layout <manifest>     Explain layout fields, intents, and fingerprint");
        eprintln!(
            "  hopper explain program <manifest>    Explain an entire program from its manifest"
        );
        eprintln!("  hopper explain context <manifest>    Explain instruction contexts (accounts, roles, policies)");
        eprintln!("  hopper explain instruction <manifest> <tag|name>  Explain one instruction's accounts and policy");
        process::exit(1);
    }
    match args[0].as_str() {
        "account" => cmd_explain(&args[1..]),
        "receipt" => cmd_explain_receipt(&args[1..]),
        "compat" => cmd_explain_compat(&args[1..]),
        "policy" => cmd_explain_policy(&args[1..]),
        "layout" => cmd_explain_layout(&args[1..]),
        "program" => cmd_explain_program(&args[1..]),
        "context" => cmd_explain_context(&args[1..]),
        "instruction" => cmd_explain_instruction(&args[1..]),
        // Top-level differentiator: `hopper explain <tx-sig|program-id>`.
        // A confirmed-tx signature can decode against application-provisioned
        // legacy Hopper manifest PDAs; a program address fetches that same
        // legacy PDA and renders a program explanation. Anything else falls
        // back to treating the first arg as raw account hex.
        first if looks_like_tx_signature(first) => {
            cmd::tx_explain::cmd_tx_explain(args);
        }
        first if looks_like_program_id(first) => {
            cmd_explain_program_onchain(args);
        }
        _ => cmd_explain(args), // treat first arg as hex data
    }
}

/// A base58 confirmed-transaction signature is 64 raw bytes, which
/// encodes to 86-88 base58 chars. Hex account data never reaches that
/// length with a purely base58 alphabet, so length + alphabet is a
/// reliable discriminator here.
fn looks_like_tx_signature(s: &str) -> bool {
    if s.len() < 84 || s.len() > 90 {
        return false;
    }
    is_base58(s)
        && bs58::decode(s)
            .into_vec()
            .map(|b| b.len() == 64)
            .unwrap_or(false)
}

/// A base58 program address is 32 raw bytes (32-44 base58 chars). We
/// also reject pure-hex strings (which would be account data) by
/// requiring at least one non-hex base58 character, so a short hex blob
/// is never mistaken for an address.
fn looks_like_program_id(s: &str) -> bool {
    if s.len() < 32 || s.len() > 44 {
        return false;
    }
    if !is_base58(s) {
        return false;
    }
    let all_hex = s.chars().all(|c| c.is_ascii_hexdigit());
    if all_hex {
        return false;
    }
    bs58::decode(s)
        .into_vec()
        .map(|b| b.len() == 32)
        .unwrap_or(false)
}

fn is_base58(s: &str) -> bool {
    const ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    !s.is_empty() && s.bytes().all(|b| ALPHABET.contains(&b))
}

/// Fetch a program's on-chain Hopper manifest by address and render the
/// same full explanation as `hopper explain program <manifest-file>`.
fn cmd_explain_program_onchain(args: &[String]) {
    let program_id = &args[0];
    let mut rpc_override: Option<String> = None;
    let mut i = 1;
    while i < args.len() {
        if args[i] == "--rpc" {
            rpc_override = args.get(i + 1).cloned();
            i += 2;
        } else {
            i += 1;
        }
    }
    let rpc_url = crate::rpc::resolve_rpc_url(rpc_override.as_deref());
    match cmd::manager_invoke::try_fetch_manifest(&rpc_url, program_id) {
        Ok(json) => cmd_explain_program(&[json]),
        Err(e) => {
            eprintln!("hopper explain {program_id}: no on-chain Hopper manifest found ({e})");
            eprintln!();
            eprintln!("Hint: Hopper has no generic publisher for the legacy manifest PDA.");
            eprintln!("Pass a local manifest: `hopper explain program <manifest.json>`.");
            process::exit(1);
        }
    }
}

fn cmd_explain_instruction(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain instruction <manifest> <tag|name>");
        process::exit(1);
    }
    cmd_manager_instruction(args);
}

fn cmd_client_family(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper client gen [--ts|--kt|--py|--go|--c] <manifest-json>");
        eprintln!();
        eprintln!("Subcommands:");
        eprintln!("  gen --ts <manifest>   Generate TypeScript client SDK");
        eprintln!("  gen --kt <manifest>   Generate Kotlin client SDK");
        eprintln!("  gen --py <manifest>   Generate Python client SDK");
        eprintln!("  gen --go <manifest>   Generate Go client SDK");
        eprintln!("  gen --c <manifest>    Generate C client header");
        process::exit(1);
    }
    match args[0].as_str() {
        "gen" => cmd_client_gen(&args[1..]),
        other => {
            eprintln!("Unknown client subcommand: {}", other);
            process::exit(1);
        }
    }
}

#[derive(Default)]
struct RustEmitFilters {
    layout: Option<String>,
    instruction: Option<String>,
    context: Option<String>,
}

enum CompileManifestSource {
    Explicit(String),
    CurrentPackage,
    Package(String),
    ProgramId {
        program_id: String,
        rpc_override: Option<String>,
    },
}

struct CompileOptions {
    source: CompileManifestSource,
    filters: RustEmitFilters,
    out: Option<PathBuf>,
    force: bool,
    /// Inline `hopper lint` after the artifact emit. Errors fail the
    /// command; warnings are printed but pass.
    lint: bool,
    /// Treat warnings as errors when `--lint` is on.
    lint_fail_on_warn: bool,
}

/// Multi-target emit dispatch.
///
/// `hopper compile --emit <target> ...` routes through a single
/// trait-like dispatch table rather than a hard-coded `== "rust"`
/// check. Each target shares the common argument parsing
/// (`parse_compile_options`) and output handling (stdout vs
/// `--out` + `--force`). Adding a new target is one entry here
/// and one renderer fn.
fn cmd_compile(args: &[String]) {
    if args.iter().any(|arg| arg == "--help" || arg == "-h") {
        print_compile_usage();
        return;
    }

    if args.len() < 2 || args[0] != "--emit" {
        eprintln!("Usage: hopper compile --emit <target> [options]");
        eprintln!();
        eprintln!("Supported targets:");
        eprintln!("  rust          Lowered Rust preview (what the macros expand to)");
        eprintln!("  ts            TypeScript client SDK");
        eprintln!("  kt            Kotlin client SDK");
        eprintln!("  py            Python client SDK");
        eprintln!("  go            Go client SDK");
        eprintln!("  c             C client header");
        eprintln!("  rust-client   Off-chain Rust client (solana-sdk types)");
        eprintln!("  idl           Hopper public IDL JSON");
        eprintln!("  codama        Codama-flavored JSON");
        eprintln!("  schema        Hopper program manifest JSON (from an existing manifest)");
        eprintln!("  manifest      GENERATE hopper.manifest.json from the package source");
        eprintln!();
        eprintln!("See `hopper compile --help` for the full option set.");
        process::exit(1);
    }

    let target = args[1].as_str();
    let cwd = workspace::current_dir().unwrap_or_else(|err| {
        eprintln!("{err}");
        process::exit(1);
    });
    let options = parse_compile_options(&args[2..]).unwrap_or_else(|err| {
        eprintln!("hopper compile failed: {err}");
        process::exit(1);
    });
    // `--emit manifest` PRODUCES the manifest (from the package's exported
    // PROGRAM_MANIFEST static) that every other target consumes.
    if target == "manifest" {
        let package = match &options.source {
            CompileManifestSource::Package(name) => name.clone(),
            _ => {
                eprintln!(
                    "hopper compile --emit manifest requires --package <name> (the manifest is generated from that package's source)"
                );
                process::exit(1);
            }
        };
        let out = options.out.as_deref().map(std::path::Path::new);
        match cmd::emit_manifest::emit_manifest_from_source(&package, out, &cwd) {
            Ok(path) => {
                println!("wrote {}", path.display());
                println!(
                    "every emit target can now consume it, e.g. `hopper compile --emit ts --package {package}` or `hopper tx explain <sig> --manifest {}`",
                    path.display()
                );
                return;
            }
            Err(err) => {
                eprintln!("hopper compile failed: {err}");
                process::exit(1);
            }
        }
    }

    let prog = load_compile_manifest(&options.source, &cwd).unwrap_or_else(|err| {
        eprintln!("hopper compile failed: {err}");
        process::exit(1);
    });

    let (artifact, label): (String, &'static str) = match target {
        "rust" => match render_program_rust_preview(&prog, &options.filters) {
            Ok(text) => (text, "lowered Rust preview"),
            Err(err) => {
                eprintln!("hopper compile failed: {err}");
                process::exit(1);
            }
        },
        "ts" => (format!("{}", TsClientGen(&prog)), "TypeScript client SDK"),
        "kt" => (format!("{}", KtClientGen(&prog)), "Kotlin client SDK"),
        "py" => (format!("{}", PyClientGen(&prog)), "Python client SDK"),
        "go" => (format!("{}", GoClientGen(&prog)), "Go client SDK"),
        "c" => (format!("{}", CClientGen(&prog)), "C client header"),
        "rust-client" => (
            format!("{}", hopper_schema::rust_client::RsClientGen(&prog)),
            "Rust off-chain client",
        ),
        "idl" => (
            format!("{}", hopper_schema::codama::IdlJsonFromManifest(&prog)),
            "Hopper public IDL JSON",
        ),
        "codama" => (
            format!("{}", hopper_schema::codama::CodamaJsonFromManifest(&prog)),
            "Codama JSON",
        ),
        "schema" => (
            format!("{}", hopper_schema::codama::ManifestJson(&prog)),
            "Hopper manifest JSON",
        ),
        other => {
            eprintln!("Unsupported emit target: {}", other);
            eprintln!(
                "Supported: rust | ts | kt | py | go | c | rust-client | idl | codama | schema | manifest"
            );
            process::exit(1);
        }
    };

    if let Some(path) = options.out {
        let output_path = if path.is_absolute() {
            path
        } else {
            cwd.join(path)
        };
        workspace::write_text_file(&output_path, &artifact, options.force).unwrap_or_else(|err| {
            eprintln!("hopper compile failed: {err}");
            process::exit(1);
        });
        println!("Wrote {} to {}", label, output_path.display());
    } else {
        print!("{artifact}");
    }

    // Optional inline lint pass. Mirrors `hopper lint` over the same
    // project tree so authors don't need a second invocation in
    // tight build/iterate loops. Errors fail the command; warnings
    // print but pass unless `--lint-fail-on-warn` is set.
    if options.lint {
        let project_root = workspace::find_project_root(&cwd).unwrap_or_else(|err| {
            eprintln!("hopper compile --lint failed: {err}");
            process::exit(1);
        });
        match cmd::lint::run_lint_diagnostics(&project_root) {
            Ok(summary) => {
                for line in &summary.lines {
                    println!("{line}");
                }
                eprintln!(
                    "[hopper compile --lint] {} error(s), {} warning(s)",
                    summary.errors, summary.warnings,
                );
                let fail =
                    summary.errors > 0 || (options.lint_fail_on_warn && summary.warnings > 0);
                if fail {
                    process::exit(1);
                }
            }
            Err(err) => {
                eprintln!("hopper compile --lint failed: {err}");
                process::exit(1);
            }
        }
    }
}

fn parse_compile_options(args: &[String]) -> Result<CompileOptions, String> {
    let mut explicit_manifest = None;
    let mut package = None;
    let mut program_id = None;
    let mut rpc_override = None;
    let mut filters = RustEmitFilters::default();
    let mut out = None;
    let mut force = false;
    let mut lint = false;
    let mut lint_fail_on_warn = false;
    let mut i = 0;

    while i < args.len() {
        match args[i].as_str() {
            "--program-id" => {
                if i + 1 >= args.len() {
                    return Err("--program-id requires a base58 program address".to_string());
                }
                program_id = Some(args[i + 1].clone());
                i += 2;
            }
            "--rpc" => {
                if i + 1 >= args.len() {
                    return Err("--rpc requires a URL argument".to_string());
                }
                rpc_override = Some(args[i + 1].clone());
                i += 2;
            }
            "--package" => {
                if i + 1 >= args.len() {
                    return Err("--package requires a workspace member name".to_string());
                }
                package = Some(args[i + 1].clone());
                i += 2;
            }
            "--layout" => {
                if i + 1 >= args.len() {
                    return Err("--layout requires a layout name".to_string());
                }
                filters.layout = Some(args[i + 1].clone());
                i += 2;
            }
            "--instruction" => {
                if i + 1 >= args.len() {
                    return Err("--instruction requires an instruction name".to_string());
                }
                filters.instruction = Some(args[i + 1].clone());
                i += 2;
            }
            "--context" => {
                if i + 1 >= args.len() {
                    return Err("--context requires a context name".to_string());
                }
                filters.context = Some(args[i + 1].clone());
                i += 2;
            }
            "--out" => {
                if i + 1 >= args.len() {
                    return Err("--out requires a file path".to_string());
                }
                out = Some(PathBuf::from(&args[i + 1]));
                i += 2;
            }
            "--force" => {
                force = true;
                i += 1;
            }
            "--lint" => {
                lint = true;
                i += 1;
            }
            "--lint-fail-on-warn" => {
                lint = true;
                lint_fail_on_warn = true;
                i += 1;
            }
            other if other.starts_with('-') => {
                return Err(format!("Unknown compile argument: {other}"));
            }
            other => {
                if explicit_manifest.is_some() {
                    return Err(format!("Unexpected extra manifest argument: {other}"));
                }
                explicit_manifest = Some(other.to_string());
                i += 1;
            }
        }
    }

    if rpc_override.is_some() && program_id.is_none() {
        return Err("--rpc is only valid together with --program-id".to_string());
    }

    let source_count =
        explicit_manifest.is_some() as u8 + package.is_some() as u8 + program_id.is_some() as u8;
    if source_count > 1 {
        return Err(
            "Choose only one manifest source: an explicit manifest, --package, or --program-id"
                .to_string(),
        );
    }

    let source = if let Some(program_id) = program_id {
        CompileManifestSource::ProgramId {
            program_id,
            rpc_override,
        }
    } else if let Some(package) = package {
        CompileManifestSource::Package(package)
    } else if let Some(arg) = explicit_manifest {
        CompileManifestSource::Explicit(arg)
    } else {
        CompileManifestSource::CurrentPackage
    };

    Ok(CompileOptions {
        source,
        filters,
        out,
        force,
        lint,
        lint_fail_on_warn,
    })
}

fn load_compile_manifest(
    source: &CompileManifestSource,
    cwd: &std::path::Path,
) -> Result<ProgramManifest, String> {
    match source {
        CompileManifestSource::Explicit(arg) => Ok(load_program_manifest(arg)),
        CompileManifestSource::CurrentPackage => {
            let manifest_path = workspace::infer_program_manifest_for_project(cwd)?;
            load_program_manifest_from_path(&manifest_path)
        }
        CompileManifestSource::Package(package) => {
            let workspace_root = workspace::find_workspace_root(cwd)?;
            let manifest_path =
                workspace::infer_program_manifest_for_package(&workspace_root, package)?;
            load_program_manifest_from_path(&manifest_path)
        }
        CompileManifestSource::ProgramId {
            program_id,
            rpc_override,
        } => {
            let json = fetch_manifest_json(program_id, rpc_override.as_deref());
            Ok(load_program_manifest_from_json(&json))
        }
    }
}

fn load_program_manifest_from_path(path: &std::path::Path) -> Result<ProgramManifest, String> {
    let json = std::fs::read_to_string(path)
        .map_err(|err| format!("Failed to read {}: {err}", path.display()))?;
    Ok(load_program_manifest_from_json(&json))
}

fn cmd_client_gen(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper client gen [--ts|--kt|--py|--go|--c] <manifest-json>");
        process::exit(1);
    }

    let (lang, manifest_arg) = if args[0].starts_with("--") {
        if args.len() < 2 {
            eprintln!("Usage: hopper client gen [--ts|--kt|--py|--go|--c] <manifest-json>");
            process::exit(1);
        }
        (args[0].as_str(), &args[1])
    } else {
        // Default to TypeScript
        ("--ts", &args[0])
    };

    let manifest = load_program_manifest(manifest_arg);

    match lang {
        "--ts" => {
            println!("{}", TsClientGen(&manifest));
        }
        "--kt" => {
            println!("{}", KtClientGen(&manifest));
        }
        "--py" => {
            println!("{}", PyClientGen(&manifest));
        }
        "--go" => {
            println!("{}", GoClientGen(&manifest));
        }
        "--c" => {
            println!("{}", CClientGen(&manifest));
        }
        other => {
            eprintln!(
                "Unknown language flag: {}. Use --ts, --kt, --py, --go, or --c.",
                other
            );
            process::exit(1);
        }
    }
}

fn cmd_schema_validate(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper schema validate <manifest-json>");
        process::exit(1);
    }
    let manifest = load_program_manifest(&args[0]);
    println!("=== Manifest Validation ===");
    println!();
    println!("  Program: {} v{}", manifest.name, manifest.version);
    println!("  Layouts: {}", manifest.layouts.len());
    println!("  Instructions: {}", manifest.instructions.len());
    println!("  Events: {}", manifest.events.len());
    println!("  Policies: {}", manifest.policies.len());
    println!();

    let mut errors = 0u32;
    // Check layouts have unique discriminators
    for (i, l1) in manifest.layouts.iter().enumerate() {
        for l2 in manifest.layouts[i + 1..].iter() {
            if l1.disc == l2.disc {
                println!(
                    "  ERROR: Duplicate discriminator {} for {} and {}",
                    l1.disc, l1.name, l2.name
                );
                errors += 1;
            }
        }
    }
    // Check instructions have unique tags
    for (i, ix1) in manifest.instructions.iter().enumerate() {
        for ix2 in manifest.instructions[i + 1..].iter() {
            if ix1.tag == ix2.tag {
                println!(
                    "  ERROR: Duplicate instruction tag {} for {} and {}",
                    ix1.tag, ix1.name, ix2.name
                );
                errors += 1;
            }
        }
    }
    // Check events have unique tags
    for (i, e1) in manifest.events.iter().enumerate() {
        for e2 in manifest.events[i + 1..].iter() {
            if e1.tag == e2.tag {
                println!(
                    "  ERROR: Duplicate event tag {} for {} and {}",
                    e1.tag, e1.name, e2.name
                );
                errors += 1;
            }
        }
    }

    if errors == 0 {
        println!("  VALID: No errors found.");
    } else {
        println!();
        println!("  {} error(s) found.", errors);
        process::exit(1);
    }
}

fn cmd_explain_receipt(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain receipt <hex-data>");
        process::exit(1);
    }
    let data = match hex_decode(&args[0]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };
    if data.len() < RECEIPT_WIRE_SIZE {
        eprintln!("Receipt data too short.");
        process::exit(1);
    }

    let changed_bytes = u32::from_le_bytes(data[16..20].try_into().expect("slice length mismatch"));
    let flags = data[32];
    let was_resized = flags & (1 << 0) != 0;
    let invariants_passed = flags & (1 << 1) != 0;
    let cpi_invoked = flags & (1 << 2) != 0;
    let committed = flags & (1 << 3) != 0;
    let before_fp = &data[33..41];
    let after_fp = &data[41..49];
    let phase = data[58];
    let compat_impact = data[61];
    let migration_flags = data[62];

    let phase_name = match phase {
        1 => "initialization",
        2 => "close",
        3 => "migration",
        4 => "read-only inspection",
        _ => "update",
    };

    println!("=== Receipt Explanation ===");
    println!();
    if !committed {
        println!("  This receipt was NOT committed. The mutation was started but not finalized.");
        return;
    }
    println!("  This receipt records a state {} operation.", phase_name);
    if before_fp == after_fp {
        println!("  The account data was NOT changed (fingerprints match).");
    } else {
        println!(
            "  The account data WAS changed ({} bytes modified).",
            changed_bytes
        );
    }
    if was_resized {
        let old_size = u32::from_le_bytes(data[22..26].try_into().expect("slice length mismatch"));
        let new_size = u32::from_le_bytes(data[26..30].try_into().expect("slice length mismatch"));
        println!(
            "  The account was RESIZED from {} to {} bytes.",
            old_size, new_size
        );
    }
    if invariants_passed {
        println!("  All invariants PASSED.");
    } else {
        let inv_checked =
            u16::from_le_bytes(data[30..32].try_into().expect("slice length mismatch"));
        if inv_checked > 0 {
            println!("  WARNING: Invariants were checked but DID NOT PASS.");
        }
    }
    if cpi_invoked {
        let cpi_count = data[57];
        println!("  CPI was invoked ({} call(s)).", cpi_count);
    }
    if compat_impact != 0 {
        let impact_name = match compat_impact {
            1 => "append-only (backward readable)",
            2 => "requires migration",
            3 => "BREAKING",
            _ => "unknown",
        };
        println!("  Compatibility impact: {}.", impact_name);
    }
    if migration_flags != 0 {
        let mut mig = Vec::new();
        if migration_flags & 1 != 0 {
            mig.push("triggered");
        }
        if migration_flags & 2 != 0 {
            mig.push("realloc");
        }
        if migration_flags & 4 != 0 {
            mig.push("schema bump");
        }
        println!("  Migration: {}.", mig.join(", "));
    }
}

fn cmd_explain_compat(args: &[String]) {
    if args.len() < 2 {
        eprintln!("Usage: hopper explain compat <v1-json> <v2-json>");
        process::exit(1);
    }
    let v1 = parse_or_exit(&args[0]);
    let v2 = parse_or_exit(&args[1]);
    let (m1, _f1) = to_manifest(&v1);
    let (m2, _f2) = to_manifest(&v2);

    let verdict = CompatibilityVerdict::between(&m1, &m2);

    println!("=== Compatibility Explanation ===");
    println!();
    println!(
        "  Comparing '{}' v{} → v{}",
        m1.name, m1.version, m2.version
    );
    println!("  Verdict: {}", verdict.name());
    println!();

    match verdict {
        CompatibilityVerdict::Identical => {
            println!("  No structural changes detected.");
        }
        CompatibilityVerdict::WireCompatible => {
            println!("  WIRE-COMPATIBLE: Byte layout is identical but semantic metadata differs.");
            println!("  Readers can parse both versions with the same wire code.");
            println!("  Review field intents and update tooling if semantics changed.");
        }
        CompatibilityVerdict::AppendSafe => {
            println!("  SAFE upgrade: New version preserves the old field prefix.");
            println!("  Old readers can still parse new accounts (they ignore new fields).");
        }
        CompatibilityVerdict::MigrationRequired => {
            println!("  MIGRATION required: Field layout has changed.");
            println!("  Old data is NOT directly backward-readable.");
            println!("  You need a migration instruction to move accounts to the new layout.");
            println!("  Use `hopper plan` to generate a step-by-step migration plan.");
        }
        CompatibilityVerdict::Incompatible => {
            println!("  BREAKING change: Field layout has changed and is NOT backward-readable.");
            println!("  You MUST migrate all accounts before deploying the new version.");
            println!("  Use `hopper plan` to generate a step-by-step migration plan.");
        }
    }

    // Explain field-level changes
    let report = compare_fields::<64>(&m1, &m2);
    let mut changes = Vec::new();
    for i in 0..report.len() {
        if let Some(entry) = report.get(i) {
            match entry.status {
                FieldCompat::Identical => {}
                FieldCompat::Added => changes.push(format!("  + Added field '{}'", entry.name)),
                FieldCompat::Removed => changes.push(format!("  - Removed field '{}'", entry.name)),
                FieldCompat::Changed => changes.push(format!("  ~ Changed field '{}'", entry.name)),
            }
        }
    }
    if !changes.is_empty() {
        println!();
        println!("  Field changes:");
        for c in &changes {
            println!("{}", c);
        }
    }
}

fn cmd_explain_policy(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain policy <pack-name>");
        eprintln!();
        eprintln!("Available packs:");
        eprintln!("  TreasuryWrite       Vault/treasury balance mutations");
        eprintln!("  JournalTouch        Journal segment writes");
        eprintln!("  ExternalCall        CPI-invoking instructions");
        eprintln!("  ShardMutation       Shard data modifications");
        eprintln!("  MigrationSensitive  Account reallocation/migration");
        eprintln!("  AuthorityChange     Authority/permission modifications");
        eprintln!("  ReadOnlyAudit       Read-only inspection/audit");
        eprintln!("  AccountInit         Account creation");
        eprintln!("  AccountClose        Account closure");
        process::exit(1);
    }

    let policy_info: (&str, &[(&str, &str)], bool, &[&str]) = match args[0].as_str() {
        "TreasuryWrite" => (
            "Vault/treasury balance mutations",
            &[
                ("MutatesState", "Authority, StateSnapshot"),
                ("MutatesTreasury", "LamportConservation, InvariantCheck"),
            ],
            true,
            &["lamport_balance_conserved", "no_phantom_credit"],
        ),
        "JournalTouch" => (
            "Journal segment writes",
            &[
                ("MutatesState", "Authority"),
                ("TouchesJournal", "JournalCapacity, StateSnapshot"),
            ],
            true,
            &["journal_append_only", "segment_bounds_checked"],
        ),
        "ExternalCall" => (
            "CPI-invoking instructions",
            &[("ExternalCall", "CpiGuard, PostMutationCheck, StateSnapshot")],
            true,
            &["cpi_target_allowlisted", "no_reentrant_mutation"],
        ),
        "ShardMutation" => (
            "Shard data modifications",
            &[("MutatesState", "Authority, StateSnapshot, InvariantCheck")],
            true,
            &["shard_index_bounds_checked", "discriminator_preserved"],
        ),
        "MigrationSensitive" => (
            "Account reallocation/migration",
            &[(
                "ReallocatesAccount",
                "Authority, RentExemption, StateSnapshot, InvariantCheck",
            )],
            true,
            &["layout_id_updated", "old_data_preserved_or_migrated"],
        ),
        "AuthorityChange" => (
            "Authority/permission modifications",
            &[(
                "ModifiesAuthority",
                "Authority, CpiGuard, PostMutationCheck, InvariantCheck",
            )],
            true,
            &["old_authority_signed", "no_authority_escalation"],
        ),
        "ReadOnlyAudit" => (
            "Read-only inspection",
            &[("ReadsState", "StateSnapshot")],
            false,
            &["no_state_mutation"],
        ),
        "AccountInit" => (
            "Account creation",
            &[("CreatesAccount", "Authority, RentExemption, InvariantCheck")],
            true,
            &["header_initialized_correctly", "discriminator_set"],
        ),
        "AccountClose" => (
            "Account closure",
            &[(
                "ClosesAccount",
                "Authority, StateSnapshot, LamportConservation",
            )],
            true,
            &["lamports_drained", "data_zeroed"],
        ),
        other => {
            eprintln!("Unknown policy pack: {}", other);
            process::exit(1);
        }
    };

    println!("=== Policy Pack: {} ===", args[0]);
    println!();
    println!("  Purpose: {}", policy_info.0);
    println!();
    println!("  Rules:");
    for &(cap, reqs) in policy_info.1 {
        println!("    When {}  → require {}", cap, reqs);
    }
    println!();
    println!(
        "  Receipt expected: {}",
        if policy_info.2 { "YES" } else { "NO" }
    );
    println!();
    if !policy_info.3.is_empty() {
        println!("  Invariant hints:");
        for hint in policy_info.3 {
            println!("    • {}", hint);
        }
        println!();
    }
    println!("  When this policy pack is active, the listed requirements");
    println!("  are automatically enforced for any instruction declaring");
    println!("  the corresponding capability.");
}

fn cmd_explain_layout(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain layout <manifest-json>");
        process::exit(1);
    }
    let pm = load_program_manifest(&args[0]);

    println!("=== Layout Explanation: {} v{} ===", pm.name, pm.version);
    println!();

    if pm.layouts.is_empty() {
        println!("  No layouts defined.");
        return;
    }

    for layout in pm.layouts {
        println!(
            "  Layout: {} (disc={}, version={})",
            layout.name, layout.disc, layout.version
        );
        println!("    Wire layout_id: {}", hex_encode(&layout.layout_id));

        let fp = LayoutFingerprint::from_manifest(layout);
        println!(
            "    Semantic fingerprint: {}",
            hex_encode(&fp.semantic_hash)
        );
        println!(
            "    Total size: {} bytes ({} fields)",
            layout.total_size, layout.field_count
        );
        println!();

        if layout.fields.is_empty() {
            println!("    (no field descriptors)");
        } else {
            println!("    Fields:");
            let mut monetary_count = 0u32;
            let mut identity_count = 0u32;
            for field in layout.fields {
                let intent_tag = if field.intent as u8 != 255 {
                    field.intent.name()
                } else {
                    "custom"
                };
                println!(
                    "      {:16} {:12} {:>3}B  @{:<4}  intent={}",
                    field.name, field.canonical_type, field.size, field.offset, intent_tag
                );
                if field.intent.is_monetary() {
                    monetary_count += 1;
                }
                if field.intent.is_identity() {
                    identity_count += 1;
                }
            }
            println!();
            if monetary_count > 0 {
                println!(
                    "    {} monetary field(s): lamport conservation checks recommended.",
                    monetary_count
                );
            }
            if identity_count > 0 {
                println!(
                    "    {} identity field(s): authority validation required.",
                    identity_count
                );
            }
        }
        println!();
    }
}

fn cmd_explain_program(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain program <manifest>");
        eprintln!("  Human-readable explanation of the entire program: layouts, instructions,");
        eprintln!("  policies, events, compatibility, and the Hopper pipeline steps it uses.");
        process::exit(1);
    }
    let prog = load_program_manifest(&args[0]);

    println!("=== Program: {} v{} ===", prog.name, prog.version);
    println!();
    println!("  {}", prog.description);
    println!();

    // Pipeline coverage
    println!("  Pipeline Coverage:");
    println!("    1. Define     {} layout(s) defined", prog.layouts.len());
    println!(
        "    2. Resolve    {} instruction(s) with account resolution",
        prog.instructions.len()
    );
    let policy_count = prog.policies.len();
    if policy_count > 0 {
        println!("    3. Validate   {} policy pack(s) enforced", policy_count);
    } else {
        println!("    3. Validate   (no named policies; consider adding policy packs)");
    }
    println!("    4. Execute    Mutations guarded by capabilities");
    let receipt_count = prog
        .instructions
        .iter()
        .filter(|ix| ix.receipt_expected)
        .count();
    if receipt_count > 0 {
        println!(
            "    5. Record     {} instruction(s) emit receipts",
            receipt_count
        );
    } else {
        println!("    5. Record     (no receipt expectations; consider adding receipt tracking)");
    }
    let compat_count = prog.compatibility_pairs.len();
    if compat_count > 0 {
        println!("    6. Verify     {} compatibility rule(s)", compat_count);
    } else {
        println!("    6. Verify     (no compat rules; safe for single-version programs)");
    }
    let event_count = prog.events.len();
    println!(
        "    7. Inspect    {} event(s) for off-chain observability",
        event_count
    );
    println!();

    // Layouts
    println!("  Layouts:");
    for l in prog.layouts.iter() {
        let fp = LayoutFingerprint::from_manifest(l);
        println!(
            "    {} v{} | disc {} | {} bytes | {} fields",
            l.name, l.version, l.disc, l.total_size, l.field_count
        );
        println!(
            "      wire={}  semantic={}",
            hex_encode(&fp.wire_hash),
            hex_encode(&fp.semantic_hash)
        );
        let monetary: Vec<&str> = l
            .fields
            .iter()
            .filter(|f| f.intent.is_monetary())
            .map(|f| f.name)
            .collect();
        let identity: Vec<&str> = l
            .fields
            .iter()
            .filter(|f| f.intent.is_identity())
            .map(|f| f.name)
            .collect();
        if !monetary.is_empty() {
            println!("      monetary fields: {}", monetary.join(", "));
        }
        if !identity.is_empty() {
            println!("      identity fields: {}", identity.join(", "));
        }
    }
    println!();

    // Instructions
    println!("  Instructions:");
    for ix in prog.instructions.iter() {
        let read_accounts: Vec<&str> = ix
            .accounts
            .iter()
            .filter(|account| !account.writable)
            .map(|account| account.name)
            .collect();
        let write_accounts: Vec<&str> = ix
            .accounts
            .iter()
            .filter(|account| account.writable)
            .map(|account| account.name)
            .collect();
        let signer_accounts: Vec<&str> = ix
            .accounts
            .iter()
            .filter(|account| account.signer)
            .map(|account| account.name)
            .collect();
        print!(
            "    [{}] {} | {} args | {} accounts",
            ix.tag,
            ix.name,
            ix.args.len(),
            ix.accounts.len()
        );
        if ix.receipt_expected {
            print!(" | receipt");
        }
        if !ix.policy_pack.is_empty() {
            print!(" | policy={}", ix.policy_pack);
        }
        println!();
        println!("      reads : {}", format_name_list(&read_accounts));
        println!("      writes: {}", format_name_list(&write_accounts));
        println!("      signers: {}", format_name_list(&signer_accounts));
    }
    println!();

    // Policies
    if !prog.policies.is_empty() {
        println!("  Policies:");
        for p in prog.policies.iter() {
            println!(
                "    {} | {} capabilities, {} requirements, {} invariants | receipt={}",
                p.name,
                p.capabilities.len(),
                p.requirements.len(),
                p.invariants.len(),
                p.receipt_profile
            );
        }
        println!();
    }

    // Events
    if !prog.events.is_empty() {
        println!("  Events:");
        for ev in prog.events.iter() {
            println!("    [{}] {} | {} fields", ev.tag, ev.name, ev.fields.len());
        }
        println!();
    }

    // Contexts
    if !prog.contexts.is_empty() {
        println!("  Contexts:");
        for ctx in prog.contexts.iter() {
            let signers = ctx.accounts.iter().filter(|a| a.signer).count();
            let writables = ctx.accounts.iter().filter(|a| a.writable).count();
            print!(
                "    {} | {} accounts ({} signer, {} writable)",
                ctx.name,
                ctx.accounts.len(),
                signers,
                writables
            );
            if !ctx.policies.is_empty() {
                print!(" | policies: {}", ctx.policies.join(", "));
            }
            if ctx.receipts_expected {
                print!(" | receipt");
            }
            println!();
        }
        println!();
    } else {
        println!("  Contexts:");
        println!("    No typed contexts embedded in this manifest.");
        println!("    Use `hopper compile --emit rust [<manifest>|--package <name>]` to inspect");
        println!("    runtime accessors Hopper derives from the instruction account lists.");
        println!();
    }

    // Assessment
    println!("  Assessment:");
    if policy_count > 0 && receipt_count > 0 && compat_count > 0 {
        println!("    This manifest declares layouts, policies, receipts, and");
        println!("    compatibility rules for schema-aware tooling.");
    } else {
        let mut missing = Vec::new();
        if policy_count == 0 {
            missing.push("named policies");
        }
        if receipt_count == 0 {
            missing.push("receipt tracking");
        }
        if compat_count == 0 {
            missing.push("compatibility rules");
        }
        println!(
            "    This manifest does not declare: {}.",
            missing.join(", ")
        );
        println!("    These are optional for simple programs but recommended for");
        println!("    protocols planning version evolution or operator dashboards.");
    }
}

fn cmd_explain_context(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain context <manifest> [--type <ContextName>]");
        eprintln!("  Show instruction contexts with account roles, mutability, signer status,");
        eprintln!(
            "  layout bindings, policy bindings, seeds, optionality, and generated accessors."
        );
        eprintln!();
        eprintln!("  Without --type, shows all contexts in the manifest.");
        eprintln!("  With --type, filters to a single named context.");
        process::exit(1);
    }

    let mut manifest_path: Option<&str> = None;
    let mut filter_type: Option<&str> = None;
    let mut i = 0;
    while i < args.len() {
        if args[i] == "--type" {
            if i + 1 < args.len() {
                filter_type = Some(&args[i + 1]);
                i += 2;
                continue;
            } else {
                eprintln!("--type requires a context name argument");
                process::exit(1);
            }
        }
        if manifest_path.is_none() {
            manifest_path = Some(&args[i]);
        }
        i += 1;
    }

    let manifest_path = match manifest_path {
        Some(p) => p,
        None => {
            eprintln!("Missing manifest path");
            process::exit(1);
        }
    };

    let manifest = load_program_manifest(manifest_path);

    if manifest.contexts.is_empty() {
        println!("=== Contexts: {} v{} ===", manifest.name, manifest.version);
        println!();
        println!("  No contexts defined in this manifest.");
        println!("  Use hopper_accounts! or #[derive(HopperAccounts)] to add typed contexts.");
        println!("  For instruction-level lowered accessors, run:");
        println!("    hopper compile --emit rust {}", manifest_path);
        return;
    }

    let contexts: Vec<_> = if let Some(name) = filter_type {
        manifest
            .contexts
            .iter()
            .filter(|c| c.name == name)
            .collect()
    } else {
        manifest.contexts.iter().collect()
    };

    if contexts.is_empty() {
        if let Some(name) = filter_type {
            eprintln!("No context named '{}' found in manifest.", name);
            eprintln!("Available contexts:");
            for c in manifest.contexts.iter() {
                eprintln!("  {}", c.name);
            }
            process::exit(1);
        }
    }

    println!("=== Contexts: {} v{} ===", manifest.name, manifest.version);
    println!();

    for ctx in &contexts {
        let read_accounts: Vec<&str> = ctx
            .accounts
            .iter()
            .filter(|account| !account.writable)
            .map(|account| account.name)
            .collect();
        let write_accounts: Vec<&str> = ctx
            .accounts
            .iter()
            .filter(|account| account.writable)
            .map(|account| account.name)
            .collect();
        let signer_accounts: Vec<&str> = ctx
            .accounts
            .iter()
            .filter(|account| account.signer)
            .map(|account| account.name)
            .collect();

        println!("  Context: {}", ctx.name);
        println!(
            "    Accounts: {} total, {} signer(s), {} writable",
            ctx.accounts.len(),
            ctx.accounts.iter().filter(|a| a.signer).count(),
            ctx.accounts.iter().filter(|a| a.writable).count(),
        );
        println!("    Reads: {}", format_name_list(&read_accounts));
        println!("    Writes: {}", format_name_list(&write_accounts));
        println!("    Signers: {}", format_name_list(&signer_accounts));
        println!();

        for acct in ctx.accounts.iter() {
            print!("    {:16} {:16}", acct.name, acct.kind);
            let mut flags = Vec::new();
            if acct.writable {
                flags.push("mut");
            }
            if acct.signer {
                flags.push("signer");
            }
            if acct.optional {
                flags.push("optional");
            }
            if !flags.is_empty() {
                print!("  [{}]", flags.join(", "));
            }
            println!();

            if !acct.layout_ref.is_empty() {
                println!("      layout = {}", acct.layout_ref);
            }
            if !acct.policy_ref.is_empty() {
                println!("      policy = {}", acct.policy_ref);
            }
            if !acct.seeds.is_empty() {
                println!("      seeds  = [{}]", acct.seeds.join(", "));
            }
            println!(
                "      access = {}",
                render_context_accessor_summary(ctx.name, acct)
            );
        }
        println!();

        println!("    Borrow path:");
        println!(
            "      Shared reads lower to Context::account(index) -> AccountView::load()/raw_ref()."
        );
        println!("      Writable access lowers to Context::account_mut(index) -> AccountView::load_mut()/raw_mut().");
        println!(
            "      Segment-safe mutations stay explicit in handlers via Context::segment_mut(...)."
        );
        println!("    Conflict model:");
        println!("      Static duplicate-name conflicts are not visible in the manifest.");
        println!("      Runtime duplicate-account and segment conflicts are enforced by Hopper's audit and borrow registry.");
        println!();

        if !ctx.policies.is_empty() {
            println!("    Policies: {}", ctx.policies.join(", "));
        }
        if ctx.receipts_expected {
            println!("    Receipts: expected");
        }
        if !ctx.mutation_classes.is_empty() {
            println!("    Mutations: {}", ctx.mutation_classes.join(", "));
        }
        if !ctx.policies.is_empty() || ctx.receipts_expected || !ctx.mutation_classes.is_empty() {
            println!();
        }
    }
}

fn cmd_inspect_layout(args: &[String]) {
    decode_layout_from_source(
        args,
        "hopper inspect layout <manifest> <hex-data> | --program-id <program-id> [--rpc <url>] <hex-data>",
        "Layout Inspect",
    );
}

fn render_program_rust_preview(
    prog: &ProgramManifest,
    filters: &RustEmitFilters,
) -> Result<String, String> {
    if let Some(layout_name) = filters.layout.as_deref() {
        if !prog.layouts.iter().any(|layout| layout.name == layout_name) {
            return Err(format!(
                "unknown layout '{}' (available: {})",
                layout_name,
                prog.layouts
                    .iter()
                    .map(|layout| layout.name)
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
    }

    if let Some(instruction_name) = filters.instruction.as_deref() {
        if !prog
            .instructions
            .iter()
            .any(|instruction| instruction.name == instruction_name)
        {
            return Err(format!(
                "unknown instruction '{}' (available: {})",
                instruction_name,
                prog.instructions
                    .iter()
                    .map(|instruction| instruction.name)
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
    }

    if let Some(context_name) = filters.context.as_deref() {
        if !prog
            .contexts
            .iter()
            .any(|context| context.name == context_name)
        {
            return Err(format!(
                "unknown context '{}' (available: {})",
                context_name,
                prog.contexts
                    .iter()
                    .map(|context| context.name)
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
    }

    let selected_instructions: Vec<&InstructionDescriptor> = prog
        .instructions
        .iter()
        .filter(|instruction| match filters.instruction.as_deref() {
            Some(name) => instruction.name == name,
            None => true,
        })
        .collect();

    let selected_contexts: Vec<&ContextDescriptor> = prog
        .contexts
        .iter()
        .filter(|context| match filters.context.as_deref() {
            Some(name) => context.name == name,
            None => true,
        })
        .collect();

    let referenced_layouts: Vec<&str> = if filters.layout.is_none()
        && (filters.instruction.is_some() || filters.context.is_some())
    {
        let mut names = Vec::new();
        for instruction in selected_instructions.iter() {
            for account in instruction.accounts.iter() {
                if !account.layout_ref.is_empty() && !names.contains(&account.layout_ref) {
                    names.push(account.layout_ref);
                }
            }
        }
        for context in selected_contexts.iter() {
            for account in context.accounts.iter() {
                if !account.layout_ref.is_empty() && !names.contains(&account.layout_ref) {
                    names.push(account.layout_ref);
                }
            }
        }
        names
    } else {
        Vec::new()
    };

    let selected_layouts: Vec<&LayoutManifest> = prog
        .layouts
        .iter()
        .filter(|layout| {
            if let Some(name) = filters.layout.as_deref() {
                return layout.name == name;
            }
            if referenced_layouts.is_empty() {
                return true;
            }
            referenced_layouts.contains(&layout.name)
        })
        .collect();

    let mut out = String::new();
    out.push_str("// ───────────────────────────────────────────────────────────────\n");
    out.push_str("//  Hopper lowered Rust preview\n");
    out.push_str("// ───────────────────────────────────────────────────────────────\n");
    out.push_str("// Generated from ProgramManifest metadata. NOT your source file.\n");
    out.push_str("// This is what Hopper's one access model lowers to: indexed accounts,\n");
    out.push_str("// const segment offsets, and typed projections. No hidden runtime,\n");
    out.push_str("// no reflection, no string lookups in the hot path.\n");
    out.push_str("//\n");
    out.push_str("// Access model (all three paths share the same pointer arithmetic):\n");
    out.push_str("//   Tier A  ctx.load::<T>(idx)?            // validate header + project\n");
    out.push_str("//   Tier B  ctx.segment_mut::<T>(idx, off) // fine-grained segment borrow\n");
    out.push_str("//   Tier C  unsafe ctx.raw_mut::<T>(idx)?  // caller owns all validation\n");
    out.push_str("// ───────────────────────────────────────────────────────────────\n\n");
    out.push_str("use hopper::prelude::*;\n");
    out.push_str("use hopper::__runtime::{Ref, RefMut};\n\n");

    let module_name = sanitize_ident(&format!("{}_generated", &snake_case(prog.name)));
    push_line(&mut out, 0, &format!("pub mod {} {{", module_name));
    push_line(
        &mut out,
        4,
        &format!(
            "pub const PROGRAM_NAME: &str = \"{}\";",
            escape_rust_string(prog.name)
        ),
    );
    push_line(
        &mut out,
        4,
        &format!(
            "pub const PROGRAM_VERSION: &str = \"{}\";",
            escape_rust_string(prog.version)
        ),
    );
    push_line(
        &mut out,
        4,
        &format!(
            "pub const PROGRAM_DESCRIPTION: &str = \"{}\";",
            escape_rust_string(prog.description)
        ),
    );
    push_line(&mut out, 4, "pub const HEADER_LEN: usize = 16;");
    out.push('\n');

    if !selected_layouts.is_empty() {
        push_line(&mut out, 4, "pub mod layouts {");
        for layout in selected_layouts.iter() {
            render_layout_rust_preview(&mut out, layout);
        }
        push_line(&mut out, 4, "}");
        out.push('\n');
    }

    if !selected_instructions.is_empty() {
        push_line(&mut out, 4, "pub mod instructions {");
        for instruction in selected_instructions.iter() {
            render_instruction_rust_preview(&mut out, instruction);
        }
        push_line(&mut out, 4, "}");
        out.push('\n');
    }

    if !selected_contexts.is_empty() {
        push_line(&mut out, 4, "pub mod contexts {");
        for context in selected_contexts.iter() {
            render_context_rust_preview(&mut out, context);
        }
        push_line(&mut out, 4, "}");
        out.push('\n');
    }

    if selected_instructions.is_empty() && selected_contexts.is_empty() {
        push_line(
            &mut out,
            4,
            "// No instruction or context metadata was selected.",
        );
        push_line(&mut out, 4, "// Add --instruction/--context filters only when those descriptors exist in the manifest.");
        out.push('\n');
    }

    push_line(&mut out, 0, "}");
    Ok(out)
}

fn render_layout_rust_preview(out: &mut String, layout: &LayoutManifest) {
    let module_name = sanitize_ident(&snake_case(layout.name));
    push_line(out, 8, &format!("pub mod {} {{", module_name));
    push_line(
        out,
        12,
        &format!(
            "pub const NAME: &str = \"{}\";",
            escape_rust_string(layout.name)
        ),
    );
    push_line(out, 12, &format!("pub const DISC: u8 = {};", layout.disc));
    push_line(
        out,
        12,
        &format!("pub const VERSION: u8 = {};", layout.version),
    );
    push_line(
        out,
        12,
        &format!("pub const TOTAL_SIZE: usize = {};", layout.total_size),
    );
    push_line(
        out,
        12,
        &format!(
            "pub const LAYOUT_ID: [u8; 8] = {};",
            render_u8_array(&layout.layout_id)
        ),
    );
    push_line(out, 12, "pub const TYPE_OFFSET: usize = HEADER_LEN;");
    push_line(out, 12, "");
    for field in layout.fields.iter() {
        let field_name = upper_snake_case(field.name);
        let field_end = field.offset as usize + field.size as usize;
        push_line(
            out,
            12,
            &format!(
                "// {}: {} @ bytes {}..{}",
                field.name, field.canonical_type, field.offset, field_end
            ),
        );
        push_line(
            out,
            12,
            &format!(
                "// pointer path: account.try_borrow()? -> base_ptr.add({}) as *const {}",
                field.offset, field.canonical_type
            ),
        );
        push_line(
            out,
            12,
            &format!("pub const {}_OFFSET: usize = {};", field_name, field.offset),
        );
        push_line(
            out,
            12,
            &format!("pub const {}_SIZE: usize = {};", field_name, field.size),
        );
        push_line(out, 12, "");
    }
    push_line(out, 8, "}");
    out.push('\n');
}

fn render_instruction_rust_preview(out: &mut String, instruction: &InstructionDescriptor) {
    let module_name = sanitize_ident(&snake_case(instruction.name));
    let reads: Vec<&str> = instruction
        .accounts
        .iter()
        .filter(|account| !account.writable)
        .map(|account| account.name)
        .collect();
    let writes: Vec<&str> = instruction
        .accounts
        .iter()
        .filter(|account| account.writable)
        .map(|account| account.name)
        .collect();
    let signers: Vec<&str> = instruction
        .accounts
        .iter()
        .filter(|account| account.signer)
        .map(|account| account.name)
        .collect();

    push_line(out, 8, &format!("pub mod {} {{", module_name));
    push_line(
        out,
        12,
        &format!(
            "pub const NAME: &str = \"{}\";",
            escape_rust_string(instruction.name)
        ),
    );
    push_line(
        out,
        12,
        &format!("pub const TAG: u8 = {};", instruction.tag),
    );
    push_line(
        out,
        12,
        &format!("pub const READS: &[&str] = &{};", render_str_slice(&reads)),
    );
    push_line(
        out,
        12,
        &format!(
            "pub const WRITES: &[&str] = &{};",
            render_str_slice(&writes)
        ),
    );
    push_line(
        out,
        12,
        &format!(
            "pub const SIGNERS: &[&str] = &{};",
            render_str_slice(&signers)
        ),
    );
    if !instruction.policy_pack.is_empty() {
        push_line(
            out,
            12,
            &format!(
                "pub const POLICY_PACK: &str = \"{}\";",
                escape_rust_string(instruction.policy_pack)
            ),
        );
    }
    push_line(
        out,
        12,
        &format!(
            "pub const RECEIPT_EXPECTED: bool = {};",
            instruction.receipt_expected
        ),
    );
    push_line(out, 12, "");

    if !instruction.args.is_empty() {
        push_line(out, 12, "// Instruction arguments:");
        for argument in instruction.args.iter() {
            push_line(
                out,
                12,
                &format!(
                    "//   {}: {} ({} bytes)",
                    argument.name, argument.canonical_type, argument.size
                ),
            );
        }
        push_line(out, 12, "");
    }

    render_account_accessor_block(
        out,
        12,
        &format!("{}Accounts", pascal_case(instruction.name)),
        instruction
            .accounts
            .iter()
            .map(|account| DerivedAccountDescriptor {
                name: account.name,
                kind: "AccountView",
                writable: account.writable,
                signer: account.signer,
                layout_ref: account.layout_ref,
                policy_ref: "",
                seeds: &[],
                optional: false,
            })
            .collect::<Vec<_>>()
            .as_slice(),
        Some("Generated from InstructionDescriptor account order."),
    );

    push_line(out, 8, "}");
    out.push('\n');
}

fn render_context_rust_preview(out: &mut String, context: &ContextDescriptor) {
    let module_name = sanitize_ident(&snake_case(context.name));
    push_line(out, 8, &format!("pub mod {} {{", module_name));
    push_line(
        out,
        12,
        &format!(
            "pub const NAME: &str = \"{}\";",
            escape_rust_string(context.name)
        ),
    );
    push_line(
        out,
        12,
        &format!(
            "pub const POLICIES: &[&str] = &{};",
            render_str_slice(context.policies)
        ),
    );
    push_line(
        out,
        12,
        &format!(
            "pub const MUTATION_CLASSES: &[&str] = &{};",
            render_str_slice(context.mutation_classes)
        ),
    );
    push_line(
        out,
        12,
        &format!(
            "pub const RECEIPTS_EXPECTED: bool = {};",
            context.receipts_expected
        ),
    );
    push_line(out, 12, "");

    let accounts: Vec<DerivedAccountDescriptor<'_>> = context
        .accounts
        .iter()
        .map(|account| DerivedAccountDescriptor {
            name: account.name,
            kind: account.kind,
            writable: account.writable,
            signer: account.signer,
            layout_ref: account.layout_ref,
            policy_ref: account.policy_ref,
            seeds: account.seeds,
            optional: account.optional,
        })
        .collect();
    render_account_accessor_block(
        out,
        12,
        &format!("{}Context", pascal_case(context.name)),
        accounts.as_slice(),
        Some("Generated from ContextDescriptor account order."),
    );

    push_line(out, 8, "}");
    out.push('\n');
}

#[derive(Clone, Copy)]
struct DerivedAccountDescriptor<'a> {
    name: &'a str,
    kind: &'a str,
    writable: bool,
    signer: bool,
    layout_ref: &'a str,
    policy_ref: &'a str,
    seeds: &'a [&'a str],
    optional: bool,
}

fn render_account_accessor_block(
    out: &mut String,
    indent: usize,
    struct_name: &str,
    accounts: &[DerivedAccountDescriptor<'_>],
    header_note: Option<&str>,
) {
    if let Some(note) = header_note {
        push_line(out, indent, &format!("// {}", note));
    }
    push_line(
        out,
        indent,
        &format!("pub struct {};", sanitize_ident(struct_name)),
    );
    push_line(
        out,
        indent,
        &format!("impl {} {{", sanitize_ident(struct_name)),
    );
    push_line(
        out,
        indent + 4,
        &format!("pub const ACCOUNT_LEN: usize = {};", accounts.len()),
    );
    push_line(out, indent + 4, "");

    for (index, account) in accounts.iter().enumerate() {
        let const_name = format!("{}_INDEX", upper_snake_case(account.name));
        push_line(
            out,
            indent + 4,
            &format!("pub const {}: usize = {};", const_name, index),
        );
    }
    push_line(out, indent + 4, "");

    for account in accounts.iter() {
        let account_fn = sanitize_ident(&format!("{}_account", snake_case(account.name)));
        let index_const = format!("{}_INDEX", upper_snake_case(account.name));
        let account_getter = if account.writable {
            "account_mut"
        } else {
            "account"
        };

        push_line(
            out,
            indent + 4,
            &format!(
                "// {}: {}{}{}{}",
                account.name,
                account.kind,
                if account.writable { " [mut]" } else { "" },
                if account.signer { " [signer]" } else { "" },
                if account.optional { " [optional]" } else { "" },
            ),
        );
        if !account.layout_ref.is_empty() {
            push_line(
                out,
                indent + 4,
                &format!("// layout = {}", account.layout_ref),
            );
        }
        if !account.policy_ref.is_empty() {
            push_line(
                out,
                indent + 4,
                &format!("// policy = {}", account.policy_ref),
            );
        }
        if !account.seeds.is_empty() {
            push_line(
                out,
                indent + 4,
                &format!("// seeds = [{}]", account.seeds.join(", ")),
            );
        }
        push_line(
            out,
            indent + 4,
            &format!(
                "pub fn {}(ctx: &Context<'_>) -> Result<&AccountView, ProgramError> {{",
                account_fn
            ),
        );
        push_line(
            out,
            indent + 8,
            &format!("ctx.{}(Self::{})", account_getter, index_const),
        );
        push_line(out, indent + 4, "}");

        if !account.layout_ref.is_empty() {
            let load_fn = sanitize_ident(&format!("{}_load", snake_case(account.name)));
            let raw_ref_fn = sanitize_ident(&format!("{}_raw_ref", snake_case(account.name)));
            push_line(
                out,
                indent + 4,
                &format!(
                    "pub fn {}(ctx: &Context<'_>) -> Result<Ref<'_, {}>, ProgramError> {{",
                    load_fn, account.layout_ref,
                ),
            );
            push_line(
                out,
                indent + 8,
                &format!(
                    "Self::{}(ctx)?.load::<{}>()",
                    account_fn, account.layout_ref
                ),
            );
            push_line(out, indent + 4, "}");
            push_line(
                out,
                indent + 4,
                &format!(
                    "pub unsafe fn {}(ctx: &Context<'_>) -> Result<Ref<'_, {}>, ProgramError> {{",
                    raw_ref_fn, account.layout_ref,
                ),
            );
            push_line(
                out,
                indent + 8,
                &format!(
                    "unsafe {{ Self::{}(ctx)?.raw_ref::<{}>() }}",
                    account_fn, account.layout_ref
                ),
            );
            push_line(out, indent + 4, "}");

            if account.writable {
                let load_mut_fn = sanitize_ident(&format!("{}_load_mut", snake_case(account.name)));
                let raw_mut_fn = sanitize_ident(&format!("{}_raw_mut", snake_case(account.name)));
                push_line(
                    out,
                    indent + 4,
                    "// Whole-account mutable path. Use Context::segment_mut(...) when you only need a narrower region.",
                );
                push_line(
                    out,
                    indent + 4,
                    &format!(
                        "pub fn {}(ctx: &Context<'_>) -> Result<RefMut<'_, {}>, ProgramError> {{",
                        load_mut_fn, account.layout_ref,
                    ),
                );
                push_line(
                    out,
                    indent + 8,
                    &format!(
                        "Self::{}(ctx)?.load_mut::<{}>()",
                        account_fn, account.layout_ref
                    ),
                );
                push_line(out, indent + 4, "}");
                push_line(
                    out,
                    indent + 4,
                    &format!(
                        "pub unsafe fn {}(ctx: &Context<'_>) -> Result<RefMut<'_, {}>, ProgramError> {{",
                        raw_mut_fn,
                        account.layout_ref,
                    ),
                );
                push_line(
                    out,
                    indent + 8,
                    &format!(
                        "unsafe {{ Self::{}(ctx)?.raw_mut::<{}>() }}",
                        account_fn, account.layout_ref
                    ),
                );
                push_line(out, indent + 4, "}");
            }
        }

        push_line(out, indent + 4, "");
    }

    push_line(out, indent, "}");
}

fn render_context_accessor_summary(
    context_name: &str,
    account: &ContextAccountDescriptor,
) -> String {
    let mut accessors = vec![format!("{}_account()", snake_case(account.name))];
    if !account.layout_ref.is_empty() {
        accessors.push(format!("{}_load()", snake_case(account.name)));
        accessors.push(format!("{}_raw_ref()", snake_case(account.name)));
        if account.writable {
            accessors.push(format!("{}_load_mut()", snake_case(account.name)));
            accessors.push(format!("{}_raw_mut()", snake_case(account.name)));
        }
    }

    format!("{} on {}", accessors.join(", "), context_name,)
}

fn format_name_list(names: &[&str]) -> String {
    if names.is_empty() {
        "(none)".to_string()
    } else {
        names.join(", ")
    }
}

fn push_line(out: &mut String, indent: usize, line: &str) {
    for _ in 0..indent {
        out.push(' ');
    }
    out.push_str(line);
    out.push('\n');
}

fn render_u8_array(bytes: &[u8]) -> String {
    let rendered = bytes
        .iter()
        .map(|byte| byte.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{rendered}]")
}

fn render_str_slice(values: &[&str]) -> String {
    if values.is_empty() {
        return "[]".to_string();
    }

    let rendered = values
        .iter()
        .map(|value| format!("\"{}\"", escape_rust_string(value)))
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{rendered}]")
}

fn escape_rust_string(value: &str) -> String {
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
}

fn sanitize_ident(value: &str) -> String {
    let mut ident = String::new();
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' {
            ident.push(ch);
        } else {
            ident.push('_');
        }
    }

    if ident.is_empty() {
        ident.push('_');
    }
    if ident
        .chars()
        .next()
        .map(|ch| ch.is_ascii_digit())
        .unwrap_or(false)
    {
        ident.insert(0, '_');
    }
    ident
}

fn snake_case(value: &str) -> String {
    let mut out = String::new();
    let mut prev_was_lower_or_digit = false;
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            if ch.is_ascii_uppercase() {
                if prev_was_lower_or_digit && !out.ends_with('_') {
                    out.push('_');
                }
                out.push(ch.to_ascii_lowercase());
                prev_was_lower_or_digit = false;
            } else {
                out.push(ch.to_ascii_lowercase());
                prev_was_lower_or_digit = ch.is_ascii_lowercase() || ch.is_ascii_digit();
            }
        } else if !out.ends_with('_') {
            out.push('_');
            prev_was_lower_or_digit = false;
        }
    }

    sanitize_ident(out.trim_matches('_'))
}

fn upper_snake_case(value: &str) -> String {
    snake_case(value).to_ascii_uppercase()
}

fn pascal_case(value: &str) -> String {
    let mut out = String::new();
    let mut capitalize = true;
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            if capitalize {
                out.push(ch.to_ascii_uppercase());
                capitalize = false;
            } else {
                out.push(ch);
            }
        } else {
            capitalize = true;
        }
    }

    sanitize_ident(&out)
}

fn print_compile_usage() {
    eprintln!("Usage: hopper compile --emit <target> [<manifest> | --package <name> | --program-id <id>] [--rpc <url>] [--layout <L>] [--instruction <I>] [--context <C>] [--out <path>] [--force] [--lint] [--lint-fail-on-warn]");
    eprintln!();
    eprintln!("Supported targets:");
    eprintln!("  rust    Lowered Rust preview (accessors, offsets, pointer path)");
    eprintln!("  ts      TypeScript client SDK");
    eprintln!("  kt      Kotlin client SDK");
    eprintln!("  py      Python client SDK");
    eprintln!("  go      Go client SDK");
    eprintln!("  c       C client header");
    eprintln!("  rust-client  Off-chain Rust client SDK");
    eprintln!("  idl     Hopper public IDL JSON");
    eprintln!("  codama  Codama-flavored JSON");
    eprintln!("  schema  Normalize a supplied or fetched Hopper manifest as JSON");
    eprintln!("  manifest  Generate hopper.manifest.json from package source (--package required)");
    eprintln!();
    eprintln!("Inline lint:");
    eprintln!("  --lint                  Run `hopper lint` against the project after emitting");
    eprintln!("                          the artifact. Errors fail the command; warnings pass.");
    eprintln!("  --lint-fail-on-warn     Treat lint warnings as errors (implies --lint)");
    eprintln!();
    eprintln!("For targets other than manifest, omitting a source infers an existing");
    eprintln!(
        "hopper.manifest.json from the current package. The manifest target requires --package."
    );
    eprintln!();
    eprintln!("Examples:");
    eprintln!("  hopper compile --emit rust");
    eprintln!(
        "  hopper compile --emit ts --package hopper-token-2022-vault --out vault.ts --force"
    );
    eprintln!("  hopper compile --emit idl @hopper.manifest.json --out idl.json");
    eprintln!("  hopper compile --emit codama --program-id <program-id> --rpc <url>");
    eprintln!("  hopper compile --emit kt --package vault");
    eprintln!("  hopper compile --emit py --package vault --out vault_client.py --force");
    eprintln!("  hopper compile --emit go --package vault --out vault_client.go --force");
    eprintln!("  hopper compile --emit c --package vault --out vault_client.h --force");
    eprintln!("  hopper compile --emit schema @hopper.manifest.json --out normalized.json --force");
    eprintln!("  hopper compile --emit manifest --package vault");
    eprintln!("  hopper compile --emit rust --package vault --lint    # one-shot build + lint");
}

fn print_usage() {
    println!("hopper-cli: Hopper account inspection, schema tooling, and program management");
    println!();
    println!("COMMAND FAMILIES:");
    println!();
    println!("  Compile:");
    println!("    hopper compile --emit <rust|ts|kt|py|go|c|rust-client|idl|codama|schema|manifest> [<manifest>|--package <name>|--program-id ...]");
    println!("                                           Emit lowered Rust, client SDKs, IDL JSON, Codama, or manifest");
    println!();
    println!("  Verify (manifest and release-interface integrity):");
    println!("    hopper verify [<manifest>] [<.so>]     Check manifest integrity and report layout-anchor diagnostics");
    println!("    hopper verify --release <manifest> <.so>  Require the exact versioned interface commitment in the ELF");
    println!(
        "    hopper verify --package <name>         Infer manifest + .so from a workspace package"
    );
    println!("    hopper publish-check --package <name>  Run interface binding, docs, feature, client, and fuzz gates");
    println!(
        "    hopper audit-check [--strict] [--json] Verify audit evidence, freshness, and blockers"
    );
    println!("    hopper publish-idl --manifest <path> --program-id <pubkey> [--dry-run]");
    println!("                                           Publish Solana IDL v0.1.0 through Program Metadata (zero Node deps)");
    println!("    hopper publish-security --file security.json --program-id <pubkey> [--init] [--read] [--dry-run]");
    println!("                                           Publish, scaffold, or read back the security.txt record (seed \"security\")");
    println!(
        "    hopper publish-manifest --manifest <path> --program-id <pubkey> [--read] [--dry-run]"
    );
    println!("                                           Publish or read back the full Hopper manifest (seed \"hopper-manifest\")");
    println!("    hopper solana-check [--all]            Check SBF crate shape and Hopper entrypoint invariants");
    println!("    hopper contention <manifest>           Declared write-lock/signature footprint per instruction");
    println!("                                           (--max-block-cost <CU> gates it in CI)");
    println!("    hopper fuzz generate --program <manifest> [--out <plan.json>] [--corpus <dir>]");
    println!("                                           Derive seeded cases from every declared contract");
    println!("    hopper fuzz check --program <manifest> [--plan <plan.json>]");
    println!(
        "                                           Fail CI when the committed fuzz plan drifts"
    );
    println!(
        "    hopper fuzz run --program <manifest> --adapter <executable> [--plan <plan.json>]"
    );
    println!(
        "                                           Execute cases and required invariant hooks"
    );
    println!();
    println!("  Schema:");
    println!("    hopper schema export               Schema format reference");
    println!("    hopper schema validate <manifest>   Validate a program manifest");
    println!("    hopper schema diff <old> <new>      Field-level diff");
    println!();
    println!("  Inspect:");
    println!("    hopper inspect <hex-data>           Decode account header");
    println!("    hopper inspect layout <manifest|--program-id ...> <hex>  Decode fields using a manifest");
    println!("    hopper inspect segments <hex-data>  Decode segment map");
    println!("    hopper inspect receipt <hex-data>   Decode a state receipt");
    println!();
    println!("  Explain:");
    println!("    hopper explain <hex-data>           Human-readable headered-account explanation");
    println!("    hopper explain account <hex-data>   Explicit headered-account explanation");
    println!("    hopper explain receipt <hex-data>   Explain a receipt in plain English");
    println!("    hopper explain compat <old> <new>   Explain compatibility report");
    println!("    hopper explain policy <pack-name>   Explain a named policy pack");
    println!("    hopper explain layout <manifest>    Explain layout fields, intents, fingerprint");
    println!("    hopper explain program <manifest>   Explain entire program pipeline");
    println!("    hopper explain <tx-signature>       Decode a confirmed tx against local or application-provisioned legacy manifests");
    println!("    hopper explain <program-id>         Fetch an application-provisioned legacy manifest PDA");
    println!("    hopper explain instruction <manifest> <tag|name>  Explain instruction accounts and policy");
    println!(
        "    hopper explain context <manifest>   Explain instruction contexts and account roles"
    );
    println!();
    println!("  Compatibility:");
    println!("    hopper compat <v1-json> <v2-json>   Compatibility report");
    println!("    hopper plan <v1-json> <v2-json>     Migration plan with steps");
    println!();
    println!("  Receipts:");
    println!("    hopper receipt <hex-data>           Decode and display receipt");
    println!();
    println!("  Manager:");
    println!("    hopper manager summary <manifest|--program-id ...>     Program overview");
    println!(
        "    hopper manager identify <manifest|--program-id ...> <hex>  Identify account type"
    );
    println!("    hopper manager decode <manifest|--program-id ...> <hex>    Decode all fields");
    println!("    hopper manager instruction <manifest|--program-id ...> <tag|name>  Instruction details");
    println!("    hopper manager layouts <manifest|--program-id ...>     List all layouts");
    println!("    hopper manager policies <manifest|--program-id ...>    List policy packs");
    println!("    hopper manager events <manifest|--program-id ...>      List events with fields");
    println!("    hopper manager fingerprints <manifest|--program-id ...>  Show all fingerprints");
    println!("    hopper manager compat <manifest|--program-id ...> <hex-old> <hex-new>  Compare two accounts");
    println!("    hopper manager receipt <hex-64-or-72-bytes>             Decode a state receipt");
    println!("    hopper manager explain <manifest|--program-id ...>     Aggregated summary");
    println!("    hopper manager diff <manifest|--program-id ...> <hex-old> <hex-new>  Semantic field diff");
    println!("    hopper manager simulate <manifest|--program-id ...> <instruction>  Preview requirements");
    println!();
    println!("  Fetch (application-provisioned legacy PDA; no generic Hopper publisher):");
    println!("    hopper fetch <program-id> [--rpc <url>]          Fetch legacy manifest PDA");
    println!("    hopper fetch <program-id> --json [--rpc <url>]   Fetch legacy manifest JSON");
    println!(
        "    hopper manager fetch <program-id> [--rpc <url>]  Fetch legacy PDA + show summary"
    );
    println!();
    println!("  Lifecycle:");
    println!("    hopper init [path]                 Create a Hopper project (wizard if no path)");
    println!("    hopper add [-i|-s|-e <name>]       Scaffold an instruction, state, or error into the current project");
    println!("    hopper build [--host|--sbf]        Build the current project (default: SBF)");
    println!("    hopper test                        Run the current project's host-side tests");
    println!("    hopper deploy [--dry-run] [--cluster <c>] [--keypair <p>] [--no-build]  Quote or deploy the current SBF program");
    println!(
        "    hopper upgrade --program-id <id> [--cluster <c>]  Upgrade a deployed program in place"
    );
    println!("    hopper close --program-id <id> [--cluster <c>]    Close a program/buffer and reclaim rent");
    println!("    hopper migrate --program-id <id> [--cluster <c>]  Upgrade a program carrying a layout migration");
    println!("    hopper dump [--no-build]           Disassemble the current SBF artifact");
    println!("    hopper clean [-a|--all]            Remove target/{{deploy,idl,client,profile,hopper}} (preserves keypairs)");
    println!();
    println!("  Profiling:");
    println!("    hopper profile bench               Run the primitive benchmark lab");
    println!();
    println!("  Interactive:");
    println!("    hopper interactive <manifest|--program-id ...>  Launch interactive explorer");
    println!("    hopper ui <manifest|--program-id ...>           Alias for interactive");
    println!("    hopper manager interactive <manifest|--program-id ...>  Interactive from manager context");
    println!();
    println!("  Client:");
    println!("    hopper client gen --ts <manifest>  Generate TypeScript client SDK");
    println!("    hopper client gen --kt <manifest>  Generate Kotlin client SDK");
    println!("    hopper client gen --py <manifest>  Generate Python client SDK");
    println!("    hopper client gen --go <manifest>  Generate Go client SDK");
    println!("    hopper client gen --c <manifest>   Generate C client header");
    println!("    hopper actions gen --program <manifest> --out api/actions  Generate Solana Actions route scaffolds");
    println!("    hopper mobile gen --program <manifest> --target kotlin|react-native  Generate mobile binding stubs");
    println!(
        "    hopper test-gen security --program <manifest>  Generate security test matrix scaffold"
    );
    println!();
    println!("Hex data: hex-encoded account bytes (no 0x prefix).");
    println!("Manifest arguments accept inline JSON or @path/to/file.json.");
    println!("Program IDs: base58-encoded Solana public keys.");
    println!("RPC URL: set via --rpc flag, SOLANA_RPC_URL env, or defaults to mainnet.");
}

// -- Hex decode (inline, no external dependency) --

fn hex_decode(s: &str) -> Result<Vec<u8>, String> {
    let s = s.trim();
    if !s.len().is_multiple_of(2) {
        return Err("Hex string must have even length".to_string());
    }
    let mut bytes = Vec::with_capacity(s.len() / 2);
    let chars: Vec<u8> = s.bytes().collect();
    for pair in chars.chunks(2) {
        let hi =
            hex_nibble(pair[0]).ok_or_else(|| format!("Invalid hex char: {}", pair[0] as char))?;
        let lo =
            hex_nibble(pair[1]).ok_or_else(|| format!("Invalid hex char: {}", pair[1] as char))?;
        bytes.push((hi << 4) | lo);
    }
    Ok(bytes)
}

fn hex_nibble(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        s.push(HEX[(b >> 4) as usize] as char);
        s.push(HEX[(b & 0xf) as usize] as char);
    }
    s
}

// -- Minimal JSON manifest parser (no serde dependency) --

/// Parsed manifest from JSON input (simplified).
struct ParsedManifest {
    name: String,
    disc: u8,
    version: u8,
    layout_id: [u8; 8],
    total_size: usize,
    has_dynamic_tail: bool,
    fields: Vec<ParsedField>,
}

struct ParsedField {
    name: String,
    canonical_type: String,
    size: u16,
    offset: u16,
}

fn parse_manifest_json(json: &str) -> Result<ParsedManifest, String> {
    // Minimal JSON parser for manifest objects.
    // Expects: {"name":"...","disc":N,"version":N,"layout_id":[...],"total_size":N,
    //           "fields":[{"name":"...","type":"...","size":N,"offset":N},...]}
    let json = json.trim();
    if !json.starts_with('{') || !json.ends_with('}') {
        return Err("Expected JSON object".to_string());
    }

    let name = extract_string(json, "name")?;
    let disc = extract_number(json, "disc")? as u8;
    let version = extract_number(json, "version")? as u8;
    // Two manifest dialects exist in the wild: the hand-written files
    // (snake_case, `layout_id` as a byte array) and `ManifestJson`'s
    // rendered output (camelCase, `layoutId` as a hex string), the
    // shape `hopper compile --emit manifest` now generates. Accept both.
    let total_size =
        extract_number(json, "total_size").or_else(|_| extract_number(json, "totalSize"))? as usize;
    let has_dynamic_tail = if find_after_key(json, "has_dynamic_tail").is_some() {
        extract_bool(json, "has_dynamic_tail")?
    } else if find_after_key(json, "hasDynamicTail").is_some() {
        extract_bool(json, "hasDynamicTail")?
    } else {
        false
    };
    let mut lid = [0u8; 8];
    match extract_array_u8(json, "layout_id") {
        Ok(layout_id) => {
            if layout_id.len() != 8 {
                return Err("layout_id must be exactly 8 bytes".to_string());
            }
            lid.copy_from_slice(&layout_id);
        }
        Err(_) => {
            let hex = extract_string(json, "layoutId")
                .map_err(|_| "Missing key: layout_id (or layoutId)".to_string())?;
            if hex.len() != 16 {
                return Err("layoutId hex string must be 16 chars (8 bytes)".to_string());
            }
            for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
                let s = std::str::from_utf8(chunk).map_err(|_| "layoutId not UTF-8")?;
                lid[i] =
                    u8::from_str_radix(s, 16).map_err(|e| format!("layoutId hex parse: {e}"))?;
            }
        }
    }

    let fields = extract_fields(json)?;

    Ok(ParsedManifest {
        name,
        disc,
        version,
        layout_id: lid,
        total_size,
        has_dynamic_tail,
        fields,
    })
}

/// Position the parser at the VALUE following a genuine `"key":` token.
///
/// The manifest parser is substring-based, so a naive `find("\"key\"")`
/// also matches a string *value* that merely equals `key`; e.g. an
/// account legitimately named `"offset"` inside
/// `{ "account": "offset", "offset": 16, ... }` would shadow the real
/// `offset` key and make the whole load fail. This scans every `"key"`
/// occurrence and returns the trimmed slice after the first one actually
/// followed by `:`, so a value can never shadow a key. `None` when no
/// genuine key occurrence exists.
fn find_after_key<'a>(json: &'a str, key: &str) -> Option<&'a str> {
    let pattern = format!("\"{}\"", key);
    let mut from = 0;
    while let Some(rel) = json[from..].find(&pattern) {
        let after_pat = from + rel + pattern.len();
        let rest = json[after_pat..].trim_start();
        if let Some(value) = rest.strip_prefix(':') {
            return Some(value.trim_start());
        }
        from = after_pat;
    }
    None
}

fn extract_string(json: &str, key: &str) -> Result<String, String> {
    let after = find_after_key(json, key).ok_or_else(|| format!("Missing key: {}", key))?;
    if !after.starts_with('"') {
        return Err(format!("Expected string value for {}", key));
    }
    let after = &after[1..]; // skip opening quote
    let end = after.find('"').ok_or("Unterminated string")?;
    Ok(after[..end].to_string())
}

fn extract_number(json: &str, key: &str) -> Result<u64, String> {
    let after = find_after_key(json, key).ok_or_else(|| format!("Missing key: {}", key))?;
    let end = after
        .find(|c: char| !c.is_ascii_digit())
        .unwrap_or(after.len());
    after[..end]
        .parse()
        .map_err(|e| format!("Invalid number for {}: {}", key, e))
}

fn extract_bool(json: &str, key: &str) -> Result<bool, String> {
    let after = find_after_key(json, key).ok_or_else(|| format!("Missing key: {}", key))?;
    if after.starts_with("true") {
        Ok(true)
    } else if after.starts_with("false") {
        Ok(false)
    } else {
        Err(format!("Invalid boolean for {}", key))
    }
}

fn extract_array_u8(json: &str, key: &str) -> Result<Vec<u8>, String> {
    let after = find_after_key(json, key).ok_or_else(|| format!("Missing key: {}", key))?;
    let start = after.find('[').ok_or("Expected [")?;
    let end = after.find(']').ok_or("Expected ]")?;
    let inner = &after[start + 1..end];
    inner
        .split(',')
        .map(|s| {
            s.trim()
                .parse::<u8>()
                .map_err(|e| format!("Invalid byte: {}", e))
        })
        .collect()
}

fn extract_fields(json: &str) -> Result<Vec<ParsedField>, String> {
    let key = "\"fields\"";
    let pos = json.find(key).ok_or("Missing fields array")?;
    let after = &json[pos + key.len()..];
    let after = after.trim_start().strip_prefix(':').ok_or("Expected :")?;
    let after = after.trim_start();

    // Find the outer array brackets
    let start = after.find('[').ok_or("Expected [")?;
    let after = &after[start + 1..];

    // Parse individual field objects
    let mut fields = Vec::new();
    let mut remaining = after;

    loop {
        remaining = remaining.trim_start();
        if remaining.starts_with(']') {
            break;
        }
        if remaining.starts_with(',') {
            remaining = &remaining[1..];
            continue;
        }
        if !remaining.starts_with('{') {
            break;
        }

        let end = remaining.find('}').ok_or("Unterminated field object")?;
        let obj = &remaining[..=end];

        let name = extract_string(obj, "name")?;
        let canonical_type = extract_string(obj, "type")?;
        let size = extract_number(obj, "size")? as u16;
        let offset = extract_number(obj, "offset")? as u16;

        fields.push(ParsedField {
            name,
            canonical_type,
            size,
            offset,
        });

        remaining = &remaining[end + 1..];
    }

    Ok(fields)
}

// -- Convert ParsedManifest to hopper_schema types --

// We need to hold the field descriptors in a Vec so the LayoutManifest can
// borrow them. This helper struct owns the data.
struct OwnedManifest {
    name: String,
    disc: u8,
    version: u8,
    layout_id: [u8; 8],
    total_size: usize,
    has_dynamic_tail: bool,
    field_count: usize,
    fields: Vec<OwnedField>,
}

struct OwnedField {
    name: String,
    canonical_type: String,
    size: u16,
    offset: u16,
    intent: FieldIntent,
}

impl From<ParsedManifest> for OwnedManifest {
    fn from(p: ParsedManifest) -> Self {
        Self {
            name: p.name,
            disc: p.disc,
            version: p.version,
            layout_id: p.layout_id,
            total_size: p.total_size,
            has_dynamic_tail: p.has_dynamic_tail,
            field_count: p.fields.len(),
            fields: p
                .fields
                .into_iter()
                .map(|f| OwnedField {
                    name: f.name,
                    canonical_type: f.canonical_type,
                    size: f.size,
                    offset: f.offset,
                    intent: FieldIntent::Custom,
                })
                .collect(),
        }
    }
}

// -- Commands --

fn cmd_explain(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper explain <hex-data>");
        process::exit(1);
    }
    let data = match hex_decode(&args[0]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    if data.len() < 16 {
        println!(
            "This data is {} bytes, which is too short for Hopper's headered-account decoder.",
            data.len()
        );
        println!("Compact accounts are not decoded by this command.");
        process::exit(1);
    }

    let header = require_header(&data);

    println!(
        "Interpreting this as a headered Hopper account ({} bytes total).",
        data.len()
    );
    println!();

    // Header narrative
    println!("Header:");
    println!(
        "  Discriminator {} identifies the account type.",
        header.disc
    );
    println!(
        "  Layout version {}, fingerprint {}.",
        header.version,
        hex_encode(&header.layout_id)
    );
    let flag_str = format_flags(header.flags);
    if header.flags == 0 {
        println!("  No flags set.");
    } else {
        println!("  Flags: {} (0x{:04x}).", flag_str, header.flags);
    }
    println!();

    // Check if it looks segmented
    let is_segmented = header.flags & 0x0004 != 0;
    let has_registry = data.len() >= 20;
    let seg_result = if is_segmented || has_registry {
        decode_segments::<16>(&data)
    } else {
        None
    };

    match seg_result {
        Some((count, segments)) if count > 0 => {
            println!("Account structure: segmented ({} segments).", count);
            println!();
            let reg_end = 16 + 4 + count * 16;
            println!(
                "  Bytes 0..16 are the header, 16..{} is the segment registry.",
                reg_end
            );
            for (i, seg) in segments[..count].iter().enumerate() {
                let end = seg.offset as usize + seg.size as usize;
                let role_name = decode_segment_role(seg.flags);
                println!(
                    "  Segment {} (id {}): bytes {}..{} ({} bytes, role: {}).",
                    i,
                    hex_encode(&seg.id),
                    seg.offset,
                    end,
                    seg.size,
                    role_name,
                );
                println!("    {}", describe_segment_role(role_name));
            }

            // Migration advice summary
            let advice = SegmentMigrationReport::<16>::analyze(&segments, count);
            println!();
            println!("Migration readiness:");
            println!(
                "  {} must-preserve, {} clearable, {} rebuildable.",
                advice.must_preserve_count(),
                advice.clearable_count(),
                advice.rebuildable_bytes,
            );
            println!(
                "  preserve={} bytes, clearable={} bytes.",
                advice.preserve_bytes, advice.clearable_bytes,
            );
        }
        _ => {
            let body_size = data.len() - 16;
            println!(
                "Account structure: fixed layout ({} byte body after header).",
                body_size
            );
        }
    }

    println!();

    // Close sentinel check
    if data[0] == 0xFF {
        println!("Warning: discriminator is 0xFF. This account may have been closed");
        println!("with a sentinel byte to prevent revival.");
        println!();
    }

    // Zero-fill check
    let zero_body = data[16..].iter().all(|&b| b == 0);
    if zero_body && data.len() > 16 {
        println!("Note: the body is entirely zeroed. This account may be freshly");
        println!("initialized and still zeroed.");
        println!();
    }

    // Policy context hint based on account structure
    if is_segmented || seg_result.is_some() {
        println!("Policy context:");
        println!("  Segmented accounts typically use named policy packs:");
        println!("    TREASURY_WRITE  -- balance mutations (authority + snapshot + conservation)");
        println!("    JOURNAL_TOUCH   -- journal appends (authority + capacity + snapshot)");
        println!("    AUTHORITY_CHANGE -- permission changes (authority + CPI guard + invariants)");
        println!("  Use 'hopper receipt <hex>' to decode which capabilities were declared");
        println!("  in a specific transaction.");
        println!();
    }

    println!("Next steps:");
    println!("  hopper inspect <hex>     -- raw header fields");
    println!("  hopper segments <hex>    -- segment map with roles");
    println!("  hopper receipt <hex>     -- decode a state receipt from transaction logs");
    println!("  hopper compat <v1> <v2>  -- compare against another version");
    println!("  hopper plan <v1> <v2>    -- generate migration plan");
}

fn decode_segment_role(flags: u16) -> &'static str {
    SegmentRoleHint::from_flags(flags).name()
}

fn describe_segment_role(role: &str) -> &'static str {
    match role {
        "Core" | "core" => "Primary state, must be preserved across migrations.",
        "Extension" | "extension" => "Optional extension data, safe to append new fields.",
        "Journal" | "journal" => "Append-only log, may wrap if circular. Clearable on migration.",
        "Index" | "index" => "Derived lookup data. Can be rebuilt from core state.",
        "Cache" | "cache" => "Computed cache. Can be cleared and recomputed on migration.",
        "Audit" | "audit" => "Immutable audit trail. Must be preserved.",
        "Shard" | "shard" => "Partitioned data. May be split or merged across accounts.",
        _ => "No defined migration or runtime semantics.",
    }
}

fn cmd_inspect(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper inspect <hex-data>");
        process::exit(1);
    }
    let data = match hex_decode(&args[0]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    match decode_header(&data) {
        Some(h) => print_header(&h),
        None => {
            eprintln!(
                "Account data too short for header (need 16 bytes, got {})",
                data.len()
            );
            process::exit(1);
        }
    }
}

fn print_header(h: &DecodedHeader) {
    println!("=== Account Header (16 bytes) ===");
    println!("  Discriminator : {}", h.disc);
    println!("  Version       : {}", h.version);
    println!(
        "  Flags         : 0x{:04x} ({})",
        h.flags,
        format_flags(h.flags)
    );
    println!("  Layout ID     : {}", hex_encode(&h.layout_id));
    println!("  Schema epoch  : {}", h.schema_epoch);
}

fn format_flags(flags: u16) -> String {
    if flags == 0 {
        return "none".to_string();
    }
    let mut parts = Vec::new();
    if flags & 0x0001 != 0 {
        parts.push("INITIALIZED");
    }
    if flags & 0x0002 != 0 {
        parts.push("FROZEN");
    }
    if flags & 0x0004 != 0 {
        parts.push("SEGMENTED");
    }
    if flags & 0x0008 != 0 {
        parts.push("CLOSING");
    }
    if parts.is_empty() {
        format!("0x{:04x}", flags)
    } else {
        parts.join(" | ")
    }
}

fn cmd_segments(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper segments <hex-data>");
        process::exit(1);
    }
    let data = match hex_decode(&args[0]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    // Print header first
    if let Some(h) = decode_header(&data) {
        print_header(&h);
        println!();
    }

    match decode_segments::<16>(&data) {
        Some((count, segments)) => {
            println!("=== Segment Registry ({} segments) ===", count);
            println!(
                "  {:>4}  {:>10}  {:>10}  {:>8}  {:>6}  Ver",
                "#", "ID", "Offset", "Size", "Flags"
            );
            println!("  {}", "-".repeat(56));
            for (i, seg) in segments[..count].iter().enumerate() {
                println!(
                    "  {:>4}  {:>10}  {:>10}  {:>8}  0x{:04x}  {:>4}",
                    i,
                    hex_encode(&seg.id),
                    seg.offset,
                    seg.size,
                    seg.flags,
                    seg.version,
                );
            }

            // Visual segment map
            println!();
            println!("=== Segment Map ===");
            println!("  [Header: 0..16]");
            // Registry header + entries
            let reg_end = 16 + 4 + count * 16;
            println!("  [Registry: 16..{}]", reg_end);
            for (i, seg) in segments[..count].iter().enumerate() {
                let end = seg.offset as usize + seg.size as usize;
                println!(
                    "  [Segment {}: {}..{} ({} bytes, id={})]",
                    i,
                    seg.offset,
                    end,
                    seg.size,
                    hex_encode(&seg.id),
                );
            }
        }
        None => {
            eprintln!("Could not decode segment registry (data too short or invalid)");
            process::exit(1);
        }
    }
}

// -- Receipt decoding (matches hopper-core receipt wire format v2, 72 bytes) --

const RECEIPT_WIRE_SIZE: usize = 72;
const RECEIPT_WIRE_SIZE_LEGACY: usize = 64;

fn valid_receipt_len(len: usize) -> bool {
    len == RECEIPT_WIRE_SIZE_LEGACY || len >= RECEIPT_WIRE_SIZE
}

fn receipt_failure_stage_name(stage: u8) -> &'static str {
    match stage {
        1 => "validation",
        2 => "handler",
        3 => "invariant",
        4 => "post",
        5 => "teardown",
        _ => "none",
    }
}

fn cmd_receipt(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper receipt <hex-data>");
        process::exit(1);
    }
    let data = match hex_decode(&args[0]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    if !valid_receipt_len(data.len()) {
        eprintln!(
            "Receipt data must be exactly {} legacy bytes or at least {} current bytes (got {}).",
            RECEIPT_WIRE_SIZE_LEGACY,
            RECEIPT_WIRE_SIZE,
            data.len(),
        );
        process::exit(1);
    }

    let layout_id = &data[0..8];
    let changed_fields = u64::from_le_bytes(data[8..16].try_into().expect("slice length mismatch"));
    let changed_bytes = u32::from_le_bytes(data[16..20].try_into().expect("slice length mismatch"));
    let changed_regions =
        u16::from_le_bytes(data[20..22].try_into().expect("slice length mismatch"));
    let old_size = u32::from_le_bytes(data[22..26].try_into().expect("slice length mismatch"));
    let new_size = u32::from_le_bytes(data[26..30].try_into().expect("slice length mismatch"));
    let invariants_checked =
        u16::from_le_bytes(data[30..32].try_into().expect("slice length mismatch"));
    let flags = data[32];
    let was_resized = flags & (1 << 0) != 0;
    let invariants_passed = flags & (1 << 1) != 0;
    let cpi_invoked = flags & (1 << 2) != 0;
    let committed = flags & (1 << 3) != 0;
    let had_failure = flags & (1 << 4) != 0;
    let before_fp = &data[33..41];
    let after_fp = &data[41..49];
    let segment_mask = u16::from_le_bytes(data[49..51].try_into().expect("slice length mismatch"));
    let policy_flags = u32::from_le_bytes(data[51..55].try_into().expect("slice length mismatch"));
    let journal_appends =
        u16::from_le_bytes(data[55..57].try_into().expect("slice length mismatch"));
    let cpi_count = data[57];
    let phase = data[58];
    let validation_bundle_id =
        u16::from_le_bytes(data[59..61].try_into().expect("slice length mismatch"));
    let compat_impact = data[61];
    let migration_flags = data[62];
    let (failed_invariant_idx, failed_error_code, failure_stage) =
        if data.len() >= RECEIPT_WIRE_SIZE {
            (
                data[63],
                u32::from_le_bytes(data[64..68].try_into().expect("slice length mismatch")),
                data[68],
            )
        } else {
            (0xFF, 0, 0)
        };

    let phase_name = match phase {
        1 => "init",
        2 => "close",
        3 => "migrate",
        4 => "read-only",
        _ => "update",
    };
    let compat_name = match compat_impact {
        1 => "append",
        2 => "migration",
        3 => "breaking",
        _ => "none",
    };

    println!("=== State Receipt ({} bytes) ===", data.len());
    println!(
        "  Wire format         : {}",
        if data.len() == RECEIPT_WIRE_SIZE_LEGACY {
            "legacy 64-byte"
        } else {
            "current 72-byte"
        }
    );
    println!();
    println!("  Layout ID           : {}", hex_encode(layout_id));
    println!(
        "  Committed           : {}",
        if committed { "YES" } else { "NO" }
    );
    println!("  Phase               : {}", phase_name);
    println!();
    println!("  Changed bytes       : {}", changed_bytes);
    println!("  Changed regions     : {}", changed_regions);
    println!("  Changed field mask  : 0x{:016x}", changed_fields);
    if changed_fields != 0 {
        let mut fields_list = Vec::new();
        for bit in 0..64u32 {
            if changed_fields & (1u64 << bit) != 0 {
                fields_list.push(format!("{}", bit));
            }
        }
        println!("    Fields touched    : [{}]", fields_list.join(", "));
    }
    println!();
    println!("  Old size            : {} bytes", old_size);
    println!("  New size            : {} bytes", new_size);
    println!(
        "  Resized             : {}",
        if was_resized { "YES" } else { "NO" }
    );
    println!();
    println!("  Before fingerprint  : {}", hex_encode(before_fp));
    println!("  After fingerprint   : {}", hex_encode(after_fp));
    let fp_changed = before_fp != after_fp;
    println!(
        "  Data changed        : {}",
        if fp_changed { "YES" } else { "NO" }
    );
    println!();
    println!("  Invariants checked  : {}", invariants_checked);
    println!(
        "  Invariants passed   : {}",
        if invariants_passed { "YES" } else { "NO" }
    );
    println!();

    if policy_flags != 0 {
        println!("  Policy flags        : 0x{:08x}", policy_flags);
        let cap_names = [
            "ReadsState",
            "MutatesState",
            "TouchesJournal",
            "ExternalCall",
            "MutatesTreasury",
            "ReallocatesAccount",
            "CreatesAccount",
            "ClosesAccount",
            "ModifiesAuthority",
            "TransitionsState",
        ];
        let mut active = Vec::new();
        for (i, name) in cap_names.iter().enumerate() {
            if policy_flags & (1 << i) != 0 {
                active.push(*name);
            }
        }
        if !active.is_empty() {
            println!("    Capabilities      : {}", active.join(", "));
        }
        println!();
    }

    if segment_mask != 0 {
        println!("  Segment change mask : 0x{:04x}", segment_mask);
        let mut segs = Vec::new();
        for bit in 0..16u32 {
            if segment_mask & (1 << bit) != 0 {
                segs.push(format!("{}", bit));
            }
        }
        println!("    Segments touched  : [{}]", segs.join(", "));
        println!();
    }

    if journal_appends > 0 {
        println!("  Journal appends     : {}", journal_appends);
    }
    if cpi_invoked {
        println!("  CPI invoked         : YES ({} calls)", cpi_count);
    }

    if validation_bundle_id != 0 {
        println!("  Validation bundle   : {}", validation_bundle_id);
    }
    if compat_impact != 0 {
        println!("  Compat impact       : {}", compat_name);
    }
    if migration_flags != 0 {
        let mut mig = Vec::new();
        if migration_flags & 1 != 0 {
            mig.push("triggered");
        }
        if migration_flags & 2 != 0 {
            mig.push("realloc");
        }
        if migration_flags & 4 != 0 {
            mig.push("schema-bump");
        }
        println!("  Migration           : {}", mig.join(", "));
    }

    if had_failure || data.len() >= RECEIPT_WIRE_SIZE {
        println!(
            "  Failure recorded    : {}",
            if had_failure { "YES" } else { "NO" }
        );
        println!(
            "  Failure stage       : {}",
            receipt_failure_stage_name(failure_stage)
        );
        println!("  Failed invariant    : 0x{:02x}", failed_invariant_idx);
        println!("  Failed error code   : {}", failed_error_code);
    }
}

fn cmd_compat(args: &[String]) {
    let (why, operands) = match args.first().map(String::as_str) {
        Some("--why") => (true, &args[1..]),
        _ => (false, args),
    };
    if operands.len() != 2 {
        eprintln!("Usage: hopper compat [--why] <v1-json> <v2-json>");
        process::exit(1);
    }
    if why {
        cmd_explain_compat(operands);
        return;
    }
    let v1 = parse_or_exit(&operands[0]);
    let v2 = parse_or_exit(&operands[1]);

    let (m1, _f1) = to_manifest(&v1);
    let (m2, _f2) = to_manifest(&v2);

    let verdict = CompatibilityVerdict::between(&m1, &m2);

    println!("=== Compatibility Report ===");
    println!(
        "  {} v{} -> {} v{}",
        v1.name, v1.version, v2.name, v2.version
    );
    println!("  Layout ID (old) : {}", hex_encode(&v1.layout_id));
    println!("  Layout ID (new) : {}", hex_encode(&v2.layout_id));
    println!("  Size (old)      : {} bytes", v1.total_size);
    println!("  Size (new)      : {} bytes", v2.total_size);
    println!("  Verdict         : {}", verdict.name());
    println!(
        "  Safe            : {}",
        if verdict.is_safe() { "YES" } else { "NO" }
    );
    println!(
        "  Backward-read   : {}",
        if verdict.is_backward_readable() {
            "YES"
        } else {
            "NO"
        }
    );
    println!(
        "  Requires migration: {}",
        if verdict.requires_migration() {
            "YES"
        } else {
            "NO"
        }
    );

    println!();
    match verdict {
        CompatibilityVerdict::Identical => {
            println!("  Result: No changes detected.");
        }
        CompatibilityVerdict::WireCompatible => {
            println!(
                "  Result: Wire-compatible. Byte layout identical, semantic metadata differs."
            );
        }
        CompatibilityVerdict::AppendSafe => {
            println!("  Result: Safe upgrade. Old field prefix preserved, no migration needed.");
        }
        CompatibilityVerdict::MigrationRequired => {
            println!("  Result: Migration required. Use `hopper plan` for details.");
        }
        CompatibilityVerdict::Incompatible => {
            println!("  Result: Breaking change. Full migration required before upgrade.");
        }
    }
}

fn cmd_diff(args: &[String]) {
    if args.len() < 2 {
        eprintln!("Usage: hopper diff <v1-json> <v2-json>");
        process::exit(1);
    }
    let v1 = parse_or_exit(&args[0]);
    let v2 = parse_or_exit(&args[1]);

    let (m1, _f1) = to_manifest(&v1);
    let (m2, _f2) = to_manifest(&v2);

    let report = compare_fields::<32>(&m1, &m2);

    println!(
        "=== Field Diff: {} v{} -> {} v{} ===",
        v1.name, v1.version, v2.name, v2.version
    );
    println!("  {:>20}  {:>12}  {:>8}", "Field", "Status", "Detail");
    println!("  {}", "-".repeat(46));
    for i in 0..report.len() {
        if let Some(entry) = report.get(i) {
            let status_str = match entry.status {
                FieldCompat::Identical => "IDENTICAL",
                FieldCompat::Changed => "CHANGED",
                FieldCompat::Added => "ADDED",
                FieldCompat::Removed => "REMOVED",
            };
            let detail = match entry.status {
                FieldCompat::Added => {
                    // Find in v2 fields
                    let mut d = String::new();
                    for f in &v2.fields {
                        if f.name == entry.name {
                            d = format!("{} ({} bytes @ {})", f.canonical_type, f.size, f.offset);
                            break;
                        }
                    }
                    d
                }
                FieldCompat::Removed => "(deleted)".to_string(),
                FieldCompat::Changed => "(type or size changed)".to_string(),
                FieldCompat::Identical => "".to_string(),
            };
            println!("  {:>20}  {:>12}  {}", entry.name, status_str, detail);
        }
    }

    println!();
    let identical = report.count_status(FieldCompat::Identical);
    let added = report.count_status(FieldCompat::Added);
    let removed = report.count_status(FieldCompat::Removed);
    let changed = report.count_status(FieldCompat::Changed);
    println!(
        "  Summary: {} identical, {} added, {} removed, {} changed",
        identical, added, removed, changed
    );
    println!(
        "  Append-safe: {}",
        if report.is_append_safe { "YES" } else { "NO" }
    );
}

fn cmd_plan(args: &[String]) {
    if args.len() < 2 {
        eprintln!("Usage: hopper plan <v1-json> <v2-json>");
        process::exit(1);
    }
    let v1 = parse_or_exit(&args[0]);
    let v2 = parse_or_exit(&args[1]);

    let (m1, _f1) = to_manifest(&v1);
    let (m2, _f2) = to_manifest(&v2);

    let plan = MigrationPlan::<16>::generate(&m1, &m2);

    println!(
        "=== Migration Plan: {} v{} -> {} v{} ===",
        v1.name, v1.version, v2.name, v2.version
    );
    println!();

    let policy_str = match plan.policy {
        MigrationPolicy::NoOp => "NO-OP (layouts identical)",
        MigrationPolicy::AppendOnly => "APPEND-ONLY (safe in-place upgrade)",
        MigrationPolicy::RequiresMigration => "FULL MIGRATION (data copy required)",
        MigrationPolicy::Incompatible => "INCOMPATIBLE (different discriminators)",
    };
    println!("  Policy     : {}", policy_str);
    println!("  Old size   : {} bytes", plan.old_size);
    println!("  New size   : {} bytes", plan.new_size);
    println!("  Copy bytes : {}", plan.copy_bytes);
    println!("  Zero bytes : {}", plan.zero_bytes);
    println!(
        "  Backward   : {}",
        if plan.backward_readable {
            "YES (v1 code can read v2 accounts)"
        } else {
            "NO"
        }
    );
    println!("  Steps      : {}", plan.len());

    if !plan.is_empty() {
        println!();
        println!(
            "  {:>4}  {:>14}  {:>8}  {:>8}  Field",
            "#", "Action", "Offset", "Size"
        );
        println!("  {}", "-".repeat(52));
        plan.for_each_step(|i, step| {
            let action_str = match step.action {
                MigrationAction::CopyPrefix => "CopyPrefix",
                MigrationAction::ZeroInit => "ZeroInit",
                MigrationAction::UpdateHeader => "UpdateHeader",
                MigrationAction::Realloc => "Realloc",
            };
            let field = if step.field.is_empty() {
                "-"
            } else {
                step.field
            };
            println!(
                "  {:>4}  {:>14}  {:>8}  {:>8}  {}",
                i, action_str, step.offset, step.size, field
            );
        });
    }
}

fn cmd_schema_export_family(args: &[String]) {
    if args.is_empty() {
        // No flag: show the reference document
        cmd_schema_export();
        return;
    }
    match args[0].as_str() {
        "--manifest" => {
            if args.len() < 2 {
                eprintln!("Usage: hopper schema export --manifest <manifest-json>");
                process::exit(1);
            }
            let prog = load_program_manifest(&args[1]);
            println!("{}", hopper_schema::codama::ManifestJson(&prog));
        }
        "--idl" => {
            if args.len() < 2 {
                eprintln!("Usage: hopper schema export --idl <manifest-json>");
                process::exit(1);
            }
            let prog = load_program_manifest(&args[1]);
            println!("{}", hopper_schema::codama::IdlJsonFromManifest(&prog));
        }
        "--codama" => {
            if args.len() < 2 {
                eprintln!("Usage: hopper schema export --codama <manifest-json>");
                process::exit(1);
            }
            let prog = load_program_manifest(&args[1]);
            println!("{}", hopper_schema::codama::CodamaJsonFromManifest(&prog));
        }
        "--anchor-idl" => {
            if args.len() != 4 || args[2] != "--program-id" {
                eprintln!(
                    "Usage: hopper schema export --anchor-idl <manifest-json> --program-id <pubkey>"
                );
                process::exit(1);
            }
            let program_id = &args[3];
            let decoded = bs58::decode(program_id).into_vec().unwrap_or_else(|error| {
                eprintln!("invalid base58 program id: {error}");
                process::exit(1);
            });
            if decoded.len() != 32 {
                eprintln!("program id must be 32 bytes, got {}", decoded.len());
                process::exit(1);
            }
            let prog = load_program_manifest(&args[1]);
            let projection = hopper_schema::anchor_idl::AnchorIdlFromManifest {
                manifest: &prog,
                address: program_id,
            };
            if let Err(error) = projection.validate() {
                eprintln!("cannot export a complete Solana IDL v0.1.0: {error}");
                process::exit(1);
            }
            println!("{projection}");
        }
        _ => cmd_schema_export(),
    }
}

fn cmd_schema_export() {
    println!("=== Hopper Account Schema Format ===");
    println!();
    println!("Header (16 bytes, offset 0):");
    println!("  [0]      disc        u8       Account discriminator");
    println!("  [1]      version     u8       Layout version");
    println!("  [2..4]   flags       u16 LE   Status flags");
    println!("  [4..12]  layout_id   [u8;8]   SHA-256 fingerprint (first 8 bytes)");
    println!("  [12..16] schema_epoch u32 LE  Schema evolution epoch");
    println!();
    println!("Flags (bits):");
    println!("  0x0001   INITIALIZED");
    println!("  0x0002   FROZEN");
    println!("  0x0004   SEGMENTED");
    println!("  0x0008   CLOSING");
    println!();
    println!("Layout ID computation:");
    println!("  sha256(\"hopper:v1:{{Name}}:{{version}}:{{field}}:{{type}}:{{size}},...\")[..8]");
    println!();
    println!("Segment Registry (for segmented accounts):");
    println!("  [+0..2]  count       u16 LE   Number of segments");
    println!("  [+2..4]  reserved    u16 LE   Reserved");
    println!("  For each segment (16 bytes):");
    println!("    [+0..4]   id        [u8;4]   FNV-1a hash of segment name");
    println!("    [+4..8]   offset    u32 LE   Byte offset in account data");
    println!("    [+8..12]  size      u32 LE   Segment size in bytes");
    println!("    [+12..14] flags     u16 LE   Segment flags (includes role in bits 12-15)");
    println!("    [+14]     version   u8       Segment version");
    println!("    [+15]     reserved  u8       Reserved");
    println!();
    println!("Segment Roles (upper 4 bits of segment flags):");
    println!("  0x0000   Unclassified");
    println!("  0x1000   Core       -- primary state, must preserve");
    println!("  0x2000   Extension  -- optional fields, must preserve");
    println!("  0x3000   Journal    -- append-only log, clearable on migration");
    println!("  0x4000   Index      -- derived lookup, rebuildable");
    println!("  0x5000   Cache      -- computed cache, rebuildable");
    println!("  0x6000   Audit      -- immutable trail, must preserve");
    println!("  0x7000   Shard      -- partitioned data, must preserve");
    println!();
    println!("State Receipt (72 bytes current, 64-byte legacy prefix supported):");
    println!("  [0..8]   layout_id            [u8;8]    Source layout fingerprint");
    println!("  [8..16]  changed_fields       u64 LE    Changed field bitmask");
    println!("  [16..20] changed_bytes        u32 LE    Byte count of changes");
    println!("  [20..22] changed_regions      u16 LE    Number of changed regions");
    println!("  [22..26] old_size             u32 LE    Size before mutation");
    println!("  [26..30] new_size             u32 LE    Size after mutation");
    println!("  [30..32] inv_checked          u16 LE    Invariants checked count");
    println!("  [32]     flags                u8        resized/passed/CPI/committed/failure bits");
    println!("  [33..41] before_fp            [u8;8]    Fingerprint before mutation");
    println!("  [41..49] after_fp             [u8;8]    Fingerprint after mutation");
    println!("  [49..51] segment_mask         u16 LE    Bitmask of changed segments");
    println!("  [51..55] policy_flags         u32 LE    Capability bitmask");
    println!("  [55..57] journal_appends      u16 LE    Journal append count");
    println!("  [57]     cpi_count            u8        CPI invocation count");
    println!("  [58]     phase                u8        Instruction phase tag");
    println!("  [59..61] validation_bundle_id u16 LE    Program-defined validation bundle");
    println!("  [61]     compat_impact        u8        Compatibility impact tag");
    println!("  [62]     migration_flags      u8        Migration flags");
    println!("  [63]     failed_invariant_idx u8        0xFF = none");
    println!("  [64..68] failed_error_code    u32 LE    0 = none");
    println!("  [68]     failure_stage        u8        FailureStage tag");
    println!("  [69..72] reserved             [u8;3]    Reserved");
    println!();
    println!("Policy Capability Bits (in receipt policy_flags):");
    println!("  bit 0    ReadsState");
    println!("  bit 1    MutatesState");
    println!("  bit 2    TouchesJournal");
    println!("  bit 3    ExternalCall");
    println!("  bit 4    MutatesTreasury");
    println!("  bit 5    ReallocatesAccount");
    println!("  bit 6    CreatesAccount");
    println!("  bit 7    ClosesAccount");
    println!("  bit 8    ModifiesAuthority");
    println!("  bit 9    TransitionsState");
    println!();
    println!("Named Policy Packs:");
    println!("  TREASURY_WRITE      MutatesState + MutatesTreasury");
    println!("  JOURNAL_TOUCH       MutatesState + TouchesJournal");
    println!("  EXTERNAL_CALL       ExternalCall");
    println!("  SHARD_MUTATION      MutatesState");
    println!("  MIGRATION_SENSITIVE MutatesState + ReallocatesAccount");
    println!("  AUTHORITY_CHANGE    MutatesState + ModifiesAuthority");
    println!();
    println!("--- Layout Manifest JSON ---");
    println!("  {{");
    println!("    \"name\": \"Vault\",");
    println!("    \"disc\": 1,");
    println!("    \"version\": 1,");
    println!("    \"layout_id\": [1,2,3,4,5,6,7,8],");
    println!("    \"total_size\": 57,");
    println!("    \"fields\": [");
    println!("      {{\"name\":\"authority\",\"type\":\"[u8;32]\",\"size\":32,\"offset\":16}},");
    println!("      {{\"name\":\"balance\",\"type\":\"WireU64\",\"size\":8,\"offset\":48}},");
    println!("      {{\"name\":\"bump\",\"type\":\"u8\",\"size\":1,\"offset\":56}}");
    println!("    ]");
    println!("  }}");
    println!();
    println!("--- Program Manifest JSON (for Hopper Manager) ---");
    println!("  {{");
    println!("    \"name\": \"my_program\",");
    println!("    \"version\": \"0.3.0\",");
    println!("    \"description\": \"Program description\",");
    println!("    \"layouts\": [");
    println!("      {{ <layout manifest as above> }}");
    println!("    ],");
    println!("    \"instructions\": [");
    println!("      {{");
    println!("        \"name\": \"deposit\",");
    println!("        \"tag\": 1,");
    println!("        \"args\": [{{\"name\":\"amount\",\"type\":\"WireU64\",\"size\":8}}],");
    println!("        \"accounts\": [");
    println!("          {{\"name\":\"vault\",\"writable\":true,\"signer\":false,\"layout_ref\":\"VaultState\"}}");
    println!("        ],");
    println!("        \"capabilities\": [\"MutatesState\",\"MutatesTreasury\"],");
    println!("        \"policy_pack\": \"TREASURY_WRITE\",");
    println!("        \"receipt_expected\": true");
    println!("      }}");
    println!("    ],");
    println!("    \"events\": [");
    println!("      {{");
    println!("        \"name\": \"DepositEvent\",");
    println!("        \"tag\": 1,");
    println!("        \"fields\": [{{\"name\":\"amount\",\"type\":\"WireU64\",\"size\":8,\"offset\":0}}]");
    println!("      }}");
    println!("    ],");
    println!("    \"policies\": [");
    println!("      {{");
    println!("        \"name\": \"TREASURY_WRITE\",");
    println!("        \"capabilities\": [\"MutatesState\",\"MutatesTreasury\"],");
    println!("        \"requirements\": [\"SignerAuthority\",\"SnapshotCommit\"]");
    println!("      }}");
    println!("    ]");
    println!("  }}");
    println!();
    println!("Use 'hopper manager summary @manifest.json' to inspect a program manifest.");
    println!("Use 'hopper manager decode @manifest.json <hex>' to decode account fields.");
}

// -- Helpers --

/// If the argument starts with `@`, read the file contents. Otherwise return as-is.
fn resolve_manifest_arg(arg: &str) -> String {
    if let Some(path) = arg.strip_prefix('@') {
        match std::fs::read_to_string(path) {
            Ok(contents) => contents,
            Err(e) => {
                eprintln!("Could not read manifest file '{}': {}", path, e);
                process::exit(1);
            }
        }
    } else {
        arg.to_string()
    }
}

// ---------------------------------------------------------------------------
// Program Manifest JSON Parser (for Manager commands)
// ---------------------------------------------------------------------------

struct OwnedProgramManifest {
    name: String,
    version: String,
    description: String,
    layouts: Vec<OwnedManifest>,
    instructions: Vec<OwnedInstruction>,
    events: Vec<OwnedEvent>,
    policies: Vec<OwnedPolicy>,
    layout_metadata: Vec<OwnedLayoutMetadata>,
    compatibility_pairs: Vec<OwnedCompatibilityPair>,
    tooling_hints: Vec<String>,
    contexts: Vec<OwnedContext>,
}

struct OwnedInstruction {
    name: String,
    tag: u8,
    discriminator: Vec<u8>,
    args: Vec<OwnedArg>,
    accounts: Vec<OwnedAccount>,
    remaining_accounts_max: Option<u16>,
    capabilities: Vec<String>,
    policy_pack: String,
    receipt_expected: bool,
    // Byte-range write authority and compute-budget metadata.
    // Carried verbatim from the manifest so the CLI-loaded descriptor
    // matches the compiled program's declared write surface. Round-trips
    // with codama's emitter (crates/hopper-schema/src/codama.rs:643-672):
    // strictWrites / writeRanges / cuEstimate / mutationComplete /
    // lamportAccounts. Defaults (false / empty / 0) reproduce the
    // legacy behavior for older manifests that omit these keys.
    strict_writes: bool,
    write_ranges: Vec<OwnedWriteRange>,
    parametric_write_ranges: Vec<OwnedParametricWriteRange>,
    mutation_complete: bool,
    lamport_accounts: Vec<u8>,
    cu_estimate: u32,
}

/// One declared byte-range write on one instruction account, parsed from a
/// manifest `writeRanges` entry. Mirrors [`hopper_schema::WriteRange`]; the
/// `account` name string codama also emits is derived and intentionally
/// ignored here (the index is authoritative).
struct OwnedWriteRange {
    account_index: u8,
    offset: u32,
    size: u32,
}

struct OwnedParametricWriteRange {
    account_index: u8,
    base_offset: u32,
    stride: u32,
    cell_size: u32,
    count: u32,
    argument_index: u8,
    argument: String,
    segment: String,
}

struct OwnedArg {
    name: String,
    canonical_type: String,
    size: u16,
    encoding: OwnedArgEncoding,
    max_len: u16,
    element_size: u16,
}

#[derive(Clone, Copy)]
enum OwnedArgEncoding {
    Fixed,
    BoundedVec,
    BoundedString,
}

struct OwnedAccount {
    name: String,
    writable: bool,
    signer: bool,
    layout_ref: String,
    seeds: Vec<String>,
}

struct OwnedEvent {
    name: String,
    tag: u8,
    fields: Vec<OwnedField>,
}

struct OwnedPolicy {
    name: String,
    capabilities: Vec<String>,
    requirements: Vec<String>,
    invariants: Vec<String>,
    receipt_profile: String,
}

struct OwnedLayoutMetadata {
    name: String,
    segment_roles: Vec<String>,
    append_safe: bool,
    migration_required: bool,
    rebuildable: bool,
    policy_pack: String,
    invariant_pack: Vec<String>,
    receipt_profile: String,
    phase_requirements: Vec<String>,
    trust_profile: String,
    manager_hints: Vec<String>,
}

struct OwnedCompatibilityPair {
    from_layout: String,
    from_version: u8,
    to_layout: String,
    to_version: u8,
    policy: MigrationPolicy,
    backward_readable: bool,
}

struct OwnedContext {
    name: String,
    /// Handler names bound to this context (manifest key `instructions`).
    /// Absent in manifests written before the key existed.
    instructions: Vec<String>,
    accounts: Vec<OwnedContextAccount>,
    policies: Vec<String>,
    receipts_expected: bool,
    mutation_classes: Vec<String>,
    // Context-level strict-write surface, same round-trip contract as the
    // instruction fields above. Absent from legacy manifests -> defaults.
    strict_writes: bool,
    write_ranges: Vec<OwnedWriteRange>,
    parametric_write_ranges: Vec<OwnedParametricWriteRange>,
    mutation_complete: bool,
    lamport_accounts: Vec<u8>,
}

struct OwnedContextAccount {
    name: String,
    kind: String,
    writable: bool,
    signer: bool,
    layout_ref: String,
    policy_ref: String,
    seeds: Vec<String>,
    optional: bool,
    // Lifecycle metadata.
    lifecycle: AccountLifecycle,
    payer: String,
    init_space: u32,
    has_one: Vec<String>,
    expected_address: String,
    expected_owner: String,
}

/// Parse the canonical rich manifest JSON emitted by `ManifestJson`.
///
/// Legacy snake_case aliases remain accepted, but conversion is typed and
/// range-checked so contract metadata cannot disappear through substring
/// parsing or integer truncation.
fn parse_program_manifest_json(json: &str) -> Result<OwnedProgramManifest, String> {
    use serde_json::{Map, Value};

    fn object<'a>(value: &'a Value, label: &str) -> Result<&'a Map<String, Value>, String> {
        value
            .as_object()
            .ok_or_else(|| format!("{label} must be a JSON object"))
    }
    fn value_for<'a>(obj: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
        keys.iter().find_map(|key| obj.get(*key))
    }
    fn string(obj: &Map<String, Value>, keys: &[&str], default: &str) -> Result<String, String> {
        match value_for(obj, keys) {
            Some(value) => value
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| format!("{} must be a string", keys[0])),
            None => Ok(default.to_string()),
        }
    }
    fn required_string(obj: &Map<String, Value>, keys: &[&str]) -> Result<String, String> {
        let value = string(obj, keys, "")?;
        if value.is_empty() {
            Err(format!("missing required string {}", keys[0]))
        } else {
            Ok(value)
        }
    }
    fn number(obj: &Map<String, Value>, keys: &[&str], default: u64) -> Result<u64, String> {
        match value_for(obj, keys) {
            Some(value) => value
                .as_u64()
                .ok_or_else(|| format!("{} must be an unsigned integer", keys[0])),
            None => Ok(default),
        }
    }
    fn boolean(obj: &Map<String, Value>, keys: &[&str], default: bool) -> Result<bool, String> {
        match value_for(obj, keys) {
            Some(value) => value
                .as_bool()
                .ok_or_else(|| format!("{} must be a boolean", keys[0])),
            None => Ok(default),
        }
    }
    fn array<'a>(obj: &'a Map<String, Value>, keys: &[&str]) -> Result<&'a [Value], String> {
        match value_for(obj, keys) {
            Some(value) => value
                .as_array()
                .map(Vec::as_slice)
                .ok_or_else(|| format!("{} must be an array", keys[0])),
            None => Ok(&[]),
        }
    }
    fn strings(obj: &Map<String, Value>, keys: &[&str]) -> Result<Vec<String>, String> {
        array(obj, keys)?
            .iter()
            .map(|value| {
                value
                    .as_str()
                    .map(str::to_string)
                    .ok_or_else(|| format!("{} entries must be strings", keys[0]))
            })
            .collect()
    }
    fn as_u8(value: u64, label: &str) -> Result<u8, String> {
        u8::try_from(value).map_err(|_| format!("{label} exceeds u8"))
    }
    fn as_u16(value: u64, label: &str) -> Result<u16, String> {
        u16::try_from(value).map_err(|_| format!("{label} exceeds u16"))
    }
    fn as_u32(value: u64, label: &str) -> Result<u32, String> {
        u32::try_from(value).map_err(|_| format!("{label} exceeds u32"))
    }
    fn byte_array(obj: &Map<String, Value>, keys: &[&str]) -> Result<Vec<u8>, String> {
        array(obj, keys)?
            .iter()
            .map(|value| {
                value
                    .as_u64()
                    .ok_or_else(|| format!("{} entries must be bytes", keys[0]))
                    .and_then(|value| as_u8(value, keys[0]))
            })
            .collect()
    }
    fn layout_id(obj: &Map<String, Value>) -> Result<[u8; 8], String> {
        if let Some(value) = value_for(obj, &["layoutId"]) {
            let hex = value
                .as_str()
                .ok_or_else(|| "layoutId must be a hex string".to_string())?;
            if hex.len() != 16 {
                return Err("layoutId must contain exactly 8 bytes".to_string());
            }
            let mut out = [0u8; 8];
            for (index, chunk) in hex.as_bytes().chunks_exact(2).enumerate() {
                let pair = std::str::from_utf8(chunk).map_err(|_| "layoutId is not UTF-8")?;
                out[index] = u8::from_str_radix(pair, 16)
                    .map_err(|error| format!("invalid layoutId: {error}"))?;
            }
            return Ok(out);
        }
        let bytes = byte_array(obj, &["layout_id"])?;
        bytes
            .try_into()
            .map_err(|_| "layout_id must contain exactly 8 bytes".to_string())
    }
    fn field_intent(value: &str) -> Result<FieldIntent, String> {
        let intent = match value {
            "balance" => FieldIntent::Balance,
            "authority" => FieldIntent::Authority,
            "timestamp" => FieldIntent::Timestamp,
            "counter" => FieldIntent::Counter,
            "index" => FieldIntent::Index,
            "basis_points" => FieldIntent::BasisPoints,
            "flag" => FieldIntent::Flag,
            "address" => FieldIntent::Address,
            "hash" => FieldIntent::Hash,
            "pda_seed" => FieldIntent::PDASeed,
            "version" => FieldIntent::Version,
            "bump" => FieldIntent::Bump,
            "nonce" => FieldIntent::Nonce,
            "supply" => FieldIntent::Supply,
            "limit" => FieldIntent::Limit,
            "threshold" => FieldIntent::Threshold,
            "owner" => FieldIntent::Owner,
            "delegate" => FieldIntent::Delegate,
            "status" => FieldIntent::Status,
            "custom" => FieldIntent::Custom,
            _ => return Err(format!("unknown field intent `{value}`")),
        };
        Ok(intent)
    }
    fn arg_encoding(value: &str) -> Result<OwnedArgEncoding, String> {
        match value {
            "fixed" => Ok(OwnedArgEncoding::Fixed),
            "boundedVec" => Ok(OwnedArgEncoding::BoundedVec),
            "boundedString" => Ok(OwnedArgEncoding::BoundedString),
            _ => Err(format!("unknown argument encoding `{value}`")),
        }
    }
    fn account_lifecycle(value: &str) -> Result<AccountLifecycle, String> {
        let normalized: String = value
            .trim()
            .chars()
            .filter(|character| !matches!(character, '_' | '-'))
            .map(|character| character.to_ascii_lowercase())
            .collect();
        match normalized.as_str() {
            "existing" => Ok(AccountLifecycle::Existing),
            "init" | "create" => Ok(AccountLifecycle::Init),
            "initifneeded" | "createifneeded" => Ok(AccountLifecycle::InitIfNeeded),
            "realloc" | "reallocate" => Ok(AccountLifecycle::Realloc),
            "close" => Ok(AccountLifecycle::Close),
            _ => Err(format!("unknown account lifecycle `{value}`")),
        }
    }
    fn write_ranges(
        obj: &Map<String, Value>,
        keys: &[&str],
    ) -> Result<Vec<OwnedWriteRange>, String> {
        array(obj, keys)?
            .iter()
            .map(|value| {
                let range = object(value, "write range")?;
                Ok(OwnedWriteRange {
                    account_index: as_u8(
                        number(range, &["accountIndex", "account_index"], 0)?,
                        "accountIndex",
                    )?,
                    offset: as_u32(number(range, &["offset"], 0)?, "offset")?,
                    size: as_u32(number(range, &["size"], 0)?, "size")?,
                })
            })
            .collect()
    }
    fn parametric_ranges(
        obj: &Map<String, Value>,
        keys: &[&str],
    ) -> Result<Vec<OwnedParametricWriteRange>, String> {
        array(obj, keys)?
            .iter()
            .map(|value| {
                let range = object(value, "parametric write range")?;
                Ok(OwnedParametricWriteRange {
                    account_index: as_u8(
                        number(range, &["accountIndex", "account_index"], 0)?,
                        "accountIndex",
                    )?,
                    base_offset: as_u32(
                        number(range, &["baseOffset", "base_offset"], 0)?,
                        "baseOffset",
                    )?,
                    stride: as_u32(number(range, &["stride"], 0)?, "stride")?,
                    cell_size: as_u32(number(range, &["cellSize", "cell_size"], 0)?, "cellSize")?,
                    count: as_u32(number(range, &["count"], 0)?, "count")?,
                    argument_index: as_u8(
                        number(range, &["argumentIndex", "argument_index"], 0)?,
                        "argumentIndex",
                    )?,
                    argument: required_string(
                        range,
                        &["argument", "argumentName", "argument_name"],
                    )?,
                    segment: required_string(range, &["segment", "segmentName", "segment_name"])?,
                })
            })
            .collect()
    }

    let root: Value = serde_json::from_str(json)
        .map_err(|error| format!("invalid program manifest JSON: {error}"))?;
    let root = object(&root, "program manifest")?;
    let name = required_string(root, &["name"])?;
    let version = string(root, &["version"], "0.1.0")?;
    let description = string(root, &["description"], "")?;

    let mut layouts = Vec::new();
    for value in array(root, &["layouts"])? {
        let layout = object(value, "layout")?;
        let mut fields = Vec::new();
        for value in array(layout, &["fields"])? {
            let field = object(value, "layout field")?;
            fields.push(OwnedField {
                name: required_string(field, &["name"])?,
                canonical_type: required_string(
                    field,
                    &["type", "canonicalType", "canonical_type"],
                )?,
                size: as_u16(number(field, &["size"], 0)?, "field size")?,
                offset: as_u16(number(field, &["offset"], 0)?, "field offset")?,
                intent: field_intent(&string(field, &["intent"], "custom")?)?,
            });
        }
        let field_count = usize::try_from(number(
            layout,
            &["fieldCount", "field_count"],
            fields.len() as u64,
        )?)
        .map_err(|_| "fieldCount exceeds usize".to_string())?;
        layouts.push(OwnedManifest {
            name: required_string(layout, &["name"])?,
            disc: as_u8(number(layout, &["disc"], 0)?, "layout disc")?,
            version: as_u8(number(layout, &["version"], 0)?, "layout version")?,
            layout_id: layout_id(layout)?,
            total_size: usize::try_from(number(layout, &["totalSize", "total_size"], 0)?)
                .map_err(|_| "totalSize exceeds usize".to_string())?,
            has_dynamic_tail: boolean(layout, &["hasDynamicTail", "has_dynamic_tail"], false)?,
            field_count,
            fields,
        });
    }

    let mut instructions = Vec::new();
    for value in array(root, &["instructions"])? {
        let instruction = object(value, "instruction")?;
        let ix_name = required_string(instruction, &["name"])?;
        let tag = as_u8(number(instruction, &["tag"], 0)?, "instruction tag")?;
        let mut args = Vec::new();
        for value in array(instruction, &["args"])? {
            let arg = object(value, "instruction argument")?;
            args.push(OwnedArg {
                name: required_string(arg, &["name"])?,
                canonical_type: required_string(arg, &["type", "canonicalType", "canonical_type"])?,
                size: as_u16(number(arg, &["size"], 0)?, "argument size")?,
                encoding: arg_encoding(&string(arg, &["encoding"], "fixed")?)?,
                max_len: as_u16(number(arg, &["maxLen", "max_len"], 0)?, "maxLen")?,
                element_size: as_u16(
                    number(arg, &["elementSize", "element_size"], 0)?,
                    "elementSize",
                )?,
            });
        }
        let mut accounts = Vec::new();
        for value in array(instruction, &["accounts"])? {
            let account = object(value, "instruction account")?;
            accounts.push(OwnedAccount {
                name: required_string(account, &["name"])?,
                writable: boolean(account, &["writable"], false)?,
                signer: boolean(account, &["signer"], false)?,
                layout_ref: string(account, &["layoutRef", "layout_ref"], "")?,
                seeds: strings(account, &["seeds"])?,
            });
        }
        let mut discriminator =
            byte_array(instruction, &["discriminatorBytes", "discriminator_bytes"])?;
        if discriminator.is_empty() {
            discriminator.push(tag);
        }
        if discriminator.len() > 8 || discriminator[0] != tag {
            return Err(format!(
                "instruction `{ix_name}` has invalid discriminatorBytes: expected 1..=8 bytes beginning with tag {tag}"
            ));
        }
        let remaining_accounts_max = value_for(
            instruction,
            &["remainingAccountsMax", "remaining_accounts_max"],
        )
        .map(|_| {
            number(
                instruction,
                &["remainingAccountsMax", "remaining_accounts_max"],
                0,
            )
        })
        .transpose()?
        .map(|value| as_u16(value, "remainingAccountsMax"))
        .transpose()?;
        instructions.push(OwnedInstruction {
            name: ix_name,
            tag,
            discriminator,
            args,
            accounts,
            remaining_accounts_max,
            capabilities: strings(instruction, &["capabilities"])?,
            policy_pack: string(instruction, &["policyPack", "policy_pack"], "")?,
            receipt_expected: boolean(
                instruction,
                &["receiptExpected", "receipt_expected"],
                false,
            )?,
            strict_writes: boolean(instruction, &["strictWrites", "strict_writes"], false)?,
            write_ranges: write_ranges(instruction, &["writeRanges", "write_ranges"])?,
            parametric_write_ranges: parametric_ranges(
                instruction,
                &["parametricWriteRanges", "parametric_write_ranges"],
            )?,
            mutation_complete: boolean(
                instruction,
                &["mutationComplete", "mutation_complete"],
                false,
            )?,
            lamport_accounts: byte_array(instruction, &["lamportAccounts", "lamport_accounts"])?,
            cu_estimate: as_u32(
                number(instruction, &["cuEstimate", "cu_estimate"], 0)?,
                "cuEstimate",
            )?,
        });
    }

    let mut events = Vec::new();
    for value in array(root, &["events"])? {
        let event = object(value, "event")?;
        let mut fields = Vec::new();
        for value in array(event, &["fields"])? {
            let field = object(value, "event field")?;
            fields.push(OwnedField {
                name: required_string(field, &["name"])?,
                canonical_type: required_string(field, &["type"])?,
                size: as_u16(number(field, &["size"], 0)?, "event field size")?,
                offset: as_u16(number(field, &["offset"], 0)?, "event field offset")?,
                intent: field_intent(&string(field, &["intent"], "custom")?)?,
            });
        }
        events.push(OwnedEvent {
            name: required_string(event, &["name"])?,
            tag: as_u8(number(event, &["tag"], 0)?, "event tag")?,
            fields,
        });
    }

    let mut policies = Vec::new();
    for value in array(root, &["policies"])? {
        let policy = object(value, "policy")?;
        policies.push(OwnedPolicy {
            name: required_string(policy, &["name"])?,
            capabilities: strings(policy, &["capabilities"])?,
            requirements: strings(policy, &["requirements"])?,
            invariants: strings(policy, &["invariants"])?,
            receipt_profile: string(policy, &["receiptProfile", "receipt_profile"], "")?,
        });
    }

    let mut layout_metadata = Vec::new();
    for value in array(root, &["layoutMetadata", "layout_metadata"])? {
        let metadata = object(value, "layout metadata")?;
        layout_metadata.push(OwnedLayoutMetadata {
            name: required_string(metadata, &["name"])?,
            segment_roles: strings(metadata, &["segmentRoles", "segment_roles"])?,
            append_safe: boolean(metadata, &["appendSafe", "append_safe"], false)?,
            migration_required: boolean(
                metadata,
                &["migrationRequired", "migration_required"],
                false,
            )?,
            rebuildable: boolean(metadata, &["rebuildable"], false)?,
            policy_pack: string(metadata, &["policyPack", "policy_pack"], "")?,
            invariant_pack: strings(metadata, &["invariantPack", "invariant_pack"])?,
            receipt_profile: string(metadata, &["receiptProfile", "receipt_profile"], "")?,
            phase_requirements: strings(metadata, &["phaseRequirements", "phase_requirements"])?,
            trust_profile: string(metadata, &["trustProfile", "trust_profile"], "")?,
            manager_hints: strings(metadata, &["managerHints", "manager_hints"])?,
        });
    }

    let mut compatibility_pairs = Vec::new();
    for value in array(
        root,
        &["compatRules", "compatibilityPairs", "compatibility_pairs"],
    )? {
        let pair = object(value, "compatibility rule")?;
        let policy_name = required_string(pair, &["policy"])?;
        let policy = match policy_name.as_str() {
            "noop" | "no-op" => MigrationPolicy::NoOp,
            "append-only" | "append_only" => MigrationPolicy::AppendOnly,
            "requires-migration" | "requires_migration" => MigrationPolicy::RequiresMigration,
            "incompatible" => MigrationPolicy::Incompatible,
            _ => return Err(format!("unknown migration policy `{policy_name}`")),
        };
        compatibility_pairs.push(OwnedCompatibilityPair {
            from_layout: required_string(pair, &["from", "fromLayout", "from_layout"])?,
            from_version: as_u8(
                number(pair, &["fromVersion", "from_version"], 0)?,
                "fromVersion",
            )?,
            to_layout: required_string(pair, &["to", "toLayout", "to_layout"])?,
            to_version: as_u8(number(pair, &["toVersion", "to_version"], 0)?, "toVersion")?,
            policy,
            backward_readable: boolean(pair, &["backwardReadable", "backward_readable"], false)?,
        });
    }

    let mut contexts = Vec::new();
    for value in array(root, &["contexts"])? {
        let context = object(value, "context")?;
        let mut accounts = Vec::new();
        for value in array(context, &["accounts"])? {
            let account = object(value, "context account")?;
            accounts.push(OwnedContextAccount {
                name: required_string(account, &["name"])?,
                kind: string(account, &["kind"], "AccountView")?,
                writable: boolean(account, &["writable"], false)?,
                signer: boolean(account, &["signer"], false)?,
                layout_ref: string(account, &["layoutRef", "layout_ref"], "")?,
                policy_ref: string(account, &["policyRef", "policy_ref"], "")?,
                seeds: strings(account, &["seeds"])?,
                optional: boolean(account, &["optional"], false)?,
                lifecycle: account_lifecycle(&string(account, &["lifecycle"], "existing")?)?,
                payer: string(account, &["payer"], "")?,
                init_space: as_u32(
                    number(account, &["initSpace", "init_space"], 0)?,
                    "initSpace",
                )?,
                has_one: strings(account, &["hasOne", "has_one"])?,
                expected_address: string(account, &["expectedAddress", "expected_address"], "")?,
                expected_owner: string(account, &["expectedOwner", "expected_owner"], "")?,
            });
        }
        contexts.push(OwnedContext {
            name: required_string(context, &["name"])?,
            instructions: strings(context, &["instructions"])?,
            accounts,
            policies: strings(context, &["policies"])?,
            receipts_expected: boolean(context, &["receiptsExpected", "receipts_expected"], false)?,
            mutation_classes: strings(context, &["mutationClasses", "mutation_classes"])?,
            strict_writes: boolean(context, &["strictWrites", "strict_writes"], false)?,
            write_ranges: write_ranges(context, &["writeRanges", "write_ranges"])?,
            parametric_write_ranges: parametric_ranges(
                context,
                &["parametricWriteRanges", "parametric_write_ranges"],
            )?,
            mutation_complete: boolean(context, &["mutationComplete", "mutation_complete"], false)?,
            lamport_accounts: byte_array(context, &["lamportAccounts", "lamport_accounts"])?,
        });
    }

    Ok(OwnedProgramManifest {
        name,
        version,
        description,
        layouts,
        instructions,
        events,
        policies,
        layout_metadata,
        compatibility_pairs,
        tooling_hints: strings(root, &["toolingHints", "tooling_hints"])?,
        contexts,
    })
}

/// Convert an OwnedProgramManifest to a ProgramManifest by leaking into static refs.
fn to_program_manifest(m: &OwnedProgramManifest) -> ProgramManifest {
    let layouts: Vec<LayoutManifest> = m.layouts.iter().map(|l| to_manifest(l).0).collect();

    let instructions: Vec<InstructionDescriptor> = m
        .instructions
        .iter()
        .map(|ix| {
            // Program-macro instruction summaries intentionally stay compact.
            // The Accounts-derived context is the authoritative source for
            // PDA and constraint metadata, so recover it by the ordered
            // account contract when a JSON manifest is loaded.
            let context = matching_owned_context(ix, &m.contexts);
            let args: Vec<ArgDescriptor> = ix
                .args
                .iter()
                .map(|a| ArgDescriptor {
                    name: leak_str(&a.name),
                    canonical_type: leak_str(&a.canonical_type),
                    size: a.size,
                    encoding: match a.encoding {
                        OwnedArgEncoding::Fixed => hopper_schema::ArgEncoding::Fixed,
                        OwnedArgEncoding::BoundedVec => hopper_schema::ArgEncoding::BoundedVec {
                            max_len: a.max_len,
                            element_size: a.element_size,
                        },
                        OwnedArgEncoding::BoundedString => {
                            hopper_schema::ArgEncoding::BoundedString { max_len: a.max_len }
                        }
                    },
                })
                .collect();
            let accounts: Vec<AccountEntry> = ix
                .accounts
                .iter()
                .enumerate()
                .map(|(account_index, account)| {
                    let context_account =
                        context.and_then(|context| context.accounts.get(account_index));
                    let layout_ref = if account.layout_ref.is_empty() {
                        context_account.map_or("", |context| context.layout_ref.as_str())
                    } else {
                        account.layout_ref.as_str()
                    };
                    let source_seeds = if account.seeds.is_empty() {
                        context_account.map(|context| context.seeds.as_slice())
                    } else {
                        Some(account.seeds.as_slice())
                    };
                    let seeds: Vec<&'static str> = source_seeds
                        .unwrap_or_default()
                        .iter()
                        .map(|seed| leak_str(seed))
                        .collect();
                    AccountEntry {
                        name: leak_str(&account.name),
                        writable: account.writable,
                        signer: account.signer,
                        layout_ref: leak_str(layout_ref),
                        seeds: Box::leak(seeds.into_boxed_slice()),
                    }
                })
                .collect();
            let capabilities: Vec<&'static str> =
                ix.capabilities.iter().map(|c| leak_str(c)).collect();
            // Carry the parsed write-set through verbatim. This is the exact
            // round-trip of codama's emitter: what codama serialized (byte
            // ranges, strict-write flag, lamport targets, CU estimate) is what
            // the loaded InstructionDescriptor now declares, so the CLI and the
            // compiled program can no longer disagree on the write authority.
            let write_ranges: Vec<WriteRange> = ix
                .write_ranges
                .iter()
                .map(|r| WriteRange::new(r.account_index, r.offset, r.size))
                .collect();
            let lamport_accounts: Vec<u8> = ix.lamport_accounts.clone();
            let parametric_write_ranges: Vec<hopper_schema::ParametricWriteRange> = ix
                .parametric_write_ranges
                .iter()
                .map(|range| {
                    hopper_schema::ParametricWriteRange::new(
                        range.account_index,
                        range.base_offset,
                        range.stride,
                        range.cell_size,
                        range.count,
                        range.argument_index,
                        leak_str(&range.argument),
                        leak_str(&range.segment),
                    )
                })
                .collect();
            InstructionDescriptor {
                name: leak_str(&ix.name),
                tag: ix.tag,
                discriminator: Box::leak(ix.discriminator.clone().into_boxed_slice()),
                args: Box::leak(args.into_boxed_slice()),
                accounts: Box::leak(accounts.into_boxed_slice()),
                remaining_accounts: ix
                    .remaining_accounts_max
                    .map(|max| hopper_schema::RemainingAccountsDescriptor { max }),
                capabilities: Box::leak(capabilities.into_boxed_slice()),
                policy_pack: leak_str(&ix.policy_pack),
                receipt_expected: ix.receipt_expected,
                strict_writes: ix.strict_writes,
                write_ranges: Box::leak(write_ranges.into_boxed_slice()),
                parametric_write_ranges: Box::leak(parametric_write_ranges.into_boxed_slice()),
                mutation_complete: ix.mutation_complete,
                lamport_accounts: Box::leak(lamport_accounts.into_boxed_slice()),
                cu_estimate: ix.cu_estimate,
            }
        })
        .collect();

    let events: Vec<EventDescriptor> = m
        .events
        .iter()
        .map(|e| {
            let fields: Vec<FieldDescriptor> = e
                .fields
                .iter()
                .map(|f| FieldDescriptor {
                    name: leak_str(&f.name),
                    canonical_type: leak_str(&f.canonical_type),
                    size: f.size,
                    offset: f.offset,
                    intent: f.intent,
                })
                .collect();
            EventDescriptor {
                name: leak_str(&e.name),
                tag: e.tag,
                fields: Box::leak(fields.into_boxed_slice()),
            }
        })
        .collect();

    let policies: Vec<PolicyDescriptor> = m
        .policies
        .iter()
        .map(|p| {
            let caps: Vec<&'static str> = p.capabilities.iter().map(|c| leak_str(c)).collect();
            let reqs: Vec<&'static str> = p.requirements.iter().map(|r| leak_str(r)).collect();
            let invs: Vec<&'static str> = p.invariants.iter().map(|i| leak_str(i)).collect();
            PolicyDescriptor {
                name: leak_str(&p.name),
                capabilities: Box::leak(caps.into_boxed_slice()),
                requirements: Box::leak(reqs.into_boxed_slice()),
                invariants: Box::leak(invs.into_boxed_slice()),
                receipt_profile: leak_str(&p.receipt_profile),
            }
        })
        .collect();

    let contexts: Vec<ContextDescriptor> = m
        .contexts
        .iter()
        .map(|ctx| {
            let accounts: Vec<ContextAccountDescriptor> = ctx
                .accounts
                .iter()
                .map(|account| {
                    let seeds: Vec<&'static str> =
                        account.seeds.iter().map(|seed| leak_str(seed)).collect();
                    let has_one: Vec<&'static str> =
                        account.has_one.iter().map(|h| leak_str(h)).collect();
                    ContextAccountDescriptor {
                        name: leak_str(&account.name),
                        kind: leak_str(&account.kind),
                        writable: account.writable,
                        signer: account.signer,
                        layout_ref: leak_str(&account.layout_ref),
                        policy_ref: leak_str(&account.policy_ref),
                        seeds: Box::leak(seeds.into_boxed_slice()),
                        optional: account.optional,
                        lifecycle: account.lifecycle,
                        payer: leak_str(&account.payer),
                        init_space: account.init_space,
                        has_one: Box::leak(has_one.into_boxed_slice()),
                        expected_address: leak_str(&account.expected_address),
                        expected_owner: leak_str(&account.expected_owner),
                    }
                })
                .collect();
            let policies: Vec<&'static str> =
                ctx.policies.iter().map(|policy| leak_str(policy)).collect();
            let mutation_classes: Vec<&'static str> = ctx
                .mutation_classes
                .iter()
                .map(|class_name| leak_str(class_name))
                .collect();

            let ctx_write_ranges: Vec<WriteRange> = ctx
                .write_ranges
                .iter()
                .map(|r| WriteRange::new(r.account_index, r.offset, r.size))
                .collect();
            let ctx_parametric_write_ranges: Vec<hopper_schema::ParametricWriteRange> = ctx
                .parametric_write_ranges
                .iter()
                .map(|range| {
                    hopper_schema::ParametricWriteRange::new(
                        range.account_index,
                        range.base_offset,
                        range.stride,
                        range.cell_size,
                        range.count,
                        range.argument_index,
                        leak_str(&range.argument),
                        leak_str(&range.segment),
                    )
                })
                .collect();
            let lamport_accounts = ctx.lamport_accounts.clone();
            let instructions: Vec<&'static str> =
                ctx.instructions.iter().map(|name| leak_str(name)).collect();
            ContextDescriptor {
                name: leak_str(&ctx.name),
                instructions: Box::leak(instructions.into_boxed_slice()),
                accounts: Box::leak(accounts.into_boxed_slice()),
                policies: Box::leak(policies.into_boxed_slice()),
                receipts_expected: ctx.receipts_expected,
                mutation_classes: Box::leak(mutation_classes.into_boxed_slice()),
                // Round-trip the context strict-write surface parsed from the
                // manifest (same fidelity contract as the instruction path).
                strict_writes: ctx.strict_writes,
                write_ranges: Box::leak(ctx_write_ranges.into_boxed_slice()),
                parametric_write_ranges: Box::leak(ctx_parametric_write_ranges.into_boxed_slice()),
                mutation_complete: ctx.mutation_complete,
                lamport_accounts: Box::leak(lamport_accounts.into_boxed_slice()),
            }
        })
        .collect();

    let layout_metadata: Vec<LayoutMetadata> = m
        .layout_metadata
        .iter()
        .map(|metadata| {
            let segment_roles: Vec<&'static str> = metadata
                .segment_roles
                .iter()
                .map(|value| leak_str(value))
                .collect();
            let invariant_pack: Vec<&'static str> = metadata
                .invariant_pack
                .iter()
                .map(|value| leak_str(value))
                .collect();
            let phase_requirements: Vec<&'static str> = metadata
                .phase_requirements
                .iter()
                .map(|value| leak_str(value))
                .collect();
            let manager_hints: Vec<&'static str> = metadata
                .manager_hints
                .iter()
                .map(|value| leak_str(value))
                .collect();
            LayoutMetadata {
                name: leak_str(&metadata.name),
                segment_roles: Box::leak(segment_roles.into_boxed_slice()),
                append_safe: metadata.append_safe,
                migration_required: metadata.migration_required,
                rebuildable: metadata.rebuildable,
                policy_pack: leak_str(&metadata.policy_pack),
                invariant_pack: Box::leak(invariant_pack.into_boxed_slice()),
                receipt_profile: leak_str(&metadata.receipt_profile),
                phase_requirements: Box::leak(phase_requirements.into_boxed_slice()),
                trust_profile: leak_str(&metadata.trust_profile),
                manager_hints: Box::leak(manager_hints.into_boxed_slice()),
            }
        })
        .collect();
    let compatibility_pairs: Vec<CompatibilityPair> = m
        .compatibility_pairs
        .iter()
        .map(|pair| CompatibilityPair {
            from_layout: leak_str(&pair.from_layout),
            from_version: pair.from_version,
            to_layout: leak_str(&pair.to_layout),
            to_version: pair.to_version,
            policy: pair.policy,
            backward_readable: pair.backward_readable,
        })
        .collect();
    let tooling_hints: Vec<&'static str> =
        m.tooling_hints.iter().map(|hint| leak_str(hint)).collect();

    ProgramManifest {
        name: leak_str(&m.name),
        version: leak_str(&m.version),
        description: leak_str(&m.description),
        layouts: Box::leak(layouts.into_boxed_slice()),
        instructions: Box::leak(instructions.into_boxed_slice()),
        events: Box::leak(events.into_boxed_slice()),
        policies: Box::leak(policies.into_boxed_slice()),
        layout_metadata: Box::leak(layout_metadata.into_boxed_slice()),
        compatibility_pairs: Box::leak(compatibility_pairs.into_boxed_slice()),
        tooling_hints: Box::leak(tooling_hints.into_boxed_slice()),
        contexts: Box::leak(contexts.into_boxed_slice()),
    }
}

fn matching_owned_context<'a>(
    instruction: &OwnedInstruction,
    contexts: &'a [OwnedContext],
) -> Option<&'a OwnedContext> {
    let instruction_name = canonical_manifest_name(&instruction.name);
    if let Some(named) = contexts
        .iter()
        .filter(|context| owned_context_matches_instruction(instruction, context))
        .find(|context| canonical_manifest_name(&context.name) == instruction_name)
    {
        return Some(named);
    }
    let mut candidates = contexts
        .iter()
        .filter(|context| owned_context_matches_instruction(instruction, context));
    let only = candidates.next()?;
    candidates.next().is_none().then_some(only)
}

fn owned_context_matches_instruction(
    instruction: &OwnedInstruction,
    context: &OwnedContext,
) -> bool {
    context.accounts.len() == instruction.accounts.len()
        && instruction.accounts.iter().zip(&context.accounts).all(
            |(instruction_account, context_account)| {
                instruction_account.name == context_account.name
                    && instruction_account.writable == context_account.writable
                    && instruction_account.signer == context_account.signer
                    && (instruction_account.layout_ref.is_empty()
                        || context_account.layout_ref.is_empty()
                        || instruction_account.layout_ref == context_account.layout_ref)
            },
        )
}

fn canonical_manifest_name(value: &str) -> String {
    value
        .bytes()
        .filter(u8::is_ascii_alphanumeric)
        .map(|byte| byte.to_ascii_lowercase() as char)
        .collect()
}

// ---------------------------------------------------------------------------
// Manager Command
// ---------------------------------------------------------------------------

fn cmd_tx_family(args: &[String]) {
    if args.is_empty() || matches!(args[0].as_str(), "--help" | "-h" | "help") {
        eprintln!("Usage: hopper tx <subcommand>");
        eprintln!();
        eprintln!("Subcommands:");
        eprintln!("  explain <signature>        Decode a confirmed transaction against");
        eprintln!("                             every touched Hopper program's manifest");
        eprintln!("  send --program <id> ...    Send one instruction with explicit metas");
        eprintln!("                             and hex data, signed locally (no Node)");
        eprintln!("  simulate <tx-base64>       Simulate a pre-built transaction");
        eprintln!("  submit <tx-base64>         Submit a pre-built transaction");
        return;
    }
    match args[0].as_str() {
        "explain" => cmd::tx_explain::cmd_tx_explain(&args[1..]),
        "send" => cmd::tx_send::cmd_tx_send(&args[1..]),
        "simulate" => cmd::meta::cmd_tx_simulate(&args[1..]),
        "submit" => cmd::meta::cmd_tx_submit(&args[1..]),
        other => {
            eprintln!("Unknown tx subcommand: {other}");
            process::exit(1);
        }
    }
}

fn cmd_manager(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper manager <subcommand> [args]");
        eprintln!();
        eprintln!("Subcommands:");
        eprintln!("  summary <manifest|--program-id ...>     Program overview");
        eprintln!("  identify <manifest|--program-id ...> <hex>  Identify account type");
        eprintln!("  decode <manifest|--program-id ...> <hex>    Decode all fields with values");
        eprintln!("  instruction <manifest|--program-id ...> <tag|name>  Instruction details and policies");
        eprintln!("  layouts <manifest|--program-id ...>     List all layouts with fields");
        eprintln!("  policies <manifest|--program-id ...>    List policy packs with mappings");
        eprintln!("  events <manifest|--program-id ...>      List events with fields");
        eprintln!("  fingerprints <manifest|--program-id ...>  Show all layout fingerprints");
        eprintln!("  compat <manifest|--program-id ...> <hex-old> <hex-new>  Compare two account versions");
        eprintln!("  receipt <hex-64-or-72-bytes>             Decode a receipt from wire bytes");
        eprintln!("  explain <manifest|--program-id ...>     Aggregated human-readable summary");
        eprintln!("  diff <manifest|--program-id ...> <hex-before> <hex-after>  Semantic field-level diff");
        eprintln!("  simulate <manifest|--program-id ...> <instruction>  Preview instruction requirements");
        eprintln!("  fetch <program-id> [--rpc <url>]        Fetch manifest from on-chain");
        eprintln!("  interactive <manifest|--program-id ...>  Interactive terminal explorer");
        process::exit(1);
    }

    match args[0].as_str() {
        "summary" => cmd_manager_summary(&args[1..]),
        "identify" => cmd_manager_identify(&args[1..]),
        "decode" => cmd_manager_decode(&args[1..]),
        "instruction" => cmd_manager_instruction(&args[1..]),
        "layouts" => cmd_manager_layouts(&args[1..]),
        "policies" => cmd_manager_policies(&args[1..]),
        "events" => cmd_manager_events(&args[1..]),
        "fingerprints" => cmd_manager_fingerprints(&args[1..]),
        "compat" => cmd_manager_compat(&args[1..]),
        "receipt" => cmd_manager_receipt(&args[1..]),
        "explain" => cmd_manager_explain(&args[1..]),
        "diff" => cmd_manager_diff(&args[1..]),
        "fetch" => cmd_manager_fetch(&args[1..]),
        "simulate" => cmd_manager_simulate(&args[1..]),
        "invoke" => cmd::manager_invoke::cmd_manager_invoke(&args[1..]),
        "crank" => cmd::manager_invoke::cmd_manager_crank(&args[1..]),
        "accounts" => {
            // Route `accounts read <pk>` to meta.rs, everything else
            // (list, future subs) to the full accounts-command tree.
            if matches!(args.get(1).map(String::as_str), Some("read")) {
                cmd::meta::cmd_manager_accounts_read(&args[2..]);
            } else {
                cmd::manager_accounts::cmd_manager_accounts(&args[1..]);
            }
        }
        "interactive" | "ui" => cmd_interactive(&args[1..]),
        other => {
            eprintln!("Unknown manager subcommand: {}", other);
            process::exit(1);
        }
    }
}

// ---------------------------------------------------------------------------
// On-Chain Fetch Commands
// ---------------------------------------------------------------------------

/// Parse common fetch flags from args: (program_id, rpc_override, json_mode)
fn parse_fetch_args(args: &[String]) -> (String, Option<String>, bool) {
    let mut program_id = None;
    let mut rpc_override = None;
    let mut json_mode = false;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--rpc" => {
                if i + 1 >= args.len() {
                    eprintln!("--rpc requires a URL argument");
                    process::exit(1);
                }
                rpc_override = Some(args[i + 1].clone());
                i += 2;
            }
            "--json" => {
                json_mode = true;
                i += 1;
            }
            other => {
                if program_id.is_none() {
                    program_id = Some(other.to_string());
                } else {
                    eprintln!("Unexpected argument: {}", other);
                    process::exit(1);
                }
                i += 1;
            }
        }
    }
    let pid = match program_id {
        Some(p) => p,
        None => {
            eprintln!("Missing required <program-id> argument");
            process::exit(1);
        }
    };
    (pid, rpc_override, json_mode)
}

/// Fetch an application-provisioned legacy Hopper manifest PDA, returning its
/// raw JSON string. This does not discover Program Metadata.
fn fetch_manifest_json(program_id_str: &str, rpc_override: Option<&str>) -> String {
    let rpc_url = rpc::resolve_rpc_url(rpc_override);
    let program_id = match rpc::decode_pubkey(program_id_str) {
        Ok(pk) => pk,
        Err(e) => {
            eprintln!("Invalid program ID: {}", e);
            process::exit(1);
        }
    };

    let (pda, bump) = match rpc::find_program_address(&[hopper_schema::MANIFEST_SEED], &program_id)
    {
        Some(result) => result,
        None => {
            eprintln!("Failed to derive manifest PDA (no valid bump found)");
            process::exit(1);
        }
    };

    let pda_b58 = rpc::encode_pubkey(&pda);
    eprintln!("Legacy manifest PDA: {} (bump {})", pda_b58, bump);
    eprintln!("RPC endpoint: {}", rpc_url);
    eprintln!();

    let account = match rpc::get_account_info(&rpc_url, &pda_b58) {
        Ok(Some(info)) => info,
        Ok(None) => {
            eprintln!(
                "No application-provisioned legacy manifest found at PDA {}",
                pda_b58
            );
            eprintln!();
            eprintln!(
                "The program {} does not have a legacy Hopper manifest at MANIFEST_SEED.",
                program_id_str
            );
            eprintln!("Hopper has no generic publisher for this legacy manifest PDA.");
            eprintln!("Use an application-specific publisher, or pass a local manifest file.");
            process::exit(1);
        }
        Err(e) => {
            eprintln!("RPC error: {}", e);
            process::exit(1);
        }
    };

    let manifest = match rpc::decode_manifest_account(&account.data) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("Failed to decode manifest account: {}", e);
            eprintln!("Account owner: {}", account.owner);
            eprintln!("Account size:  {} bytes", account.data.len());
            process::exit(1);
        }
    };

    eprintln!("Manifest version: {}", manifest.version);
    eprintln!("JSON size:        {} bytes", manifest.json.len());
    eprintln!();

    manifest.json
}

fn cmd_fetch(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper fetch <program-id> [--rpc <url>] [--json]");
        eprintln!();
        eprintln!("Fetch an application-provisioned legacy Hopper manifest PDA and display it.");
        eprintln!(
            "This does not discover Solana Program Metadata; Hopper ships no generic publisher."
        );
        eprintln!();
        eprintln!("Options:");
        eprintln!("  --rpc <url>  Solana RPC endpoint (default: SOLANA_RPC_URL env or mainnet)");
        eprintln!("  --json       Output raw manifest JSON instead of summary");
        process::exit(1);
    }

    let (program_id, rpc_override, json_mode) = parse_fetch_args(args);
    let json = fetch_manifest_json(&program_id, rpc_override.as_deref());

    if json_mode {
        println!("{}", json);
    } else {
        let prog = load_program_manifest_from_json(&json);
        println!("{}", prog);
    }
}

fn cmd_manager_fetch(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper manager fetch <program-id> [--rpc <url>]");
        eprintln!();
        eprintln!("Fetch a program's Hopper manifest from on-chain and show manager summary.");
        process::exit(1);
    }

    let (program_id, rpc_override, _) = parse_fetch_args(args);
    let json = fetch_manifest_json(&program_id, rpc_override.as_deref());
    let prog = load_program_manifest_from_json(&json);
    println!("{}", prog);
}

fn cmd_interactive(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper interactive <manifest>");
        eprintln!("       hopper interactive --program-id <program-id> [--rpc <url>]");
        eprintln!("       hopper manager interactive <manifest>");
        eprintln!("       hopper manager interactive --program-id <program-id> [--rpc <url>]");
        eprintln!("       hopper ui <manifest>");
        eprintln!();
        eprintln!("Launch an interactive terminal UI for exploring a program manifest.");
        eprintln!("Manifest can be inline JSON, @path/to/file.json, or fetched from a program ID.");
        process::exit(1);
    }

    let (prog, _) = load_program_manifest_source(
        args,
        "hopper interactive <manifest> | --program-id <program-id> [--rpc <url>]",
    );
    let mut session = interactive::Session::new(&prog);
    if let Err(e) = session.run() {
        eprintln!("Interactive session error: {}", e);
        process::exit(1);
    }
}

fn load_program_manifest(arg: &str) -> ProgramManifest {
    let resolved = if std::path::Path::new(arg).is_file() {
        std::fs::read_to_string(arg).unwrap_or_else(|error| {
            eprintln!("Could not read manifest file '{arg}': {error}");
            process::exit(1);
        })
    } else {
        resolve_manifest_arg(arg)
    };
    load_program_manifest_from_json(&resolved)
}

fn load_program_manifest_from_json(json: &str) -> ProgramManifest {
    match parse_program_manifest_json(json) {
        Ok(m) => to_program_manifest(&m),
        Err(e) => {
            eprintln!("Program manifest parse error: {}", e);
            process::exit(1);
        }
    }
}

fn load_program_manifest_source(args: &[String], usage: &str) -> (ProgramManifest, usize) {
    if args.is_empty() {
        eprintln!("Usage: {usage}");
        process::exit(1);
    }

    if args[0] != "--program-id" {
        return (load_program_manifest(&args[0]), 1);
    }

    if args.len() < 2 {
        eprintln!("Usage: {usage}");
        eprintln!();
        eprintln!("--program-id requires a base58 program address.");
        process::exit(1);
    }

    let mut rpc_override = None;
    let mut consumed = 2;
    while consumed < args.len() {
        match args[consumed].as_str() {
            "--rpc" => {
                if consumed + 1 >= args.len() {
                    eprintln!("Usage: {usage}");
                    eprintln!();
                    eprintln!("--rpc requires a URL argument.");
                    process::exit(1);
                }
                rpc_override = Some(args[consumed + 1].clone());
                consumed += 2;
            }
            _ => break,
        }
    }

    let json = fetch_manifest_json(&args[1], rpc_override.as_deref());
    (load_program_manifest_from_json(&json), consumed)
}

fn cmd_manager_summary(args: &[String]) {
    let (prog, _) = load_program_manifest_source(
        args,
        "hopper manager summary <manifest> | --program-id <program-id> [--rpc <url>]",
    );
    println!("{}", prog);
}

fn cmd_manager_identify(args: &[String]) {
    let usage = "hopper manager identify <manifest> <hex-data> | --program-id <program-id> [--rpc <url>] <hex-data>";
    let (prog, consumed) = load_program_manifest_source(args, usage);
    if args.len() <= consumed {
        eprintln!("Usage: {usage}");
        process::exit(1);
    }
    let data = match hex_decode(&args[consumed]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    if data.len() < 16 {
        eprintln!(
            "Data too short for Hopper header (need 16 bytes, got {})",
            data.len()
        );
        process::exit(1);
    }

    let header = require_header(&data);
    println!("=== Account Identification ===");
    println!("  Data size    : {} bytes", data.len());
    println!("  Header disc  : {}", header.disc);
    println!("  Header ver   : {}", header.version);
    println!("  Layout ID    : {}", hex_encode(&header.layout_id));
    println!();

    match prog.identify_from_data(&data) {
        Some(layout) => {
            println!("  MATCH: {} v{}", layout.name, layout.version);
            println!("  Expected size: {} bytes", layout.total_size);
            println!("  Fields       : {}", layout.field_count);
            if data.len() != layout.total_size {
                println!(
                    "  WARNING: data size ({}) != expected size ({})",
                    data.len(),
                    layout.total_size
                );
            }
            println!();
            println!("Use 'hopper manager decode' to see field values.");
        }
        None => {
            println!("  NO MATCH: This account does not match any layout in the manifest.");
            println!();
            println!("Known layouts:");
            for l in prog.layouts.iter() {
                println!(
                    "    {} v{} (disc={}, id={})",
                    l.name,
                    l.version,
                    l.disc,
                    hex_encode(&l.layout_id)
                );
            }
        }
    }
}

fn cmd_manager_decode(args: &[String]) {
    decode_layout_from_source(
        args,
        "hopper manager decode <manifest> <hex-data> | --program-id <program-id> [--rpc <url>] <hex-data>",
        "Account Decode",
    );
}

fn decode_layout_from_source(args: &[String], usage: &str, heading: &str) {
    let (prog, consumed) = load_program_manifest_source(args, usage);
    if args.len() <= consumed {
        eprintln!("Usage: {usage}");
        process::exit(1);
    }
    let data = match hex_decode(&args[consumed]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    if data.len() < 16 {
        eprintln!("Data too short for Hopper header");
        process::exit(1);
    }

    let header = require_header(&data);

    let layout = match prog.identify_from_data(&data) {
        Some(layout) => layout,
        None => {
            eprintln!(
                "Cannot identify account type (disc={}, layout_id={})",
                header.disc,
                hex_encode(&header.layout_id)
            );
            eprintln!("Use 'hopper manager identify' for diagnostics.");
            process::exit(1);
        }
    };

    println!("=== {}: {} v{} ===", heading, layout.name, layout.version);
    println!(
        "  Size: {} bytes (expected {})",
        data.len(),
        layout.total_size
    );
    println!(
        "  Flags: {} (0x{:04x})",
        format_flags(header.flags),
        header.flags
    );
    println!("  Disc : {}", header.disc);
    println!("  Wire : {}", hex_encode(&layout.layout_id));
    println!();

    if layout.field_count == 0 {
        println!("  (no field descriptors in manifest)");
        return;
    }

    let (count, fields) = decode_account_fields::<64>(&data, layout);
    let mut buf = [0u8; 128];
    println!(
        "  {:>4}  {:>20}  {:>12}  {:>6}  {:>6}  Value",
        "#", "Field", "Type", "Offset", "Size"
    );
    println!("  {}", "-".repeat(76));
    for (i, slot) in fields.iter().enumerate().take(count) {
        if let Some(ref field) = slot {
            let val_len = field.format_value(&mut buf);
            let val_str = std::str::from_utf8(&buf[..val_len]).unwrap_or("???");
            println!(
                "  {:>4}  {:>20}  {:>12}  {:>6}  {:>6}  {}",
                i, field.name, field.canonical_type, field.offset, field.size, val_str,
            );
        }
    }

    println!();
    println!("  Decoded {}/{} fields.", count, layout.field_count);
}

fn cmd_manager_instruction(args: &[String]) {
    let usage = "hopper manager instruction <manifest> <tag|name> | --program-id <program-id> [--rpc <url>] <tag|name>";
    let (prog, consumed) = load_program_manifest_source(args, usage);
    if args.len() <= consumed {
        eprintln!("Usage: {usage}");
        process::exit(1);
    }
    let tag: u8 = match args[consumed].parse() {
        Ok(t) => t,
        Err(_) => {
            // Try matching by name
            let name = &args[consumed];
            let mut found = None;
            for ix in prog.instructions.iter() {
                if ix.name == name.as_str() {
                    found = Some(ix.tag);
                    break;
                }
            }
            match found {
                Some(t) => t,
                None => {
                    eprintln!("Unknown instruction: '{}'. Known:", name);
                    for ix in prog.instructions.iter() {
                        eprintln!("  {}  {}", ix.tag, ix.name);
                    }
                    process::exit(1);
                }
            }
        }
    };

    let ix = match prog.find_instruction(tag) {
        Some(ix) => ix,
        None => {
            eprintln!("No instruction with tag {}", tag);
            process::exit(1);
        }
    };

    println!("=== Instruction: {} (tag {}) ===", ix.name, ix.tag);
    println!();

    if !ix.accounts.is_empty() {
        println!("  Accounts ({}):", ix.accounts.len());
        for (i, acct) in ix.accounts.iter().enumerate() {
            let mut flags = Vec::new();
            if acct.writable {
                flags.push("writable");
            }
            if acct.signer {
                flags.push("signer");
            }
            let flag_str = if flags.is_empty() {
                "read-only".to_string()
            } else {
                flags.join(", ")
            };
            let layout_str = if acct.layout_ref.is_empty() {
                ""
            } else {
                acct.layout_ref
            };
            if layout_str.is_empty() {
                println!("    [{}] {:20} ({})", i, acct.name, flag_str);
            } else {
                println!(
                    "    [{}] {:20} ({}) -> {}",
                    i, acct.name, flag_str, layout_str
                );
            }
        }
        println!();
    }

    if !ix.args.is_empty() {
        println!("  Arguments ({}):", ix.args.len());
        for arg in ix.args.iter() {
            println!(
                "    {:20} : {} ({} bytes)",
                arg.name, arg.canonical_type, arg.size
            );
        }
        println!();
    }

    if !ix.capabilities.is_empty() {
        println!("  Capabilities:");
        for cap in ix.capabilities.iter() {
            println!("    - {}", cap);
        }
        println!();
    }

    if !ix.policy_pack.is_empty() {
        println!("  Policy pack: {}", ix.policy_pack);
        if let Some(policy) = prog.find_policy(ix.policy_pack) {
            println!("    Requirements:");
            for req in policy.requirements.iter() {
                println!("      - {}", req);
            }
        }
        println!();
    }

    println!(
        "  Receipt expected: {}",
        if ix.receipt_expected { "YES" } else { "NO" }
    );
}

fn cmd_manager_layouts(args: &[String]) {
    let (prog, _) = load_program_manifest_source(
        args,
        "hopper manager layouts <manifest> | --program-id <program-id> [--rpc <url>]",
    );
    // Rendering lives in the hopper-manager library so other tooling
    // (custom UIs, editor plugins, web explorers) can reuse the exact
    // same output without depending on the CLI binary.
    print!("{}", hopper_manager::summary::layouts_report(&prog));
}

fn cmd_manager_policies(args: &[String]) {
    let (prog, _) = load_program_manifest_source(
        args,
        "hopper manager policies <manifest> | --program-id <program-id> [--rpc <url>]",
    );

    if prog.policies.is_empty() {
        println!("No policies defined in manifest.");
        return;
    }

    println!("=== Policy Packs ({}) ===", prog.policies.len());
    println!();

    for policy in prog.policies.iter() {
        println!("  {}", policy.name);
        if !policy.capabilities.is_empty() {
            println!("    Capabilities:");
            for cap in policy.capabilities.iter() {
                println!("      - {}", cap);
            }
        }
        if !policy.requirements.is_empty() {
            println!("    Requirements:");
            for req in policy.requirements.iter() {
                println!("      - {}", req);
            }
        }
        println!();
    }

    // Show which instructions use which policies
    println!("  Instruction -> Policy mapping:");
    for ix in prog.instructions.iter() {
        if !ix.policy_pack.is_empty() {
            println!("    {:20} -> {}", ix.name, ix.policy_pack);
        }
    }
}

fn cmd_manager_events(args: &[String]) {
    let (prog, _) = load_program_manifest_source(
        args,
        "hopper manager events <manifest> | --program-id <program-id> [--rpc <url>]",
    );

    if prog.events.is_empty() {
        println!("No events defined in manifest.");
        return;
    }

    println!("=== Events ({}) ===", prog.events.len());
    println!();

    for event in prog.events.iter() {
        println!("  {} (tag {})", event.name, event.tag);
        if event.fields.is_empty() {
            println!("    (no fields)");
        } else {
            println!("    Fields ({}):", event.fields.len());
            for f in event.fields.iter() {
                println!(
                    "      [{:>3}..{:>3}] {:20} : {} ({} bytes)",
                    f.offset,
                    f.offset + f.size,
                    f.name,
                    f.canonical_type,
                    f.size,
                );
            }
        }
        println!();
    }

    // Show which instructions emit which events
    let has_receipt_ix: Vec<_> = prog
        .instructions
        .iter()
        .filter(|ix| ix.receipt_expected)
        .collect();
    if !has_receipt_ix.is_empty() {
        println!("  Instructions with receipt emissions:");
        for ix in &has_receipt_ix {
            println!("    {:20} (tag {})", ix.name, ix.tag);
        }
    }
}

fn cmd_manager_fingerprints(args: &[String]) {
    let (prog, _) = load_program_manifest_source(
        args,
        "hopper manager fingerprints <manifest> | --program-id <program-id> [--rpc <url>]",
    );

    println!("=== Layout Fingerprints ===");
    println!();
    println!(
        "  {:>20}  {:>3}  {:>3}  {:>6}  Layout ID",
        "Name", "D", "V", "Size"
    );
    println!("  {}", "-".repeat(60));

    for layout in prog.layouts.iter() {
        println!(
            "  {:>20}  {:>3}  {:>3}  {:>6}  {}",
            layout.name,
            layout.disc,
            layout.version,
            layout.total_size,
            hex_encode(&layout.layout_id),
        );
    }

    // Check for disc collisions
    println!();
    let mut seen_discs = std::collections::HashMap::new();
    for layout in prog.layouts.iter() {
        if let Some(prev) = seen_discs.insert(layout.disc, layout.name) {
            println!(
                "  WARNING: Disc {} shared by '{}' and '{}'",
                layout.disc, prev, layout.name
            );
        }
    }

    // Check for layout_id collisions
    let mut seen_ids = std::collections::HashMap::new();
    for layout in prog.layouts.iter() {
        let id_hex = hex_encode(&layout.layout_id);
        if let Some(prev) = seen_ids.insert(id_hex.clone(), layout.name) {
            println!(
                "  WARNING: Layout ID {} shared by '{}' and '{}'",
                id_hex, prev, layout.name
            );
        }
    }

    if seen_discs.len() == prog.layouts.len() && seen_ids.len() == prog.layouts.len() {
        println!("  All discriminators and layout IDs are unique.");
    }
}

fn cmd_manager_compat(args: &[String]) {
    let usage = "hopper manager compat <manifest> <hex-old> <hex-new> | --program-id <program-id> [--rpc <url>] <hex-old> <hex-new>";
    let (prog, consumed) = load_program_manifest_source(args, usage);
    if args.len() < consumed + 2 {
        eprintln!("Usage: {usage}");
        eprintln!("  Compares two account data blobs and reports compatibility.");
        process::exit(1);
    }
    let old_data = match hex_decode(&args[consumed]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error (old): {}", e);
            process::exit(1);
        }
    };
    let new_data = match hex_decode(&args[consumed + 1]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error (new): {}", e);
            process::exit(1);
        }
    };

    if old_data.len() < 16 || new_data.len() < 16 {
        eprintln!("Both data blobs must be at least 16 bytes (header).");
        process::exit(1);
    }

    let old_header = require_header(&old_data);
    let new_header = require_header(&new_data);

    println!("=== Compatibility Analysis ===");
    println!();
    println!(
        "  Old: disc={}, ver={}, layout_id={}, size={}",
        old_header.disc,
        old_header.version,
        hex_encode(&old_header.layout_id),
        old_data.len()
    );
    println!(
        "  New: disc={}, ver={}, layout_id={}, size={}",
        new_header.disc,
        new_header.version,
        hex_encode(&new_header.layout_id),
        new_data.len()
    );
    println!();

    if old_header.disc != new_header.disc {
        println!("  RESULT: Different discriminators. These are different account types.");
        return;
    }

    if old_header.layout_id == new_header.layout_id {
        println!("  RESULT: Same layout ID. Same schema version, no compat issue.");
        return;
    }

    // Try to find both layouts in the manifest
    let old_layout = prog.identify_from_data(&old_data);
    let new_layout = prog.identify_from_data(&new_data);

    match (old_layout, new_layout) {
        (Some(ol), Some(nl)) => {
            println!("  Old layout: {} v{}", ol.name, ol.version);
            println!("  New layout: {} v{}", nl.name, nl.version);

            let report = compare_fields::<64>(ol, nl);
            println!();
            println!("  Field-level changes:");
            for i in 0..report.len() {
                if let Some(entry) = report.get(i) {
                    let status = match entry.status {
                        FieldCompat::Identical => "identical",
                        FieldCompat::Changed => "CHANGED",
                        FieldCompat::Added => "added",
                        FieldCompat::Removed => "REMOVED",
                    };
                    println!("    {:20} : {}", entry.name, status);
                }
            }
            let verdict = CompatibilityVerdict::between(ol, nl);
            println!();
            println!("  Verdict: {}", verdict.name());
            match verdict {
                CompatibilityVerdict::Identical => {
                    println!("  RESULT: Identical layout. No changes.");
                }
                CompatibilityVerdict::WireCompatible => {
                    println!("  RESULT: Wire-compatible. Byte layout identical, semantic metadata differs.");
                }
                CompatibilityVerdict::AppendSafe => {
                    println!(
                        "  RESULT: Append-safe. Old field prefix preserved, no migration needed."
                    );
                }
                CompatibilityVerdict::MigrationRequired => {
                    println!(
                        "  RESULT: Migration required. Data is not directly backward-readable."
                    );
                }
                CompatibilityVerdict::Incompatible => {
                    println!("  RESULT: Incompatible. Breaking change detected.");
                }
            }
        }
        (Some(ol), None) => {
            println!("  Old layout identified: {} v{}", ol.name, ol.version);
            println!("  New layout: NOT IN MANIFEST");
            println!("  RESULT: Cannot determine compatibility (new layout unknown).");
        }
        (None, Some(nl)) => {
            println!("  Old layout: NOT IN MANIFEST");
            println!("  New layout identified: {} v{}", nl.name, nl.version);
            println!("  RESULT: Cannot determine compatibility (old layout unknown).");
        }
        (None, None) => {
            println!("  Neither layout found in manifest.");
            println!("  RESULT: Cannot determine compatibility.");
        }
    }
}

fn cmd_manager_receipt(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: hopper manager receipt <hex-64-or-72-bytes>");
        process::exit(1);
    }
    let data = match hex_decode(&args[0]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error: {}", e);
            process::exit(1);
        }
    };

    if !valid_receipt_len(data.len()) {
        eprintln!(
            "Receipt data must be exactly {} legacy bytes or at least {} current bytes (got {})",
            RECEIPT_WIRE_SIZE_LEGACY,
            RECEIPT_WIRE_SIZE,
            data.len()
        );
        process::exit(1);
    }

    let r = match DecodedReceipt::from_bytes(&data) {
        Some(r) => r,
        None => {
            eprintln!("Failed to decode receipt");
            process::exit(1);
        }
    };

    let phase = Phase::from_tag(r.phase);
    let impact = CompatImpact::from_tag(r.compat_impact);

    println!("=== State Receipt ===");
    println!(
        "  Wire format         : {}",
        if data.len() == RECEIPT_WIRE_SIZE_LEGACY {
            "legacy 64-byte"
        } else {
            "current 72-byte"
        }
    );
    println!();
    println!("  Layout ID           : {}", hex_encode(&r.layout_id));
    println!("  Phase               : {} ({})", phase.name(), r.phase);
    println!("  Committed           : {}", r.committed);
    println!();
    println!("  Changed fields mask : 0x{:016x}", r.changed_fields);
    println!("  Changed bytes       : {}", r.changed_bytes);
    println!("  Changed regions     : {}", r.changed_regions);
    println!(
        "  Was resized         : {} ({} -> {} bytes)",
        r.was_resized, r.old_size, r.new_size
    );
    println!();
    println!(
        "  Before fingerprint  : {}",
        hex_encode(&r.before_fingerprint)
    );
    println!(
        "  After fingerprint   : {}",
        hex_encode(&r.after_fingerprint)
    );
    let fp_changed = r.before_fingerprint != r.after_fingerprint;
    println!("  Fingerprint changed : {}", fp_changed);
    println!();
    println!("  Invariants passed   : {}", r.invariants_passed);
    println!("  Invariants checked  : {}", r.invariants_checked);
    println!(
        "  CPI invoked         : {} ({} calls)",
        r.cpi_invoked, r.cpi_count
    );
    println!("  Journal appends     : {}", r.journal_appends);
    println!("  Segment mask        : 0x{:04x}", r.segment_changed_mask);
    println!("  Policy flags        : 0x{:08x}", r.policy_flags);
    println!();
    println!(
        "  Compat impact       : {} ({})",
        impact.name(),
        r.compat_impact
    );
    println!("  Validation bundle   : {}", r.validation_bundle_id);
    println!("  Migration flags     : 0b{:08b}", r.migration_flags);
    if r.migration_flags & 0x01 != 0 {
        println!("    - Migration triggered");
    }
    if r.migration_flags & 0x02 != 0 {
        println!("    - Realloc performed");
    }
    if r.migration_flags & 0x04 != 0 {
        println!("    - Schema version bumped");
    }
    println!();
    println!("  Failure recorded    : {}", r.had_failure);
    println!(
        "  Failure stage       : {}",
        receipt_failure_stage_name(r.failure_stage)
    );
    println!("  Failed invariant    : 0x{:02x}", r.failed_invariant_idx);
    println!("  Failed error code   : {}", r.failed_error_code);
}

fn cmd_manager_explain(args: &[String]) {
    if args.is_empty() {
        eprintln!(
            "Usage: hopper manager explain <manifest> | --program-id <program-id> [--rpc <url>]"
        );
        eprintln!("  Aggregated human-readable summary of the program manifest.");
        process::exit(1);
    }
    let (prog, _) = load_program_manifest_source(
        args,
        "hopper manager explain <manifest> | --program-id <program-id> [--rpc <url>]",
    );

    println!("=== Program Explanation ===");
    println!();
    println!("  Name        : {}", prog.name);
    println!("  Version     : {}", prog.version);
    println!("  Description : {}", prog.description);
    println!();

    // Layouts
    println!("  Layouts ({})", prog.layouts.len());
    for l in prog.layouts.iter() {
        let fp = LayoutFingerprint::from_manifest(l);
        println!(
            "    {} v{} | disc={} | {} fields | {} bytes | wire={} sem={}",
            l.name,
            l.version,
            l.disc,
            l.field_count,
            l.total_size,
            hex_encode(&fp.wire_hash),
            hex_encode(&fp.semantic_hash)
        );
    }
    println!();

    // Instructions
    println!("  Instructions ({})", prog.instructions.len());
    for ix in prog.instructions.iter() {
        println!(
            "    [{}] {} | {} args | {} accounts",
            ix.tag,
            ix.name,
            ix.args.len(),
            ix.accounts.len()
        );
    }
    println!();

    // Policies
    println!("  Policies ({})", prog.policies.len());
    for p in prog.policies.iter() {
        println!(
            "    {} | {}cap {}req {}inv | receipt={}",
            p.name,
            p.capabilities.len(),
            p.requirements.len(),
            p.invariants.len(),
            p.receipt_profile
        );
    }
    println!();

    // Events
    println!("  Events ({})", prog.events.len());
    for ev in prog.events.iter() {
        println!("    [{}] {} | {} fields", ev.tag, ev.name, ev.fields.len());
    }
    println!();

    // Compat pairs
    if !prog.compatibility_pairs.is_empty() {
        println!("  Compatibility Rules ({})", prog.compatibility_pairs.len());
        for cp in prog.compatibility_pairs.iter() {
            let policy = match cp.policy {
                MigrationPolicy::NoOp => "noop",
                MigrationPolicy::AppendOnly => "append-only",
                MigrationPolicy::RequiresMigration => "migration",
                MigrationPolicy::Incompatible => "incompatible",
            };
            println!(
                "    {} v{} → {} v{} | {} | backward={}",
                cp.from_layout,
                cp.from_version,
                cp.to_layout,
                cp.to_version,
                policy,
                cp.backward_readable
            );
        }
        println!();
    }

    // Tooling hints
    if !prog.tooling_hints.is_empty() {
        println!("  Tooling Hints");
        for h in prog.tooling_hints.iter() {
            println!("    - {}", h);
        }
    }
}

fn cmd_manager_diff(args: &[String]) {
    let usage = "hopper manager diff <manifest> <hex-before> <hex-after> | --program-id <program-id> [--rpc <url>] <hex-before> <hex-after>";
    let (prog, consumed) = load_program_manifest_source(args, usage);
    if args.len() < consumed + 2 {
        eprintln!("Usage: {usage}");
        eprintln!("  Semantic field-level diff between two account states.");
        process::exit(1);
    }
    let before = match hex_decode(&args[consumed]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error (before): {}", e);
            process::exit(1);
        }
    };
    let after = match hex_decode(&args[consumed + 1]) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Hex decode error (after): {}", e);
            process::exit(1);
        }
    };

    if before.len() < 16 || after.len() < 16 {
        eprintln!("Both data blobs must be at least 16 bytes (header).");
        process::exit(1);
    }

    let before_header = require_header(&before);
    let after_header = require_header(&after);

    println!("=== Semantic Diff ===");
    println!();

    let before_layout = prog.identify_from_data(&before);
    let after_layout = prog.identify_from_data(&after);

    match (before_layout, after_layout) {
        (Some(bl), Some(al)) => {
            println!("  Before : {} v{} (disc={})", bl.name, bl.version, bl.disc);
            println!("  After  : {} v{} (disc={})", al.name, al.version, al.disc);
            println!();

            // Verdict
            let verdict = CompatibilityVerdict::between(bl, al);
            println!("  Verdict: {}", verdict.name());
            println!();

            // Field-level diff with values
            let (_bc, before_fields) = decode_account_fields::<64>(&before, bl);
            let (_ac, after_fields) = decode_account_fields::<64>(&after, al);

            println!("  Field-level changes:");
            // Compare shared fields by index
            let max_fields = std::cmp::max(bl.field_count, al.field_count);
            let mut diffs_found = 0usize;
            for i in 0..max_fields {
                if i < bl.field_count && i < al.field_count {
                    let bf = &bl.fields[i];
                    let af = &al.fields[i];
                    let bv = before_fields[i].as_ref().map(|f| f.raw).unwrap_or(&[]);
                    let av = after_fields[i].as_ref().map(|f| f.raw).unwrap_or(&[]);
                    if bv != av || bf.name != af.name || bf.canonical_type != af.canonical_type {
                        println!(
                            "    {:20} : {} → {}",
                            bf.name,
                            hex_encode(bv),
                            hex_encode(av)
                        );
                        diffs_found += 1;
                    }
                } else if i < al.field_count {
                    let af = &al.fields[i];
                    let av = after_fields[i].as_ref().map(|f| f.raw).unwrap_or(&[]);
                    println!("    {:20} : (added) = {}", af.name, hex_encode(av));
                    diffs_found += 1;
                } else if i < bl.field_count {
                    let bf = &bl.fields[i];
                    println!("    {:20} : (removed)", bf.name);
                    diffs_found += 1;
                }
            }

            if diffs_found == 0 {
                println!("    (no field-level differences)");
            }

            // Size diff
            if before.len() != after.len() {
                println!();
                println!(
                    "  Size: {} → {} bytes ({}{})",
                    before.len(),
                    after.len(),
                    if after.len() > before.len() { "+" } else { "" },
                    after.len() as isize - before.len() as isize
                );
            }
        }
        (Some(bl), None) => {
            println!("  Before : {} v{}", bl.name, bl.version);
            println!(
                "  After  : UNKNOWN LAYOUT (id={})",
                hex_encode(&after_header.layout_id)
            );
            println!("  Cannot compute semantic diff: after layout not in manifest.");
        }
        (None, Some(al)) => {
            println!(
                "  Before : UNKNOWN LAYOUT (id={})",
                hex_encode(&before_header.layout_id)
            );
            println!("  After  : {} v{}", al.name, al.version);
            println!("  Cannot compute semantic diff: before layout not in manifest.");
        }
        (None, None) => {
            println!(
                "  Before : UNKNOWN LAYOUT (id={})",
                hex_encode(&before_header.layout_id)
            );
            println!(
                "  After  : UNKNOWN LAYOUT (id={})",
                hex_encode(&after_header.layout_id)
            );
            println!("  Cannot compute semantic diff: neither layout is in the manifest.");
        }
    }
}

fn cmd_manager_simulate(args: &[String]) {
    let usage = "hopper manager simulate <manifest> <instruction-name|tag> | --program-id <program-id> [--rpc <url>] <instruction-name|tag>";
    let (prog, consumed) = load_program_manifest_source(args, usage);
    if args.len() <= consumed {
        eprintln!("Usage: {usage}");
        eprintln!("  Preview what an instruction requires: accounts, args, policies, receipt.");
        process::exit(1);
    }
    let query = &args[consumed];

    // Find instruction by name or tag
    let ix = prog
        .instructions
        .iter()
        .find(|ix| ix.name == query.as_str() || format!("{}", ix.tag) == query.as_str());

    let ix = match ix {
        Some(ix) => ix,
        None => {
            eprintln!("Instruction '{}' not found.", query);
            eprintln!();
            eprintln!("Available instructions:");
            for ix in prog.instructions.iter() {
                eprintln!("  [{}] {}", ix.tag, ix.name);
            }
            process::exit(1);
        }
    };

    println!("=== Simulate: {} (tag {}) ===", ix.name, ix.tag);
    println!();

    // Required accounts
    println!("  Accounts required ({}):", ix.accounts.len());
    for (i, acc) in ix.accounts.iter().enumerate() {
        let mut flags = Vec::new();
        if acc.signer {
            flags.push("SIGNER");
        }
        if acc.writable {
            flags.push("WRITABLE");
        }
        let flag_str = if flags.is_empty() {
            "read-only".to_string()
        } else {
            flags.join(" + ")
        };
        let layout_note = if acc.layout_ref.is_empty() {
            String::new()
        } else {
            format!(" → layout:{}", acc.layout_ref)
        };
        println!("    #{}: {} [{}]{}", i, acc.name, flag_str, layout_note);
    }
    println!();

    // Required arguments (instruction data after tag byte)
    if ix.args.is_empty() {
        println!("  Arguments: none (tag byte only)");
    } else {
        let total_size: u16 = ix.args.iter().map(|a| a.size).sum();
        println!(
            "  Arguments ({}, {} bytes after tag):",
            ix.args.len(),
            total_size
        );
        let mut offset = 1usize; // tag byte
        for arg in ix.args.iter() {
            println!(
                "    @{}: {} ({}, {} bytes)",
                offset, arg.name, arg.canonical_type, arg.size
            );
            offset += arg.size as usize;
        }
        println!("  Total instruction data: {} bytes", offset);
    }
    println!();

    // Policy constraints
    if !ix.policy_pack.is_empty() {
        println!("  Policy: {}", ix.policy_pack);
        // Look up the policy descriptor for full details
        if let Some(pol) = prog.policies.iter().find(|p| p.name == ix.policy_pack) {
            if !pol.capabilities.is_empty() {
                println!("    Capabilities:");
                for cap in pol.capabilities.iter() {
                    println!("      - {}", cap);
                }
            }
            if !pol.requirements.is_empty() {
                println!("    Requirements:");
                for req in pol.requirements.iter() {
                    println!("      - {}", req);
                }
            }
            if !pol.invariants.is_empty() {
                println!("    Invariants checked:");
                for inv in pol.invariants.iter() {
                    println!("      - {}", inv);
                }
            }
        }
    } else {
        println!("  Policy: (none / custom)");
    }
    println!();

    // Receipt preview
    if ix.receipt_expected {
        println!("  Receipt: YES. This instruction emits a state receipt.");
        println!("    The receipt captures:");
        println!("      - Phase (Init/Update/Close/Migrate)");
        println!("      - Changed field bitmask");
        println!("      - Segment change mask");
        println!("      - Fingerprint before/after");
        println!("      - Compatibility impact");
        println!("      - CPI invocation flag");
    } else {
        println!("  Receipt: NO. This instruction does not emit a receipt.");
    }

    // Capability summary
    if !ix.capabilities.is_empty() {
        println!();
        println!("  Capabilities:");
        for cap in ix.capabilities.iter() {
            println!("    - {}", cap);
        }
    }
}

fn parse_or_exit(json: &str) -> OwnedManifest {
    let resolved = resolve_manifest_arg(json);
    match parse_manifest_json(&resolved) {
        Ok(p) => p.into(),
        Err(e) => {
            eprintln!("JSON parse error: {}", e);
            process::exit(1);
        }
    }
}

/// Convert an OwnedManifest to a LayoutManifest with borrowed field descriptors.
///
/// Returns the manifest and the owned field descriptor vector (must outlive manifest).
fn to_manifest(m: &OwnedManifest) -> (LayoutManifest, Vec<FieldDescriptor>) {
    let fields: Vec<FieldDescriptor> = m
        .fields
        .iter()
        .map(|f| FieldDescriptor {
            name: leak_str(&f.name),
            canonical_type: leak_str(&f.canonical_type),
            size: f.size,
            offset: f.offset,
            intent: f.intent,
        })
        .collect();

    let manifest = LayoutManifest {
        name: leak_str(&m.name),
        disc: m.disc,
        version: m.version,
        layout_id: m.layout_id,
        total_size: m.total_size,
        has_dynamic_tail: m.has_dynamic_tail,
        field_count: m.field_count,
        fields: leak_slice(&fields),
    };

    (manifest, fields)
}

/// Leak a string to get a 'static reference.
///
/// This is acceptable for a short-lived CLI binary.
fn leak_str(s: &str) -> &'static str {
    Box::leak(s.to_string().into_boxed_str())
}

/// Leak a vec to get a 'static slice reference.
fn leak_slice(v: &[FieldDescriptor]) -> &'static [FieldDescriptor] {
    Box::leak(v.to_vec().into_boxed_slice())
}

#[cfg(test)]
mod loader_write_set_tests {
    //! CLI-LOADER round-trip coverage: the JSON manifest loader must carry
    //! the write-set / lamport / CU authority into the descriptors it builds,
    //! and a manifest that omits those keys must load with the documented
    //! defaults (no regression for older manifests).
    use super::*;

    /// A codama-shaped manifest carrying every write-set field: strictWrites,
    /// writeRanges (with the derived `account` name codama also emits and the
    /// loader ignores), cuEstimate, mutationComplete, lamportAccounts, plus a
    /// context that carries strictWrites + writeRanges. Mirrors the exact
    /// key/shape codama serializes (crates/hopper-schema/src/codama.rs).
    const MANIFEST_WITH_WRITE_SET: &str = r#"{
      "name": "TestProgram",
      "version": "1.2.3",
      "instructions": [
        {
          "name": "deposit",
          "tag": 3,
          "args": [],
          "accounts": [
            { "name": "vault", "writable": true, "signer": false, "layout_ref": "Vault" },
            { "name": "authority", "writable": false, "signer": true, "layout_ref": "" }
          ],
          "capabilities": ["MutatesState"],
          "policy_pack": "VAULT_WRITE",
          "receipt_expected": true,
          "cuEstimate": 4200,
          "strictWrites": true,
          "mutationComplete": true,
          "lamportAccounts": [0, 1],
          "writeRanges": [
            { "account": "vault", "accountIndex": 0, "offset": 16, "size": 8 },
            { "account": "vault", "accountIndex": 0, "offset": 40, "size": 32 }
          ]
        }
      ],
      "contexts": [
        {
          "name": "Deposit",
          "accounts": [
            { "name": "vault", "kind": "HopperAccount", "writable": true, "signer": false, "layout_ref": "Vault", "policy_ref": "VAULT_WRITE", "seeds": [], "optional": false }
          ],
          "policies": ["VAULT_WRITE"],
          "receipts_expected": true,
          "mutation_classes": ["StateTransition"],
          "strictWrites": true,
          "writeRanges": [
            { "account": "vault", "accountIndex": 0, "offset": 16, "size": 8 }
          ]
        }
      ]
    }"#;

    /// The same program WITHOUT any of the write-set keys, an "old" manifest
    /// predating write-range, mutation-completeness, and compute-budget metadata.
    /// It must load with defaults.
    const MANIFEST_WITHOUT_WRITE_SET: &str = r#"{
      "name": "TestProgram",
      "version": "1.2.3",
      "instructions": [
        {
          "name": "deposit",
          "tag": 3,
          "args": [],
          "accounts": [
            { "name": "vault", "writable": true, "signer": false, "layout_ref": "Vault" }
          ],
          "capabilities": ["MutatesState"],
          "policy_pack": "VAULT_WRITE",
          "receipt_expected": true
        }
      ],
      "contexts": [
        {
          "name": "Deposit",
          "accounts": [
            { "name": "vault", "kind": "HopperAccount", "writable": true, "signer": false, "layout_ref": "Vault", "policy_ref": "", "seeds": [], "optional": false }
          ],
          "policies": [],
          "receipts_expected": false,
          "mutation_classes": []
        }
      ]
    }"#;

    #[test]
    fn emitted_manifest_round_trips_rich_context_and_upgrade_contract() {
        use hopper_schema::accounts::AccountLifecycle;
        use hopper_schema::codama::ManifestJson;

        static INSTRUCTION_ACCOUNTS: &[AccountEntry] = &[
            AccountEntry {
                name: "payer",
                writable: true,
                signer: true,
                layout_ref: "",
                seeds: &[],
            },
            AccountEntry {
                name: "state",
                writable: true,
                signer: false,
                layout_ref: "StateV2",
                seeds: &[],
            },
        ];
        static INSTRUCTIONS: &[InstructionDescriptor] = &[InstructionDescriptor {
            name: "initialize",
            tag: 1,
            discriminator: &[1],
            args: &[],
            accounts: INSTRUCTION_ACCOUNTS,
            remaining_accounts: None,
            capabilities: &["MutatesState"],
            policy_pack: "StatePolicy",
            receipt_expected: true,
            strict_writes: false,
            write_ranges: &[],
            parametric_write_ranges: &[],
            mutation_complete: false,
            lamport_accounts: &[],
            cu_estimate: 3_000,
        }];
        static EVENT_FIELDS: &[FieldDescriptor] = &[
            FieldDescriptor {
                name: "authority",
                canonical_type: "Pubkey",
                size: 32,
                offset: 0,
                intent: FieldIntent::Authority,
            },
            FieldDescriptor {
                name: "opaque",
                canonical_type: "u8",
                size: 1,
                offset: 32,
                intent: FieldIntent::Custom,
            },
        ];
        static EVENTS: &[EventDescriptor] = &[EventDescriptor {
            name: "Initialized",
            tag: 9,
            fields: EVENT_FIELDS,
        }];
        static CONTEXT_ACCOUNTS: &[ContextAccountDescriptor] = &[
            ContextAccountDescriptor {
                name: "payer",
                kind: "Signer",
                writable: true,
                signer: true,
                layout_ref: "",
                policy_ref: "",
                seeds: &[],
                optional: false,
                lifecycle: AccountLifecycle::Existing,
                payer: "",
                init_space: 0,
                has_one: &[],
                expected_address: "",
                expected_owner: "",
            },
            ContextAccountDescriptor {
                name: "state",
                kind: "InitAccount",
                writable: true,
                signer: false,
                layout_ref: "StateV2",
                policy_ref: "StatePolicy",
                seeds: &["b\"state\"", "payer.address()"],
                optional: true,
                lifecycle: AccountLifecycle::Init,
                payer: "payer",
                init_space: 64,
                has_one: &["payer"],
                expected_address: "state-address",
                expected_owner: "state-owner",
            },
        ];
        static CONTEXT_RANGES: &[WriteRange] = &[WriteRange::new(1, 16, 8)];
        static CONTEXT_PARAMETRIC: &[hopper_schema::ParametricWriteRange] =
            &[hopper_schema::ParametricWriteRange::new(
                1, 24, 8, 8, 4, 0, "slot", "cells",
            )];
        static CONTEXTS: &[ContextDescriptor] = &[ContextDescriptor {
            name: "Initialize",
            instructions: &[],
            accounts: CONTEXT_ACCOUNTS,
            policies: &["StatePolicy"],
            receipts_expected: true,
            mutation_classes: &["Initialization"],
            strict_writes: true,
            write_ranges: CONTEXT_RANGES,
            parametric_write_ranges: CONTEXT_PARAMETRIC,
            mutation_complete: true,
            lamport_accounts: &[0, 1],
        }];
        static METADATA: &[LayoutMetadata] = &[LayoutMetadata {
            name: "StateV2",
            segment_roles: &["core", "cells"],
            append_safe: true,
            migration_required: false,
            rebuildable: true,
            policy_pack: "StatePolicy",
            invariant_pack: &["StateValid"],
            receipt_profile: "StateReceipt",
            phase_requirements: &["Update"],
            trust_profile: "verified",
            manager_hints: &["show-cells"],
        }];
        static COMPATIBILITY: &[CompatibilityPair] = &[CompatibilityPair {
            from_layout: "StateV1",
            from_version: 1,
            to_layout: "StateV2",
            to_version: 2,
            policy: MigrationPolicy::AppendOnly,
            backward_readable: true,
        }];
        static POLICIES: &[PolicyDescriptor] = &[PolicyDescriptor {
            name: "StatePolicy",
            capabilities: &["MutatesState"],
            requirements: &["SignerAuthority"],
            invariants: &["StateValid"],
            receipt_profile: "StateReceipt",
        }];
        static LAYOUTS: &[LayoutManifest] = &[LayoutManifest {
            name: "StateV2",
            disc: 7,
            version: 2,
            layout_id: [7; 8],
            total_size: 1,
            has_dynamic_tail: true,
            field_count: 0,
            fields: &[],
        }];
        let source = ProgramManifest {
            name: "roundtrip",
            version: "1.0.0",
            description: "rich manifest",
            layouts: LAYOUTS,
            layout_metadata: METADATA,
            instructions: INSTRUCTIONS,
            events: EVENTS,
            policies: POLICIES,
            compatibility_pairs: COMPATIBILITY,
            tooling_hints: &["lossless"],
            contexts: CONTEXTS,
        };

        let json = format!("{}", ManifestJson(&source));
        let owned = parse_program_manifest_json(&json).expect("emitted manifest parses");
        let loaded = to_program_manifest(&owned);

        assert!(json.contains("\"hasDynamicTail\": true"));
        assert!(loaded.layouts[0].has_dynamic_tail);
        assert_eq!(loaded.instructions[0].policy_pack, "StatePolicy");
        assert!(loaded.instructions[0].receipt_expected);
        assert_eq!(
            loaded.instructions[0].accounts[1].seeds,
            &["b\"state\"", "payer.address()"]
        );
        assert_eq!(loaded.layout_metadata.len(), 1);
        assert_eq!(loaded.layout_metadata[0].segment_roles, &["core", "cells"]);
        assert_eq!(loaded.layout_metadata[0].invariant_pack, &["StateValid"]);
        assert_eq!(loaded.compatibility_pairs.len(), 1);
        assert_eq!(
            loaded.compatibility_pairs[0].policy,
            MigrationPolicy::AppendOnly
        );
        assert!(loaded.compatibility_pairs[0].backward_readable);
        assert_eq!(loaded.contexts.len(), 1);
        assert_eq!(
            loaded.contexts[0].accounts[1].lifecycle,
            AccountLifecycle::Init
        );
        assert_eq!(loaded.contexts[0].accounts[1].has_one, &["payer"]);
        assert_eq!(loaded.contexts[0].parametric_write_ranges.len(), 1);
        assert!(loaded.contexts[0].mutation_complete);
        assert_eq!(loaded.contexts[0].lamport_accounts, &[0, 1]);
        assert_eq!(loaded.tooling_hints, &["lossless"]);
        assert_eq!(loaded.events[0].fields[0].intent, FieldIntent::Authority);
        assert_eq!(loaded.events[0].fields[1].intent, FieldIntent::Custom);
    }

    #[test]
    fn legacy_layout_without_dynamic_tail_flag_defaults_to_fixed() {
        let json = r#"{
          "name": "legacy",
          "version": "0.1.0",
          "layouts": [{
            "name": "FixedCompact",
            "disc": 3,
            "version": 1,
            "layoutId": "0102030405060708",
            "totalSize": 1,
            "fieldCount": 0,
            "fields": []
          }]
        }"#;

        let owned = parse_program_manifest_json(json).expect("legacy layout should parse");
        let loaded = to_program_manifest(&owned);
        assert!(!loaded.layouts[0].has_dynamic_tail);
    }

    #[test]
    fn single_layout_parser_carries_dynamic_tail_aliases() {
        let parsed = parse_manifest_json(
            r#"{
              "name": "DynamicCompact",
              "disc": 3,
              "version": 1,
              "layoutId": "0102030405060708",
              "totalSize": 1,
              "hasDynamicTail": true,
              "fields": []
            }"#,
        )
        .expect("dynamic compact layout should parse");
        assert!(parsed.has_dynamic_tail);

        let legacy = parse_manifest_json(
            r#"{
              "name": "FixedCompact",
              "disc": 4,
              "version": 1,
              "layout_id": [1, 2, 3, 4, 5, 6, 7, 8],
              "total_size": 1,
              "fields": []
            }"#,
        )
        .expect("legacy fixed compact layout should parse");
        assert!(!legacy.has_dynamic_tail);
    }

    #[test]
    fn loader_carries_instruction_write_set_verbatim() {
        let owned = parse_program_manifest_json(MANIFEST_WITH_WRITE_SET)
            .expect("manifest with write set should parse");
        let prog = to_program_manifest(&owned);
        let ix = &prog.instructions[0];

        assert_eq!(ix.name, "deposit");
        // strict_writes MUST NOT be zeroed away by the loader.
        assert!(ix.strict_writes, "strict_writes should round-trip as true");
        assert!(
            ix.mutation_complete,
            "mutation_complete should round-trip as true"
        );
        assert_eq!(ix.cu_estimate, 4200, "cu_estimate should round-trip");
        assert_eq!(
            ix.lamport_accounts,
            &[0u8, 1u8],
            "lamport_accounts should round-trip"
        );

        // The byte-range write surface, index/offset/size preserved and in order.
        assert_eq!(ix.write_ranges.len(), 2, "both write ranges carried");
        assert_eq!(ix.write_ranges[0].account_index, 0);
        assert_eq!(ix.write_ranges[0].offset, 16);
        assert_eq!(ix.write_ranges[0].size, 8);
        assert_eq!(ix.write_ranges[1].account_index, 0);
        assert_eq!(ix.write_ranges[1].offset, 40);
        assert_eq!(ix.write_ranges[1].size, 32);
    }

    #[test]
    fn parser_key_matcher_skips_string_values_that_equal_a_key() {
        // Regression: an account legitimately named "offset" / "size" /
        // "accountIndex" must not shadow the real key. The pre-fix
        // substring matcher matched the string VALUE first, hit ',' where
        // it expected ':', and failed the entire manifest load.
        let range = r#"{ "account": "offset", "accountIndex": 3, "offset": 16, "size": 8 }"#;
        assert_eq!(extract_number(range, "offset").unwrap(), 16);
        assert_eq!(extract_number(range, "accountIndex").unwrap(), 3);
        assert_eq!(extract_number(range, "size").unwrap(), 8);
        assert_eq!(extract_string(range, "account").unwrap(), "offset");
        // A string value equal to a boolean key must not be read as the key.
        let ix = r#"{ "policy_pack": "strictWrites", "strictWrites": true }"#;
        assert!(find_after_key(ix, "strictWrites")
            .expect("strictWrites key")
            .starts_with("true"));
        assert_eq!(extract_string(ix, "policy_pack").unwrap(), "strictWrites");
    }

    #[test]
    fn loader_carries_context_write_set_verbatim() {
        let owned = parse_program_manifest_json(MANIFEST_WITH_WRITE_SET)
            .expect("manifest with write set should parse");
        let prog = to_program_manifest(&owned);
        let ctx = &prog.contexts[0];

        assert_eq!(ctx.name, "Deposit");
        assert!(ctx.strict_writes, "context strict_writes should round-trip");
        assert_eq!(ctx.write_ranges.len(), 1);
        assert_eq!(ctx.write_ranges[0].account_index, 0);
        assert_eq!(ctx.write_ranges[0].offset, 16);
        assert_eq!(ctx.write_ranges[0].size, 8);
    }

    #[test]
    fn release_manifest_rejects_unknown_argument_encoding() {
        let json = r#"{
          "name": "fail-closed",
          "instructions": [{
            "name": "write",
            "args": [{ "name": "value", "type": "u8", "encoding": "futureEncoding" }]
          }]
        }"#;

        let error = parse_program_manifest_json(json)
            .err()
            .expect("unknown argument encoding must fail");
        assert_eq!(error, "unknown argument encoding `futureEncoding`");
    }

    #[test]
    fn release_manifest_rejects_unknown_account_lifecycle() {
        let json = r#"{
          "name": "fail-closed",
          "contexts": [{
            "name": "Write",
            "accounts": [{ "name": "state", "lifecycle": "teleport" }]
          }]
        }"#;

        let error = parse_program_manifest_json(json)
            .err()
            .expect("unknown account lifecycle must fail");
        assert_eq!(error, "unknown account lifecycle `teleport`");
    }

    #[test]
    fn release_manifest_rejects_unknown_layout_and_event_field_intents() {
        let manifests = [
            r#"{
              "name": "fail-closed-layout",
              "layouts": [{
                "name": "State",
                "layoutId": "0000000000000000",
                "fields": [{ "name": "value", "type": "u8", "intent": "mystery" }]
              }]
            }"#,
            r#"{
              "name": "fail-closed-event",
              "events": [{
                "name": "Changed",
                "fields": [{ "name": "value", "type": "u8", "intent": "mystery" }]
              }]
            }"#,
        ];

        for json in manifests {
            let error = parse_program_manifest_json(json)
                .err()
                .expect("unknown field intent must fail");
            assert_eq!(error, "unknown field intent `mystery`");
        }
    }

    #[test]
    fn release_manifest_typed_values_and_event_intents_round_trip() {
        let json = r#"{
          "name": "typed-round-trip",
          "layouts": [{
            "name": "State",
            "layoutId": "0000000000000000",
            "fields": [{ "name": "opaque", "type": "u8", "intent": "custom" }]
          }],
          "instructions": [{
            "name": "write",
            "args": [
              { "name": "fixed", "type": "u8", "size": 1, "encoding": "fixed" },
              { "name": "items", "type": "Vec<u16>", "encoding": "boundedVec", "maxLen": 7, "elementSize": 2 },
              { "name": "label", "type": "String", "encoding": "boundedString", "maxLen": 19 }
            ]
          }],
          "events": [{
            "name": "Changed",
            "fields": [
              { "name": "authority", "type": "Pubkey", "intent": "authority" },
              { "name": "opaque", "type": "u8", "intent": "custom" },
              { "name": "defaulted", "type": "u8" }
            ]
          }],
          "contexts": [{
            "name": "Write",
            "accounts": [
              { "name": "current", "lifecycle": "existing" },
              { "name": "created", "lifecycle": "init" },
              { "name": "maybe_created", "lifecycle": "init_if_needed" },
              { "name": "grown", "lifecycle": "realloc" },
              { "name": "recipient", "lifecycle": "close" }
            ]
          }]
        }"#;

        let owned = parse_program_manifest_json(json).expect("known typed values should parse");
        let manifest = to_program_manifest(&owned);

        assert_eq!(manifest.layouts[0].fields[0].intent, FieldIntent::Custom);
        assert_eq!(
            manifest.instructions[0].args[0].encoding,
            hopper_schema::ArgEncoding::Fixed
        );
        assert_eq!(
            manifest.instructions[0].args[1].encoding,
            hopper_schema::ArgEncoding::BoundedVec {
                max_len: 7,
                element_size: 2,
            }
        );
        assert_eq!(
            manifest.instructions[0].args[2].encoding,
            hopper_schema::ArgEncoding::BoundedString { max_len: 19 }
        );
        assert_eq!(manifest.events[0].fields[0].intent, FieldIntent::Authority);
        assert_eq!(manifest.events[0].fields[1].intent, FieldIntent::Custom);
        assert_eq!(manifest.events[0].fields[2].intent, FieldIntent::Custom);
        assert_eq!(
            manifest.contexts[0]
                .accounts
                .iter()
                .map(|account| account.lifecycle)
                .collect::<Vec<_>>(),
            vec![
                AccountLifecycle::Existing,
                AccountLifecycle::Init,
                AccountLifecycle::InitIfNeeded,
                AccountLifecycle::Realloc,
                AccountLifecycle::Close,
            ]
        );
    }

    #[test]
    fn old_manifest_loads_with_documented_defaults() {
        let owned = parse_program_manifest_json(MANIFEST_WITHOUT_WRITE_SET)
            .expect("legacy manifest should still parse");
        let prog = to_program_manifest(&owned);
        let ix = &prog.instructions[0];

        // Missing keys retain the legacy values without fabricating authority.
        assert!(!ix.strict_writes);
        assert!(ix.write_ranges.is_empty());
        assert!(!ix.mutation_complete);
        assert!(ix.lamport_accounts.is_empty());
        assert_eq!(ix.cu_estimate, 0);

        let ctx = &prog.contexts[0];
        assert!(!ctx.strict_writes);
        assert!(ctx.write_ranges.is_empty());
    }

    #[test]
    fn golden_counter_manifest_loads_without_write_set() {
        // The shipped counter fixture predates the write-set keys; it must
        // load cleanly with defaults (guards against a parse regression on
        // real, checked-in manifests).
        const COUNTER: &str = include_str!("../tests/fixtures/hopper-counter.manifest.json");
        let owned =
            parse_program_manifest_json(COUNTER).expect("golden counter manifest should parse");
        let prog = to_program_manifest(&owned);
        assert!(!prog.instructions.is_empty());
        for ix in prog.instructions.iter() {
            assert!(!ix.strict_writes);
            assert!(ix.write_ranges.is_empty());
            assert!(!ix.mutation_complete);
            assert!(ix.lamport_accounts.is_empty());
            assert_eq!(ix.cu_estimate, 0);
        }
    }
}