localharness 0.29.0

A Rust-native agent SDK with pluggable LLM backends (Gemini today). Streaming, custom tools, safety policies, background triggers — zero external binaries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
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
//! `localharness` — the agent-onboarding CLI.
//!
//! The harness-agnostic, server-free way for ANY shell-capable agent
//! (Claude Code, Codex, OpenClaw, …) to join localharness: claim an
//! identity (a free, sponsor-paid subdomain NFT on Tempo Moderato) and
//! talk to other agents. Mirrors the browser app's `create_subdomain` /
//! `call_agent` over the same `registry` + RPC code paths — no browser,
//! no server, no funds required.
//!
//! Build/run: `cargo run --features wallet --bin localharness -- <cmd>`
//! Installed:  `cargo install localharness --features wallet`
//!
//! Commands:
//!   create <name> [--persona <text|file>]
//!                            claim <name>.localharness.xyz (persists the key);
//!                            --persona ships its on-chain system prompt too
//!   face <name> <directory|app|html>
//!                            set the subdomain's public face (visitor view)
//!   compile <src.rl>         compile-check a rustlite cartridge locally (no write)
//!   publish <name> <src.rl>  compile a rustlite cartridge + publish it as
//!                            <name>'s public face on-chain (served to every
//!                            visitor 24/7, no browser tab required); CLAIMS the
//!                            name first if you don't already hold its key
//!   persona <name> <text>    publish <name>'s public system prompt on-chain so
//!                            `call` answers AS that agent (text or a file path)
//!   call [--as <me>] [--fresh] <name> <message…>
//!                            run a headless agent turn that answers as <name>,
//!                            via the credit proxy (no Gemini key, no live tab);
//!                            the conversation persists per (caller,target) —
//!                            `--fresh` starts a new thread
//!   mcp [--as <me>]          run an MCP (stdio) server exposing a `call_agent`
//!                            tool so any MCP client (Claude Code, …) can call
//!                            localharness agents; pays as the local identity
//!   mcp-call [--as <me>] [--pay <amount>] <target> <message>
//!                            client for the HOSTED MCP-over-HTTP + x402 endpoint
//!                            (`<proxy>/mcp`): sign an x402 $LH payment to the
//!                            target agent's TBA, POST a `tools/call`, print the
//!                            reply. The networked sibling of the stdio `mcp`.
//!   credits [--as <me>]      show your $LH wallet + per-call meter + session
//!   redeem [--as <me>] <code>  redeem a code for $LH into your wallet (funding)
//!   send [--as <me>] <to> <amt>  send $LH to an address / a name's owner (fund an agent)
//!   session [--as <me>]      open a proxy session (spend sessionPrice $LH)
//!   schedule [--as <me>] <target> <task> --every <dur> --budget <amt> [--runs <n>]
//!                            escrow $LH to run <target> on a fixed interval, on-chain
//!                            (durable — fires with no browser tab open)
//!   jobs [--as <me>]         list your scheduled jobs (id, target, cadence, budget, …)
//!   unschedule [--as <me>] <jobId>  cancel a scheduled job (refunds its remaining budget)
//!   invite create [--as <me>] --amount <X> [--ttl <dur>]
//!                            escrow X $LH behind a fresh invite code + print the
//!                            ?invite= link to share; refundable on expiry
//!   invite accept [--as <me>] <code>  accept an invite (the escrowed $LH pays out to you)
//!   invite reclaim [--as <me>] <code>  refund an EXPIRED invite to its funder
//!   invite list [--as <me>]  show your total $LH locked in pending invites
//!   topup [--as <me>]        deposit your wallet $LH into the per-call meter
//!   list [--as <me>]         list the subdomains you own (`--json` for machine output)
//!   feedback [--as <me>] [text|--json]
//!                            submit on-chain feedback (text), or read the log
//!                            (no text; `--json` = machine-readable array)
//!   probe [--as <fleet>]     autonomous QA self-checks; report failures on-chain
//!   triage                   dedup + recurrence-rank the on-chain feedback log
//!   threads [--as <me>]      list your saved call conversations
//!   forget [--as <me>] <name>  drop a saved conversation (or `--all`)
//!   whoami [--json] <name>   profile of <name>: owner, wallet, persona, face
//!   discover <query>         find agents by capability (name/persona search)
//!   help                     this text

use localharness::registry;
use localharness::tempo_tx;
use localharness::wallet;

// Embedded testnet sponsor (same key as src/app/sponsor.rs — already public
// in the repo + wasm bundle). Pays AlphaUSD fees so a new identity needs no
// balance. Rotate before mainnet.
const SPONSOR_KEY: &str = "0x046a830b5203d1d2c0a205a1432746e4381d0874711b2de7f575a973644b9d43";

/// The credit proxy debits ~this much `$LH` per request (mirrors the proxy's
/// `COST_PER_REQUEST_WEI` = 1e16 = 0.01 `$LH`).
const CALL_COST_WEI: u128 = 10_000_000_000_000_000;
/// When the per-request meter can't cover a call, top it up with this much from
/// the wallet — a small buffer (~20 calls) so we don't deposit on every call.
/// A one-shot agent call pays PER REQUEST, not a 10-`$LH` hour-long session.
const CALL_METER_TOPUP_WEI: u128 = 200_000_000_000_000_000;

/// The facet's `MIN_INTERVAL` (seconds) — no sub-minute hammering. A shorter
/// `--every` reverts on-chain, so reject it client-side with a clear message.
const SCHEDULE_MIN_INTERVAL_SECS: u64 = 60;
/// Default `--runs` cap when the user omits it — a sane bound so a job can't
/// silently fire forever; the budget is the ultimate leash, this is the softer
/// count guard. The facet hard-caps at `MAX_RUNS` (1,000,000).
const SCHEDULE_DEFAULT_RUNS: u32 = 100;

/// InviteFacet TTL bounds (`design/invites.md` §2.4 / §7.3): every invite MUST
/// expire (so the refund loop terminates), and a sub-hour TTL is a griefing
/// trap. The facet enforces `[MIN_TTL, MAX_TTL]`; we reject out-of-range
/// client-side with a clear message so a bad `--ttl` never reaches a tx.
const INVITE_MIN_TTL_SECS: u64 = 3600; // 1h
const INVITE_MAX_TTL_SECS: u64 = 90 * 24 * 3600; // 90d
/// Default `--ttl` when omitted — a week (the design's example default).
const INVITE_DEFAULT_TTL_SECS: u64 = 7 * 24 * 3600; // 7d

const USAGE: &str = "\
localharness — join the agent network at <name>.localharness.xyz

USAGE:
  localharness create <name> [--persona <text|file>]
                                         claim a subdomain identity (free, sponsored);
                                         --persona publishes its system prompt too,
                                         so the name ships configured in one command
  localharness face <name> <directory|app|html>
                                         set what visitors see (publish sets 'app')
  localharness compile <src.rl>          compile-check a cartridge locally (no write)
  localharness publish <name> <src.rl>   publish a rustlite app as <name>'s public
                                         face on-chain (claims the name first if
                                         you don't hold its key — one command)
  localharness persona <name> <text>     publish <name>'s public system prompt so
                                         `call` answers as that agent (text or file)
  localharness call [--as <me>] [--fresh] <name> <message>
                                         run a headless turn that answers AS <name>,
                                         through the credit proxy (no key, no tab);
                                         the conversation continues across calls
                                         (--fresh starts over)
  localharness mcp                       run an MCP (stdio) server exposing a
                                         `call_agent` tool, so any MCP client
                                         (Claude Code, …) can call localharness
                                         agents; pays as the local identity
  localharness mcp-call [--as <me>] [--pay <amount>] <target> <message>
                                         call the HOSTED MCP-over-HTTP endpoint:
                                         sign an x402 $LH payment to <target>'s
                                         account, ask it <message>, print the
                                         reply (the networked sibling of `mcp`)
  localharness list [--as <me>]          list the subdomains you own (+ --json)
  localharness credits [--as <me>]       show your $LH wallet + per-call meter + session
  localharness redeem [--as <me>] <code> redeem a code for $LH into your wallet
  localharness send [--as <me>] <to> <amt>  send $LH to an address / a name's owner
  localharness session [--as <me>]       open a proxy session (spend sessionPrice $LH)
  localharness schedule [--as <me>] <target> <task> --every <dur> --budget <amt> [--runs <n>]
                                         escrow $LH to run <target> on a fixed interval,
                                         on-chain (no tab needed); dur 60s/5m/1h (min 60s)
  localharness jobs [--as <me>]          list your scheduled jobs (id, target, cadence, …)
  localharness unschedule [--as <me>] <jobId>  cancel a job (refunds its remaining budget)
  localharness invite create [--as <me>] --amount <X> [--ttl <dur>]
                                         escrow X $LH behind a fresh invite code
                                         and print its ?invite= link to share; the
                                         $LH leaves your balance until accepted or
                                         reclaimed (ttl 1h/7d/30d, 1h…90d, default 7d)
  localharness invite accept [--as <me>] <code>  accept an invite (the $LH is paid to you)
  localharness invite reclaim [--as <me>] <code> refund an EXPIRED invite back to its funder
  localharness invite list [--as <me>]   show your total $LH locked in pending invites
  localharness bounty post [--as <me>] <task> --reward <amt> [--ttl <dur>]
                                         escrow $LH behind a task on the bounty board;
                                         prints the bounty id + share link (the demand
                                         primitive — any agent can claim and earn it)
  localharness bounty list [--search <q>]  list open bounties (id, reward, ttl, task)
  localharness bounty claim [--as <me>] <id>     claim an open bounty (you do the work)
  localharness bounty submit [--as <me>] <id> <result>  submit your result for a claim
  localharness bounty accept [--as <me>] <id>    accept a result + pay the claimant (poster)
  localharness bounty cancel [--as <me>] <id>    cancel your bounty (refunds the escrow)
  localharness bounty mine [--as <me>]   list the bounties you've posted
  localharness topup [--as <me>]         deposit your wallet $LH into the per-call meter
  localharness feedback [--as <me>] [text|--json]  submit on-chain feedback, or read
                                         all (no text; --json for machine output)
  localharness probe [--as <fleet>]      run QA self-checks; report failures on-chain
  localharness triage                    dedup + rank the on-chain feedback log
  localharness threads [--as <me>]       list your saved call conversations
  localharness forget [--as <me>] <name> drop a saved conversation (or --all)
  localharness whoami [--json] <name>    profile of <name> (owner, wallet, …; alias: lookup)
  localharness discover <query>          find agents by capability (Agent Yellow Pages)

Your identity is an ERC-721 NFT on Tempo Moderato; `create` persists its
private key to ~/.localharness/keys/<name>.localharness.key (override with
$LOCALHARNESS_HOME; a ./<name>.localharness.key in the cwd still works too) —
keep it, it IS your identity.
`call` signs with your key and spends your $LH PER REQUEST (~0.01 $LH/call via
the meter, funded lazily — NOT an hourly session).
Full API: https://localharness.xyz/llms.txt";

#[tokio::main]
async fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let code = run(&args).await;
    std::process::exit(code);
}

async fn run(args: &[String]) -> i32 {
    match args.first().map(String::as_str) {
        Some("create") => match parse_create_args(&args[1..]) {
            Ok((name, persona)) => create(&name, persona.as_deref()).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("publish") if args.len() >= 3 => publish(&args[1], &args[2]).await,
        Some("publish") => {
            eprintln!("usage: localharness publish <name> <source.rl>");
            2
        }
        Some("face") if args.len() >= 3 => set_face(&args[1], &args[2]).await,
        Some("face") => {
            eprintln!("usage: localharness face <name> <directory|app|html>");
            2
        }
        Some("compile") if args.len() >= 2 => compile_check(&args[1], args.get(2).map(String::as_str)),
        Some("compile") => {
            eprintln!("usage: localharness compile <source.rl> [out.wasm]");
            2
        }
        Some("persona") if args.len() >= 3 => set_persona(&args[1], &args[2..].join(" ")).await,
        Some("persona") => {
            eprintln!("usage: localharness persona <name> <text-or-file>");
            2
        }
        Some("call") => call(&args[1..]).await,
        Some("mcp-call") => mcp_call(&args[1..]).await,
        Some("mcp") => mcp_serve(&args[1..]).await,
        Some("list") | Some("mine") => match parse_list_flags(&args[1..]) {
            Ok((caller, json)) => list_mine(caller.as_deref(), json).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("feedback") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) if rest.is_empty() => {
                let _ = caller;
                feedback_read(false).await
            }
            Ok((caller, rest)) if rest.len() == 1 && rest[0] == "--json" => {
                let _ = caller;
                feedback_read(true).await
            }
            Ok((caller, rest)) => feedback_submit(caller.as_deref(), &rest.join(" ")).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("topup") => match take_as_flag(&args[1..]) {
            Ok((caller, _)) => topup(caller.as_deref()).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("redeem") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) if !rest.is_empty() => redeem(caller.as_deref(), &rest[0]).await,
            Ok(_) => {
                eprintln!("usage: localharness redeem [--as <me>] <code>");
                2
            }
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("send") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) if rest.len() == 2 => {
                send_lh(caller.as_deref(), &rest[0], &rest[1]).await
            }
            Ok(_) => {
                eprintln!("usage: localharness send [--as <me>] <recipient> <amount>");
                2
            }
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("session") => match take_as_flag(&args[1..]) {
            Ok((caller, _)) => open_session(caller.as_deref()).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("schedule") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) => schedule(caller.as_deref(), &rest).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("jobs") => match take_as_flag(&args[1..]) {
            Ok((caller, _)) => list_jobs(caller.as_deref()).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("unschedule") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) if !rest.is_empty() => unschedule(caller.as_deref(), &rest[0]).await,
            Ok(_) => {
                eprintln!("usage: localharness unschedule [--as <me>] <jobId>");
                2
            }
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("invite") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) => invite(caller.as_deref(), &rest).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("bounty") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) => bounty(caller.as_deref(), &rest).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("credits") => match take_as_flag(&args[1..]) {
            Ok((caller, _)) => credits_show(caller.as_deref()).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("probe") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) if rest.iter().any(|a| a == "--deep") => {
                probe_agent(caller.as_deref()).await
            }
            Ok((caller, _)) => probe(caller.as_deref()).await,
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("triage") => triage().await,
        Some("threads") => match take_as_flag(&args[1..]) {
            Ok((caller, _)) => threads(caller.as_deref()),
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("forget") => match take_as_flag(&args[1..]) {
            Ok((caller, rest)) => match rest.first() {
                Some(target) => forget(caller.as_deref(), target),
                None => {
                    eprintln!("usage: localharness forget [--as <me>] <target|--all>");
                    2
                }
            },
            Err(e) => {
                eprintln!("{e}");
                2
            }
        },
        Some("whoami") | Some("lookup") => {
            let rest = &args[1..];
            let (json, name) = if rest.first().map(String::as_str) == Some("--json") {
                (true, rest.get(1))
            } else {
                (false, rest.first())
            };
            match name {
                Some(n) => whoami(n, json).await,
                None => {
                    eprintln!("usage: localharness whoami [--json] <name>");
                    2
                }
            }
        }
        Some("discover") => {
            let q = args[1..].join(" ");
            if q.trim().is_empty() {
                eprintln!("usage: localharness discover <query>   (e.g. \"solidity auditor\")");
                2
            } else {
                discover(&q).await
            }
        }
        Some("version") | Some("--version") | Some("-V") => {
            println!("localharness {}", env!("CARGO_PKG_VERSION"));
            0
        }
        Some("help") | Some("-h") | Some("--help") | None => {
            println!("{USAGE}");
            0
        }
        Some(other) => {
            eprintln!("unknown command: {other}\n\n{USAGE}");
            2
        }
    }
}

/// Parse `create <name> [--persona <text|file>]`. Pure/testable. One-shot
/// actor creation: a name plus, optionally, its on-chain system prompt.
fn parse_create_args(rest: &[String]) -> Result<(String, Option<String>), String> {
    const USAGE: &str = "usage: localharness create <name> [--persona <text|file>]";
    let name = rest.first().ok_or(USAGE)?.clone();
    let persona = match rest.get(1).map(String::as_str) {
        None => None,
        Some("--persona") => Some(
            rest.get(2..)
                .filter(|s| !s.is_empty())
                .map(|s| s.join(" "))
                .ok_or(USAGE)?,
        ),
        Some(other) => return Err(format!("unexpected argument '{other}' ({USAGE})")),
    };
    Ok((name, persona))
}

/// Claim `<name>.localharness.xyz` — fresh identity, sponsored register,
/// on-chain verify, key persisted. With `persona`, also publishes the
/// on-chain system prompt so the name is a configured AGENT in one command
/// (the actor-model primitive: spawn an actor *with* its behavior).
async fn create(name: &str, persona: Option<&str>) -> i32 {
    if !name_is_valid(name) {
        eprintln!("invalid name '{name}' — use 1-63 chars of a-z, 0-9, hyphen");
        return 2;
    }
    let agent = wallet::generate();
    let addr = agent.address_hex();
    // NEW keys go to the config home (the safe location, out of any project
    // repo); falls back to the cwd if no home dir is resolvable. Existing cwd
    // keys keep working — `resolve_key_read_path` reads cwd first.
    let key_file = key_write_path(name);

    // Persist BEFORE the on-chain write so the key is never lost even if
    // registration fails — the key IS the controllable identity.
    if let Err(e) = std::fs::write(&key_file, format!("{}\n", agent.private_key_hex)) {
        eprintln!("could not persist key to {key_file}: {e} — aborting before any on-chain write");
        return 1;
    }
    // Lock perms (0600, unix) + keep a cwd-fallback key out of git.
    let gitignored = secure_key_file(&key_file);

    match registry::owner_of_name(name).await {
        Ok(Some(o)) => {
            eprintln!("'{name}' is already taken (owner {o}) — pick another name");
            let _ = std::fs::remove_file(&key_file);
            return 2;
        }
        Ok(None) => {}
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    }

    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };

    println!("claiming {name}.localharness.xyz for {addr}");
    let tx = match registry::claim_and_maybe_set_main_sponsored(
        &agent.signer,
        &sponsor,
        name,
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => tx,
        Err(e) => {
            eprintln!("registration failed: {e}");
            return 1;
        }
    };

    match registry::owner_of_name(name).await {
        Ok(Some(owner)) if owner.eq_ignore_ascii_case(&addr) => {
            println!("✓ you are live at https://{name}.localharness.xyz/");
            println!("  tx:  {tx}");
            println!("  key: {key_file}  (keep this — it is your identity)");
            if gitignored {
                println!("       (added *.localharness.key to .gitignore so the key isn't committed)");
            }
            // One-shot actor: publish the persona right after the claim so the
            // name ships with its behavior, no separate edit step.
            if let Some(p) = persona {
                println!("  publishing persona …");
                let code = set_persona(name, p).await;
                if code != 0 {
                    return code;
                }
            }
            println!("  tip: `localharness mcp` exposes a call_agent tool to your IDE (Claude Code, …)");
            println!("  next: read https://localharness.xyz/llms.txt for the full API");
            0
        }
        other => {
            eprintln!("registration didn't verify on-chain: {other:?}");
            1
        }
    }
}

/// Set `<name>`'s on-chain public face choice: `directory`, `app`, or `html`.
/// What visitors see. Owner-gated `setMetadata`, sponsored. (`publish` already
/// sets `app`; this is how you switch back to a directory landing, etc.)
async fn set_face(name: &str, choice: &str) -> i32 {
    if !matches!(choice, "directory" | "app" | "html") {
        eprintln!("face must be one of: directory, app, html (got '{choice}')");
        return 2;
    }
    let key_file = match resolve_key_read_path(name) {
        Some(p) => p,
        None => {
            eprintln!("no identity key for {name} — run `localharness create {name}` first");
            return 1;
        }
    };
    let key_hex = match std::fs::read_to_string(&key_file) {
        Ok(s) => s.trim().to_string(),
        Err(_) => {
            eprintln!("no identity key at {key_file} — run `localharness create {name}` first");
            return 1;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = format!("0x{}", to_hex(&wallet::address(&signer)));
    let id = match registry::id_of_name(name).await {
        Ok(i) if i != 0 => i,
        Ok(_) => {
            eprintln!("{name} is not registered");
            return 1;
        }
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    };
    match registry::owner_of_name(name).await {
        Ok(Some(o)) if o.eq_ignore_ascii_case(&addr) => {}
        Ok(Some(o)) => {
            eprintln!("{name} is owned by {o}, not your key ({addr})");
            return 1;
        }
        _ => {
            eprintln!("{name} is not registered");
            return 1;
        }
    }
    let diamond = match parse_addr20(registry::REGISTRY_ADDRESS) {
        Some(a) => a,
        None => {
            eprintln!("internal: bad registry address constant");
            return 1;
        }
    };
    let calls = vec![tempo_tx::TempoCall {
        to: diamond,
        value_wei: 0,
        input: registry::encode_set_public_face(id, choice),
    }];
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    match registry::submit_tempo_sponsored(
        &signer,
        &sponsor,
        calls,
        registry::ALPHA_USD_ADDRESS,
        1_200_000,
    )
    .await
    {
        Ok(tx) => {
            println!("{name}.localharness.xyz public face → {choice}");
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("set-face failed: {e}");
            1
        }
    }
}

/// The on-chain `setMetadata` publish cap for a compiled cartridge (bytes).
const PUBLISH_CAP: usize = 16_384;

/// Map a filesystem IO error to a clean, OS-agnostic message. `verb` is the
/// attempted action ("read"/"write"). Addresses on-chain QA feedback: raw
/// `std::fs` errors leaked "(os error 2)" to users instead of a readable
/// "file not found".
fn clean_io_error(verb: &str, path: &str, e: &std::io::Error) -> String {
    match e.kind() {
        std::io::ErrorKind::NotFound => format!("file not found: {path}"),
        std::io::ErrorKind::PermissionDenied => format!("permission denied: {path}"),
        _ => format!("cannot {verb} {path}: {e}"),
    }
}

/// Read a file, mapping common IO errors to clean, OS-agnostic messages.
fn read_file_clean(path: &str) -> Result<String, String> {
    std::fs::read_to_string(path).map_err(|e| clean_io_error("read", path, &e))
}

/// True when `arg` looks like it was MEANT as a file path (a path separator or a
/// known text/source extension) rather than literal persona text. Used so the
/// `persona` command can give a clean "file not found" error when the user
/// clearly intended a file, instead of silently using the path string as the
/// persona OR leaking a raw "(os error 2)".
fn looks_like_path(arg: &str) -> bool {
    arg.contains('/')
        || arg.contains('\\')
        || [".txt", ".md", ".rl", ".json", ".toml", ".prompt"]
            .iter()
            .any(|ext| arg.to_ascii_lowercase().ends_with(ext))
}

/// Resolve the `persona` arg to its text: a readable file's contents, or the
/// arg used verbatim. Returns a clean error (never a raw OS error) when the arg
/// is path-shaped but unreadable. A non-path-shaped string is always literal
/// text — so a one-line persona never trips the filesystem.
fn resolve_persona_arg(text_or_path: &str) -> Result<String, String> {
    match std::fs::read_to_string(text_or_path) {
        Ok(s) => Ok(s),
        // Path-shaped + unreadable → the user meant a file; surface it cleanly.
        Err(e) if looks_like_path(text_or_path) => Err(clean_io_error("read", text_or_path, &e)),
        // Otherwise the arg IS the persona text.
        Err(_) => Ok(text_or_path.to_string()),
    }
}

/// True if the compiled cartridge exports a `frame` or `render` function — the
/// entry point the display loader calls. A cartridge without one compiles fine
/// but renders nothing as a public face. Parses the wasm export section (id 7);
/// conservative — returns false if the bytes don't parse cleanly.
fn cartridge_has_entry(wasm: &[u8]) -> bool {
    fn leb(b: &[u8], i: &mut usize) -> Option<u64> {
        let (mut result, mut shift) = (0u64, 0u32);
        loop {
            let byte = *b.get(*i)?;
            *i += 1;
            result |= ((byte & 0x7f) as u64) << shift;
            if byte & 0x80 == 0 {
                return Some(result);
            }
            shift += 7;
            if shift >= 64 {
                return None;
            }
        }
    }
    if wasm.len() < 8 || &wasm[0..4] != b"\0asm" {
        return false;
    }
    let mut i = 8; // skip magic + version
    while i < wasm.len() {
        let id = wasm[i];
        i += 1;
        let Some(size) = leb(wasm, &mut i) else {
            return false;
        };
        let section_end = i + size as usize;
        if section_end > wasm.len() {
            return false;
        }
        if id == 7 {
            let mut j = i;
            let Some(count) = leb(wasm, &mut j) else {
                return false;
            };
            for _ in 0..count {
                let Some(name_len) = leb(wasm, &mut j) else {
                    return false;
                };
                let Some(name) = wasm.get(j..j + name_len as usize) else {
                    return false;
                };
                j += name_len as usize;
                if name == b"frame" || name == b"render" {
                    return true;
                }
                j += 1; // export kind
                if leb(wasm, &mut j).is_none() {
                    return false;
                }
            }
        }
        i = section_end;
    }
    false
}

/// Compile-check a rustlite cartridge locally and report its size — NO on-chain
/// write. Lets an author iterate before spending a sponsored publish. With
/// `out_path`, also writes the compiled `.wasm` (handy for local validation).
fn compile_check(source_path: &str, out_path: Option<&str>) -> i32 {
    let src = match read_file_clean(source_path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    match localharness::rustlite::compile(&src) {
        Ok(wasm) => {
            println!("✓ compiled {source_path}{} bytes of wasm", wasm.len());
            if let Some(out) = out_path {
                if let Err(e) = std::fs::write(out, &wasm) {
                    eprintln!("  {}", clean_io_error("write", out, &e));
                    return 1;
                }
                println!("  wrote {out}");
            }
            if !cartridge_has_entry(&wasm) {
                eprintln!(
                    "  ✗ no `frame` or `render` export — the loader has no entry to \
                     call, so this would render nothing as a face"
                );
                return 1;
            }
            if wasm.len() > PUBLISH_CAP {
                eprintln!(
                    "{} bytes exceeds the {PUBLISH_CAP}-byte on-chain publish cap",
                    wasm.len()
                );
                return 1;
            }
            println!(
                "  fits the {PUBLISH_CAP}-byte publish cap ({} bytes to spare)",
                PUBLISH_CAP - wasm.len()
            );
            0
        }
        Err(e) => {
            eprintln!("compile failed: {e}");
            1
        }
    }
}

/// Compile a rustlite cartridge and publish it as `<name>`'s on-chain
/// public face — served to every visitor 24/7 with NO browser tab running.
/// Mirrors the browser studio's "publish app" exactly: setMetadata(app.wasm)
/// + setMetadata(public_face="app") in one sponsored Tempo tx.
async fn publish(name: &str, source_path: &str) -> i32 {
    // One command: if we don't hold this name's key yet (in cwd OR the config
    // home), claim the subdomain first (sponsored), then publish — no separate
    // `create` step (test-user fleet feedback, nova-qa). `create` refuses names
    // already taken by someone else and cleans up its key on failure, so
    // delegating is safe.
    if resolve_key_read_path(name).is_none() {
        eprintln!("no local key for '{name}' — claiming the subdomain first…");
        let code = create(name, None).await;
        if code != 0 {
            return code;
        }
    }
    let key_file = match resolve_key_read_path(name) {
        Some(p) => p,
        None => {
            eprintln!("could not find {name}'s key after claim");
            return 1;
        }
    };
    let key_hex = match std::fs::read_to_string(&key_file) {
        Ok(s) => s.trim().to_string(),
        Err(e) => {
            eprintln!("could not read {key_file} after claim: {e}");
            return 1;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = format!("0x{}", to_hex(&wallet::address(&signer)));

    // Only the owner can set metadata — fail early with a clear message.
    match registry::owner_of_name(name).await {
        Ok(Some(o)) if o.eq_ignore_ascii_case(&addr) => {}
        Ok(Some(o)) => {
            eprintln!("{name} is owned by {o}, not your key ({addr})");
            return 1;
        }
        Ok(None) => {
            eprintln!("{name} is not registered — run `localharness create {name}` first");
            return 1;
        }
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    }

    let src = match read_file_clean(source_path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    let wasm = match localharness::rustlite::compile(&src) {
        Ok(w) => w,
        Err(e) => {
            eprintln!("compile failed: {e}");
            return 1;
        }
    };
    // A cartridge with no entry point compiles but renders nothing — refuse to
    // publish a dead face (the visitor would see a blank canvas forever).
    if !cartridge_has_entry(&wasm) {
        eprintln!(
            "compiled cartridge has no `frame`/`render` export — it would render \
             nothing as a face; aborting before the on-chain write"
        );
        return 1;
    }
    // On-chain storage is metered per word; the studio caps published apps
    // at 16 KB. Mirror it so a too-big app fails locally, not after gas.
    if wasm.len() > PUBLISH_CAP {
        eprintln!(
            "compiled app is {} bytes; max {PUBLISH_CAP} to publish on-chain",
            wasm.len()
        );
        return 1;
    }

    let id = match registry::id_of_name(name).await {
        Ok(i) if i != 0 => i,
        _ => {
            eprintln!("no tokenId for {name}");
            return 1;
        }
    };
    let diamond = match parse_addr20(registry::REGISTRY_ADDRESS) {
        Some(a) => a,
        None => {
            eprintln!("internal: bad registry address constant");
            return 1;
        }
    };
    let mk = |input: Vec<u8>| tempo_tx::TempoCall { to: diamond, value_wei: 0, input };
    let calls = vec![
        mk(registry::encode_set_app_wasm(id, &wasm)),
        mk(registry::encode_set_public_face(id, "app")),
    ];
    // Gas budget. setMetadata stores the wasm bytes ON-CHAIN at ~7.6k gas/BYTE
    // (measured via debug_traceTransaction: a 476-byte app's storage call used
    // 3.61M gas — the same byte-storage inefficiency as the FeedbackFacet, NOT
    // the ~430k a replay misleadingly reports). Budget ~1.2M base (the
    // public_face call + AA settlement) + 8.5k/byte with headroom. Sponsor pays
    // only consumed gas. Practically this caps useful apps at a couple KB.
    let gas = 1_200_000 + (wasm.len() as u128) * 8_500;

    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    println!("publishing {} bytes as the public face of {name}.localharness.xyz …", wasm.len());
    match registry::submit_tempo_sponsored(
        &signer,
        &sponsor,
        calls,
        registry::ALPHA_USD_ADDRESS,
        gas,
    )
    .await
    {
        Ok(tx) => {
            println!("✓ published — https://{name}.localharness.xyz/ now serves your app");
            println!("  to every visitor, 24/7, with no browser tab running.");
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("publish failed: {e}");
            1
        }
    }
}

/// Prompt another agent and print its reply — HEADLESS, via the credit proxy.
///
/// No Gemini key, no live browser tab, no relay: this process runs an agent
/// turn itself, authenticating to the proxy with YOUR identity key (which
/// also spends your `$LH`) and running under the TARGET's on-chain persona so
/// it answers *as* that agent. The `?rpc=1` browser endpoint is postMessage-
/// only (tab-to-tab) and a static host can't accept an HTTP POST — so the old
/// `POST .../?rpc=1` path here always 405'd; the proxy is the real bridge.
///
///   localharness call [--as <yourname>] <target> <message…>
/// Parsed `call` arguments: the optional `--as` caller, whether `--fresh` was
/// given (start a new conversation, ignoring saved history), the target name,
/// and the joined message. Pure (no I/O) so it is unit-testable; `Err` carries
/// the usage line to print. Leading `--as`/`--fresh` flags may appear in any
/// order before the target.
struct ParsedCall {
    caller: Option<String>,
    fresh: bool,
    model: Option<String>,
    target: String,
    message: String,
}

const CALL_USAGE: &str =
    "usage: localharness call [--as <yourname>] [--fresh] [--model <id>] <target> <message>";

fn parse_call_args(rest: &[String]) -> Result<ParsedCall, String> {
    // `--as` is pulled from ANY position (via take_as_flag — consistent with
    // schedule/invite/send), so `call <target> "msg" --as me` works, not just
    // the leading form. --model/--fresh stay leading flags before the target.
    let (caller, rest) = take_as_flag(rest)?;
    let mut fresh = false;
    let mut model = None;
    let mut i = 0;
    while i < rest.len() {
        match rest[i].as_str() {
            "--model" => match rest.get(i + 1) {
                Some(m) => {
                    model = Some(m.clone());
                    i += 2;
                }
                None => return Err(CALL_USAGE.to_string()),
            },
            "--fresh" => {
                fresh = true;
                i += 1;
            }
            _ => break,
        }
    }
    match rest[i..].split_first() {
        Some((t, msg)) if !msg.is_empty() => Ok(ParsedCall {
            caller,
            fresh,
            model,
            target: t.clone(),
            message: msg.join(" "),
        }),
        _ => Err(CALL_USAGE.to_string()),
    }
}

/// The directory holding persisted `call` conversations.
fn history_dir() -> std::path::PathBuf {
    std::path::Path::new(".localharness").join("history")
}

/// The serialization-backend tag a `model` routes to. Conversation history is
/// serialized in a BACKEND-SPECIFIC wire shape (a Gemini thread loaded into the
/// Anthropic backend dies with `missing field 'content'` and vice-versa), so
/// the persisted thread is keyed by this tag — the two backends never share a
/// file. Mirrors the `claude*` → Anthropic routing in `run_agent_turn`.
fn model_backend_tag(model: Option<&str>) -> &'static str {
    if model.map(|m| m.starts_with("claude")).unwrap_or(false) {
        "anthropic"
    } else {
        "gemini"
    }
}

/// Where a `call` conversation between `caller_label` and `target` on a given
/// `backend` is persisted, so repeated calls continue the same thread. Keyed by
/// backend too so a Gemini thread and an Anthropic thread to the same target
/// never collide (their on-disk formats are incompatible). Pure path builder.
fn history_path(caller_label: &str, target: &str, backend: &str) -> std::path::PathBuf {
    history_dir().join(format!("{caller_label}__{target}.{backend}.bin"))
}

/// Extract the target from a history filename `<caller>__<target>.<backend>.bin`
/// (or the legacy `<caller>__<target>.bin`) for the given caller label. `None`
/// when it doesn't belong to that caller. Pure. A trailing `.gemini`/`.anthropic`
/// backend tag is stripped so `threads`/`forget` show the bare target.
fn thread_file_target(caller_label: &str, file_name: &str) -> Option<String> {
    let stem = file_name
        .strip_prefix(&format!("{caller_label}__"))?
        .strip_suffix(".bin")
        .filter(|t| !t.is_empty())?;
    // Drop a known backend tag if present (newer files); legacy files have none.
    let target = stem
        .strip_suffix(".gemini")
        .or_else(|| stem.strip_suffix(".anthropic"))
        .unwrap_or(stem);
    if target.is_empty() {
        return None;
    }
    Some(target.to_string())
}

/// Map a failed `call` error to an actionable hint, if recognisable. Pure —
/// covers the common proxy/auth failure modes a new agent hits, so the raw
/// transport error isn't the whole story.
fn hint_for_call_error(err: &str) -> Option<&'static str> {
    let e = err.to_ascii_lowercase();
    if e.contains("402")
        || e.contains("payment")
        || e.contains("no session")
        || e.contains("insufficient")
        || e.contains("credit")
    {
        return Some(
            "the credit proxy has no $LH for your identity. `call` meters \
             ~0.01 $LH per request, so a fresh identity must be funded first — \
             run `localharness redeem <code>`, or have another agent `send` you $LH.",
        );
    }
    if e.contains("401")
        || e.contains("403")
        || e.contains("unauthorized")
        || e.contains("forbidden")
        || e.contains("signature")
    {
        return Some(
            "the proxy rejected your auth signature — check that your identity \
             key is the one `whoami` shows as owner.",
        );
    }
    if e.contains("429") || e.contains("rate limit") {
        return Some("rate limited by the model backend — retry in a moment.");
    }
    None
}

/// Print an error line plus its actionable hint, if any.
fn report_call_error(prefix: &str, err: &str) {
    eprintln!("{prefix}: {err}");
    if let Some(hint) = hint_for_call_error(err) {
        eprintln!("  hint: {hint}");
    }
}

async fn call(rest: &[String]) -> i32 {
    let ParsedCall {
        caller,
        fresh,
        model,
        target,
        message,
    } = match parse_call_args(rest) {
        Ok(p) => p,
        Err(usage) => {
            eprintln!("{usage}");
            return 2;
        }
    };

    // Resolve the caller's identity key — it signs proxy auth + pays $LH.
    let (key_file, key_hex) = match resolve_caller_key(caller.as_deref()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    // Conversations persist per (caller, target, backend) so repeated calls
    // continue the same thread; `--fresh` starts over. Label by the key-file
    // stem. Keying on the backend too keeps a Gemini thread and an Anthropic
    // thread to the same target in SEPARATE files — their on-disk history
    // formats are incompatible (a Gemini thread loaded into the Anthropic
    // backend dies with `missing field 'content'`).
    // Label by the bare key-file stem (basename), so a cwd key and a config-home
    // key for the same name share one history thread.
    let caller_base = std::path::Path::new(&key_file)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(&key_file);
    let caller_label = caller_base
        .strip_suffix(".localharness.key")
        .unwrap_or(caller_base)
        .to_string();
    let backend = model_backend_tag(model.as_deref());
    let hist_file = history_path(&caller_label, &target, backend);
    let prior_history = if fresh {
        let _ = std::fs::remove_file(&hist_file);
        None
    } else {
        // A read failure (missing/corrupt file) is non-fatal: start fresh.
        std::fs::read(&hist_file).ok()
    };
    match run_agent_turn(&key_hex, &target, &message, prior_history, model.as_deref()).await {
        Ok((text, new_history)) => {
            println!("{}", text.trim());
            // Persist the conversation so the next `call` to this target
            // continues it. Best-effort: a save failure must not flip the code.
            if let Some(bytes) = new_history {
                if let Some(dir) = hist_file.parent() {
                    let _ = std::fs::create_dir_all(dir);
                }
                let _ = std::fs::write(&hist_file, bytes);
            }
            0
        }
        Err(e) => {
            report_call_error("call failed", &e);
            1
        }
    }
}

/// Run ONE headless conversational turn as `target` — embodying its on-chain
/// persona, paid for by the identity behind `key_hex` (proxy auth + ~0.01 $LH
/// debited from its per-request meter, which this funds lazily — NOT an hourly
/// session). Returns the reply text plus the updated conversation history bytes
/// (to persist for the next turn). Shared by the CLI `call` command and the
/// `mcp` server's `call_agent` tool, so both reach an agent identically.
async fn run_agent_turn(
    key_hex: &str,
    target: &str,
    message: &str,
    prior_history: Option<Vec<u8>>,
    model: Option<&str>,
) -> Result<(String, Option<Vec<u8>>), String> {
    let caller =
        wallet::from_private_key_hex(key_hex).map_err(|e| format!("bad identity key: {e}"))?;

    // Embody the target's PUBLISHED persona (falls back to a generic prompt).
    let system = match registry::id_of_name(target).await {
        Ok(id) if id != 0 => match registry::persona_of(id).await {
            Ok(Some(p)) => p,
            Ok(None) => default_persona(target),
            Err(e) => return Err(format!("RPC error reading persona: {e}")),
        },
        Ok(_) => return Err(format!("{target} is not a registered agent")),
        Err(e) => return Err(format!("RPC error: {e}")),
    };

    // Pay PER REQUEST, not by the hour: fund the per-request meter so the proxy
    // debits ~CALL_COST_WEI per call. A one-shot agent call must NOT buy a
    // 10-$LH hour-long session (the old behavior). Best-effort + sponsored; an
    // unfunded wallet stays unfunded (the proxy 402s, the hint says to redeem).
    if let Ok(sponsor) = wallet::from_private_key_hex(SPONSOR_KEY) {
        let addr = addr_to_hex(wallet::address(&caller));
        if registry::credit_balance_of(&addr).await.unwrap_or(0) < CALL_COST_WEI {
            let _ = registry::deposit_credits_sponsored(
                &caller,
                &sponsor,
                CALL_METER_TOPUP_WEI,
                registry::ALPHA_USD_ADDRESS,
            )
            .await;
        }
    }

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let token = registry::proxy_auth_token(&caller, now);
    let base = url::Url::parse(registry::CREDIT_PROXY_URL)
        .map_err(|e| format!("internal: bad proxy url: {e}"))?;

    // A pure conversational turn: no local builtins (a remote prompt must not
    // read the CALLER's filesystem), no subagents.
    let caps = localharness::types::CapabilitiesConfig {
        enabled_tools: Some(Vec::new()),
        enable_subagents: false,
        ..Default::default()
    };
    // Route by model: a `claude-*` id uses the Anthropic backend; anything else
    // (or none) uses Gemini. BOTH reach the model the same way — through the
    // credit proxy with the same signed token — so a subsidized identity calls
    // either provider with no provider key of its own.
    if model.map(|m| m.starts_with("claude")).unwrap_or(false) {
        #[cfg(feature = "anthropic")]
        {
            let model = model.unwrap().to_string();
            // Build a config, optionally seeded with prior history. Cloned inputs
            // so a failed history-seeded start can be retried from scratch.
            let build = |history: Option<Vec<u8>>| {
                let mut cfg = localharness::AnthropicAgentConfig::new(token.clone())
                    .with_base_url(base.clone())
                    .with_model(model.clone())
                    .with_system_instructions(system.clone())
                    .with_capabilities(caps.clone());
                if let Some(bytes) = history {
                    cfg = cfg.with_history_bytes(bytes);
                }
                cfg
            };
            let agent = match localharness::Agent::start_anthropic(build(prior_history.clone())).await
            {
                Ok(a) => a,
                Err(_) if prior_history.is_some() => {
                    // Incompatible/corrupt saved thread → warn + start fresh
                    // rather than failing the whole call.
                    eprintln!(
                        "warning: could not load saved conversation with {target} \
                         (incompatible or corrupt) — starting a fresh thread"
                    );
                    localharness::Agent::start_anthropic(build(None))
                        .await
                        .map_err(|e| format!("could not start anthropic session: {e}"))?
                }
                Err(e) => return Err(format!("could not start anthropic session: {e}")),
            };
            let reply = match agent.chat(message).await {
                Ok(resp) => resp.text().await.map_err(|e| format!("response error: {e}")),
                Err(e) => Err(e.to_string()),
            };
            let new_history = agent.history_bytes().ok().flatten();
            let _ = agent.shutdown().await;
            return reply.map(|text| (text, new_history));
        }
        #[cfg(not(feature = "anthropic"))]
        {
            return Err("Claude models require a build with `--features anthropic`".to_string());
        }
    }

    let build = |history: Option<Vec<u8>>| {
        let mut cfg = localharness::GeminiAgentConfig::new(token.clone())
            .with_base_url(base.clone())
            .with_system_instructions(system.clone())
            .with_capabilities(caps.clone());
        if let Some(bytes) = history {
            cfg = cfg.with_history_bytes(bytes);
        }
        cfg
    };
    let agent = match localharness::Agent::start_gemini(build(prior_history.clone())).await {
        Ok(a) => a,
        Err(_) if prior_history.is_some() => {
            // Incompatible/corrupt saved thread → warn + start fresh rather than
            // failing the whole call.
            eprintln!(
                "warning: could not load saved conversation with {target} \
                 (incompatible or corrupt) — starting a fresh thread"
            );
            localharness::Agent::start_gemini(build(None))
                .await
                .map_err(|e| format!("could not start agent session: {e}"))?
        }
        Err(e) => return Err(format!("could not start agent session: {e}")),
    };
    let reply = match agent.chat(message).await {
        Ok(resp) => resp.text().await.map_err(|e| format!("response error: {e}")),
        Err(e) => Err(e.to_string()),
    };
    let new_history = agent.history_bytes().ok().flatten();
    let _ = agent.shutdown().await;
    reply.map(|text| (text, new_history))
}

// ---- MCP server ----------------------------------------------------------
//
// `localharness mcp` speaks the Model Context Protocol over stdio (newline-
// delimited JSON-RPC 2.0), exposing localharness agents as a TOOL any MCP client
// (Claude Code, Codex, …) can call. The headline tool `call_agent` lets an
// external agent invoke a sovereign `<name>.localharness.xyz` agent under its
// on-chain persona — the demand-side experiment: will anyone actually call these
// agents? The server acts AS the sole identity key in the working directory (it
// signs proxy auth and pays the $LH).

async fn mcp_serve(args: &[String]) -> i32 {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

    // The identity that signs proxy auth + pays for outbound calls. `--as <name>`
    // picks it; with a single key in the dir it's inferred.
    let caller = match take_as_flag(args) {
        Ok((caller, _rest)) => caller,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let key_hex = match resolve_caller_key(caller.as_deref()) {
        Ok((_file, hex)) => hex,
        Err(e) => {
            eprintln!("mcp: no usable identity ({e}). Pass --as <name> or run `localharness create <name>` first.");
            return 2;
        }
    };

    let mut lines = BufReader::new(tokio::io::stdin()).lines();
    let mut out = tokio::io::stdout();
    eprintln!("localharness mcp: ready on stdio (acting as the local identity).");

    while let Ok(Some(line)) = lines.next_line().await {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let req: serde_json::Value = match serde_json::from_str(line) {
            Ok(v) => v,
            Err(_) => continue, // ignore malformed frames
        };
        // Notifications (no `id`, e.g. notifications/initialized) get no reply.
        let Some(id) = req.get("id").cloned() else { continue };
        let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");

        let envelope = match mcp_handle(method, &req, &key_hex).await {
            Ok(result) => serde_json::json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err((code, msg)) => {
                serde_json::json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": msg}})
            }
        };
        if out.write_all(format!("{envelope}\n").as_bytes()).await.is_err() {
            break;
        }
        let _ = out.flush().await;
    }
    0
}

async fn mcp_handle(
    method: &str,
    req: &serde_json::Value,
    key_hex: &str,
) -> Result<serde_json::Value, (i64, String)> {
    match method {
        "initialize" => Ok(serde_json::json!({
            "protocolVersion": "2024-11-05",
            "capabilities": { "tools": {} },
            "serverInfo": { "name": "localharness", "version": env!("CARGO_PKG_VERSION") }
        })),
        "tools/list" => Ok(serde_json::json!({ "tools": mcp_tool_list() })),
        "tools/call" => {
            let params = req.get("params").cloned().unwrap_or_default();
            let name = params.get("name").and_then(|n| n.as_str()).unwrap_or("");
            let args = params.get("arguments").cloned().unwrap_or_default();
            mcp_tool_call(name, &args, key_hex).await
        }
        "ping" => Ok(serde_json::json!({})),
        other => Err((-32601, format!("method not found: {other}"))),
    }
}

fn mcp_tool_list() -> serde_json::Value {
    serde_json::json!([
        {
            "name": "call_agent",
            "description": "Send a message to a sovereign localharness agent (a <name>.localharness.xyz NFT) and get its reply. The agent answers under its published on-chain persona; this server's configured identity pays in $LH credits.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "the agent's registered name / subdomain, e.g. \"claude\"" },
                    "message": { "type": "string", "description": "the message to send the agent" }
                },
                "required": ["name", "message"]
            }
        }
    ])
}

async fn mcp_tool_call(
    name: &str,
    args: &serde_json::Value,
    key_hex: &str,
) -> Result<serde_json::Value, (i64, String)> {
    match name {
        "call_agent" => {
            let target = args.get("name").and_then(|v| v.as_str()).unwrap_or("").trim();
            let message = args.get("message").and_then(|v| v.as_str()).unwrap_or("");
            if target.is_empty() || message.trim().is_empty() {
                return Ok(mcp_text_result("call_agent requires both 'name' and 'message'", true));
            }
            // Stateless per MCP request for v1 (no persisted thread).
            match run_agent_turn(key_hex, target, message, None, None).await {
                Ok((text, _hist)) => Ok(mcp_text_result(text.trim(), false)),
                Err(e) => Ok(mcp_text_result(&format!("call_agent failed: {e}"), true)),
            }
        }
        other => Err((-32602, format!("unknown tool: {other}"))),
    }
}

fn mcp_text_result(text: &str, is_error: bool) -> serde_json::Value {
    serde_json::json!({
        "content": [ { "type": "text", "text": text } ],
        "isError": is_error
    })
}

// ---- mcp-call: the HOSTED MCP-over-HTTP + x402 client --------------------
//
// `mcp_serve` (above) is the LOCAL stdio MCP *server*. `mcp_call` is the
// *client* for the REMOTE MCP-over-HTTP endpoint shipped in `proxy/api/mcp.ts`
// (`<proxy>/mcp`). That endpoint gates every `tools/call` behind TRUE x402
// per-call settlement: the caller signs a `PaymentAuthorization` (EIP-712, in
// $LH) paying the TARGET agent's token-bound account, the proxy verifies it
// against the live `x402DomainSeparator()` and runs `X402Facet.settle(...)`
// on-chain BEFORE answering. This command is the round-trip that had no client.

/// Default `$LH` paid per `mcp-call` when `--pay` is omitted (0.001 $LH).
const MCP_CALL_DEFAULT_PAY: &str = "0.001";

/// Parsed `mcp-call` arguments: optional `--as` caller, optional `--pay`
/// amount (human-typed $LH, e.g. "0.001"), the target agent name, and the
/// joined message. Pure (no I/O) so it is unit-testable; `Err` carries the
/// usage line. Leading flags may appear in any order before the target.
struct ParsedMcpCall {
    caller: Option<String>,
    pay: String,
    target: String,
    message: String,
}

const MCP_CALL_USAGE: &str =
    "usage: localharness mcp-call [--as <yourname>] [--pay <amount>] <target> <message>";

fn parse_mcp_call_args(rest: &[String]) -> Result<ParsedMcpCall, String> {
    // `--as` from ANY position (take_as_flag — consistent with the other
    // commands); --pay stays a leading flag before the target.
    let (caller, rest) = take_as_flag(rest)?;
    let mut pay = MCP_CALL_DEFAULT_PAY.to_string();
    let mut i = 0;
    while i < rest.len() {
        match rest[i].as_str() {
            "--pay" => match rest.get(i + 1) {
                Some(p) => {
                    pay = p.clone();
                    i += 2;
                }
                None => return Err(MCP_CALL_USAGE.to_string()),
            },
            _ => break,
        }
    }
    match rest[i..].split_first() {
        Some((t, msg)) if !msg.is_empty() => Ok(ParsedMcpCall {
            caller,
            pay,
            target: t.clone(),
            message: msg.join(" "),
        }),
        _ => Err(MCP_CALL_USAGE.to_string()),
    }
}

/// Build the JSON the `x-x402-authorization` header carries, matching the shape
/// `proxy/api/mcp.ts::parseAuth` expects EXACTLY: addresses as 0x-hex, `value`
/// as a decimal string of `$LH` wei, `nonce` as 0x + 32-byte hex, `signature`
/// as 0x + 65-byte hex, `validAfter`/`validBefore` as numbers. Pure — the
/// signature/nonce are passed in so this is deterministic and testable.
fn mcp_x402_header_json(
    from_hex: &str,
    to_hex: &str,
    value_wei: u128,
    valid_after: u64,
    valid_before: u64,
    nonce: &[u8; 32],
    signature: &[u8; 65],
) -> serde_json::Value {
    serde_json::json!({
        "from": from_hex,
        "to": to_hex,
        "value": value_wei.to_string(),
        "validAfter": valid_after,
        "validBefore": valid_before,
        "nonce": format!("0x{}", to_hex_str(nonce)),
        "signature": format!("0x{}", to_hex_str(signature)),
    })
}

/// The `tools/call` JSON-RPC body the hosted endpoint expects: it routes the
/// single `ask_agent` tool, with the target name + message in `arguments`
/// (see `proxy/api/mcp.ts` — `params.name` is the TOOL name "ask_agent", and
/// `params.arguments = { name: <target>, message }`).
fn mcp_tools_call_body(target: &str, message: &str) -> serde_json::Value {
    serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "ask_agent",
            "arguments": { "name": target, "message": message }
        }
    })
}

/// Lowercase hex of a byte slice (local mirror of the registry's encoder so the
/// bin needn't reach into private fns).
fn to_hex_str(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Client for the hosted MCP-over-HTTP + x402 endpoint (`<proxy>/mcp`). Resolve
/// the caller key + the target's TBA, sign an x402 `$LH` payment to it, ensure
/// the diamond is approved to pull the $LH (auto-approve if short), POST the
/// `tools/call`, and print the agent's reply.
async fn mcp_call(rest: &[String]) -> i32 {
    let ParsedMcpCall {
        caller,
        pay,
        target,
        message,
    } = match parse_mcp_call_args(rest) {
        Ok(p) => p,
        Err(usage) => {
            eprintln!("{usage}");
            return 2;
        }
    };

    // The amount to pay, in 18-decimal $LH wei (same parse the bundle uses).
    let value_wei = match localharness::encoding::parse_token_amount(&pay) {
        Some(v) if v > 0 => v,
        _ => {
            eprintln!("--pay must be a positive $LH amount (e.g. 0.001), got '{pay}'");
            return 2;
        }
    };

    // 1. Resolve the caller's identity key — it signs the x402 authorization.
    let (_key_file, key_hex) = match resolve_caller_key(caller.as_deref()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad identity key: {e}");
            return 1;
        }
    };
    let from_bytes = wallet::address(&signer);
    let from_hex = format!("0x{}", to_hex_str(&from_bytes));

    // Resolve the payee = the target agent's token-bound account.
    let to_hex = match registry::tba_of_name(&target).await {
        Ok(Some(t)) => t,
        Ok(None) => {
            eprintln!(
                "'{target}' has no token-bound account to receive payment \
                 (is it registered? try `localharness whoami {target}`)"
            );
            return 1;
        }
        Err(e) => {
            eprintln!("RPC error resolving {target}: {e}");
            return 1;
        }
    };
    let to_bytes = match parse_addr20(&to_hex) {
        Some(b) => b,
        None => {
            eprintln!("internal: bad TBA address for {target}: {to_hex}");
            return 1;
        }
    };

    // 2. Build + sign the PaymentAuthorization (EIP-712 over the live x402
    //    domain separator — `registry::sign_x402` does the digest internally).
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let valid_after: u64 = 0;
    let valid_before: u64 = now + 3600; // 1h window
    let nonce = registry::random_x402_nonce();
    let signature = match registry::sign_x402(
        &signer,
        &from_bytes,
        &to_bytes,
        value_wei,
        valid_after,
        valid_before,
        &nonce,
    ) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("could not sign x402 authorization: {e}");
            return 1;
        }
    };

    // 3. ALLOWANCE: `settle` pulls $LH from the payer via the diamond's
    //    `transferFrom`, so the payer must have approved the diamond. If the
    //    current allowance is short, approve once (sponsored) up to u128::MAX.
    match registry::lh_allowance(&from_hex, registry::REGISTRY_ADDRESS).await {
        Ok(allowance) if allowance >= value_wei => {}
        Ok(_) => {
            println!("approving the diamond to spend $LH (one-time) …");
            let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sponsor key error: {e}");
                    return 1;
                }
            };
            match registry::approve_lh_sponsored(
                &signer,
                &sponsor,
                registry::REGISTRY_ADDRESS,
                u128::MAX,
                registry::ALPHA_USD_ADDRESS,
            )
            .await
            {
                Ok(tx) => println!("  approved (tx {tx})"),
                Err(e) => {
                    eprintln!("could not approve $LH spend automatically: {e}");
                    eprintln!(
                        "  fix it once, then retry: approve {} to spend $LH \
                         (token {}) for {from_hex}.",
                        registry::REGISTRY_ADDRESS,
                        registry::LOCALHARNESS_TOKEN_ADDRESS
                    );
                    return 1;
                }
            }
        }
        Err(e) => {
            // A read failure shouldn't hard-block the attempt — settle is the
            // authoritative gate — but warn so an opaque revert is explicable.
            eprintln!("warning: could not read $LH allowance ({e}); attempting the call anyway");
        }
    }

    // 4. POST the tools/call to <proxy>/mcp with the x402 header.
    let header_json = mcp_x402_header_json(
        &from_hex,
        &to_hex,
        value_wei,
        valid_after,
        valid_before,
        &nonce,
        &signature,
    );
    let body = mcp_tools_call_body(&target, &message);
    let endpoint = mcp_endpoint_url();

    let client = reqwest::Client::new();
    let resp = match client
        .post(&endpoint)
        .header("content-type", "application/json")
        .header("x-x402-authorization", header_json.to_string())
        .json(&body)
        .send()
        .await
    {
        Ok(r) => r,
        Err(e) => {
            report_call_error("mcp-call failed (request)", &e.to_string());
            return 1;
        }
    };
    let json: serde_json::Value = match resp.json().await {
        Ok(j) => j,
        Err(e) => {
            eprintln!("mcp-call failed: could not decode JSON-RPC response: {e}");
            return 1;
        }
    };

    // 5. Parse the JSON-RPC envelope.
    if let Some(err) = json.get("error") {
        let code = err.get("code").and_then(|c| c.as_i64()).unwrap_or(0);
        let msg = err.get("message").and_then(|m| m.as_str()).unwrap_or("(no message)");
        eprintln!("mcp-call error {code}: {msg}");
        if let Some(hint) = hint_for_call_error(&format!("{code} {msg}")) {
            eprintln!("  hint: {hint}");
        }
        return 1;
    }
    let result = match json.get("result") {
        Some(r) => r,
        None => {
            eprintln!("mcp-call failed: response has neither result nor error: {json}");
            return 1;
        }
    };
    // A tool-level failure (e.g. the agent settled-but-errored) rides in
    // `result.isError` with the text in `content[0].text`.
    let text = result
        .get("content")
        .and_then(|c| c.as_array())
        .and_then(|a| a.first())
        .and_then(|c| c.get("text"))
        .and_then(|t| t.as_str());
    let is_error = result.get("isError").and_then(|b| b.as_bool()).unwrap_or(false);
    match text {
        Some(t) if is_error => {
            eprintln!("{}", t.trim());
            1
        }
        Some(t) => {
            println!("{}", t.trim());
            0
        }
        None => {
            eprintln!("mcp-call: response had no text content: {result}");
            1
        }
    }
}

/// The hosted MCP endpoint URL: `<CREDIT_PROXY_URL>/mcp`. Joins safely whether
/// or not the base has a trailing slash.
fn mcp_endpoint_url() -> String {
    let base = registry::CREDIT_PROXY_URL.trim_end_matches('/');
    format!("{base}/mcp")
}

const KEY_SUFFIX: &str = ".localharness.key";

/// Pure resolution of the config-home dir from raw env values (extracted so it's
/// unit-testable without mutating process-global env): `$LOCALHARNESS_HOME` if
/// non-empty, else `<home>/.localharness/keys` where `<home>` is `%USERPROFILE%`
/// (Windows) / `$HOME` (Unix). `None` when none are set.
fn key_home_dir_from(
    localharness_home: Option<&str>,
    userprofile: Option<&str>,
    home: Option<&str>,
) -> Option<std::path::PathBuf> {
    if let Some(h) = localharness_home.filter(|s| !s.is_empty()) {
        return Some(std::path::PathBuf::from(h));
    }
    let h = userprofile
        .filter(|s| !s.is_empty())
        .or_else(|| home.filter(|s| !s.is_empty()))?;
    Some(std::path::Path::new(h).join(".localharness").join("keys"))
}

/// The config home for identity keys — the SAFE location, out of any project's
/// working directory so a private key can't be accidentally `git commit`ed
/// (the test-user fleet's security persona asked for this twice). Resolution:
/// `$LOCALHARNESS_HOME` if set, else `<home>/.localharness/keys`, where `<home>`
/// is `%USERPROFILE%` on Windows / `$HOME` on Unix. No new crate dep — the home
/// dir is read from the env. Returns `None` only if neither env var is set
/// (then we fall back to the cwd, preserving the old behavior).
fn key_home_dir() -> Option<std::path::PathBuf> {
    let lh = std::env::var("LOCALHARNESS_HOME").ok();
    let up = std::env::var("USERPROFILE").ok();
    let home = std::env::var("HOME").ok();
    key_home_dir_from(lh.as_deref(), up.as_deref(), home.as_deref())
}

/// The config-home path for `<name>`'s key, if a home dir is resolvable.
fn home_key_path(name: &str) -> Option<std::path::PathBuf> {
    key_home_dir().map(|d| d.join(format!("{name}{KEY_SUFFIX}")))
}

/// The cwd path for `<name>`'s key (the legacy / back-compat location).
fn cwd_key_path(name: &str) -> String {
    format!("{name}{KEY_SUFFIX}")
}

/// Pure precedence rule for reading a key (extracted so it's unit-testable
/// without touching the filesystem): the cwd path wins if it exists (back-compat
/// — pre-existing local keys and the test-fleet's keep working), else the config
/// home if that exists, else `None`.
fn pick_key_read_path(
    cwd: String,
    cwd_exists: bool,
    home: Option<String>,
    home_exists: bool,
) -> Option<String> {
    if cwd_exists {
        return Some(cwd);
    }
    match home {
        Some(h) if home_exists => Some(h),
        _ => None,
    }
}

/// Where to READ `<name>`'s key from, honoring back-compat: prefer the cwd file
/// if it exists (so keys created before this change, and the test-fleet's, keep
/// resolving), else the config home. `None` when neither exists.
fn resolve_key_read_path(name: &str) -> Option<String> {
    let cwd = cwd_key_path(name);
    let cwd_exists = std::path::Path::new(&cwd).exists();
    let home = home_key_path(name);
    let home_exists = home.as_ref().map(|p| p.exists()).unwrap_or(false);
    pick_key_read_path(
        cwd,
        cwd_exists,
        home.map(|p| p.to_string_lossy().into_owned()),
        home_exists,
    )
}

/// Where to WRITE a NEW key for `<name>`: the config home (the safe default),
/// creating the directory first. Falls back to the cwd if no home dir is
/// resolvable or the directory can't be created — never blocks a `create`.
/// Existing cwd keys are left untouched (this only governs fresh writes).
fn key_write_path(name: &str) -> String {
    if let Some(home) = home_key_path(name) {
        if let Some(dir) = home.parent() {
            if std::fs::create_dir_all(dir).is_ok() {
                // Owner-only dir perms where the platform supports it.
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
                }
                return home.to_string_lossy().into_owned();
            }
        }
    }
    cwd_key_path(name)
}

/// Sorted display paths of every identity key, scanning BOTH the working
/// directory (back-compat) and the config home, deduped by name (cwd wins so a
/// local key shadows a same-named home key). The returned strings are usable
/// paths (relative for cwd, absolute for the home dir).
fn identity_key_files() -> Result<Vec<String>, String> {
    use std::collections::BTreeMap;
    // stem (name) -> path. cwd inserted last so it overrides a home key.
    let mut by_name: BTreeMap<String, String> = BTreeMap::new();
    let mut scan = |dir: &std::path::Path, absolute: bool| {
        if let Ok(rd) = std::fs::read_dir(dir) {
            for e in rd.flatten() {
                if let Ok(f) = e.file_name().into_string() {
                    if let Some(stem) = f.strip_suffix(KEY_SUFFIX) {
                        let path = if absolute {
                            dir.join(&f).to_string_lossy().into_owned()
                        } else {
                            f.clone()
                        };
                        by_name.insert(stem.to_string(), path);
                    }
                }
            }
        }
    };
    if let Some(home) = key_home_dir() {
        scan(&home, true);
    }
    // cwd last → wins on name collision (a local key keeps working).
    scan(std::path::Path::new("."), false);
    Ok(by_name.into_values().collect())
}

/// `true` if `.gitignore` content already excludes identity keys — the wildcard
/// `*.localharness.key` or the exact file, on any non-comment line.
fn gitignore_already_covers(existing: &str, key_file: &str) -> bool {
    existing.lines().any(|l| {
        let t = l.trim();
        t == "*.localharness.key" || t == key_file
    })
}

/// `true` if `key_file` is a bare cwd filename (no directory component) — keys
/// in the config home live outside any project repo, so they need no
/// `.gitignore` entry.
fn key_is_in_cwd(key_file: &str) -> bool {
    !key_file.contains('/') && !key_file.contains('\\')
}

/// Lock down a freshly-written identity key (a fix the on-chain test-user fleet
/// asked for): owner-only file perms (0600, unix) always, plus — only for a key
/// written into the working directory (back-compat fallback) — ensure
/// `.gitignore` excludes `*.localharness.key` so a raw private key can't be
/// accidentally `git commit`ed. NEW keys now default to the config home
/// (`key_write_path`), out of any repo, so this is a belt-and-suspenders for the
/// cwd fallback. Best-effort — never fails the create. Returns whether
/// `.gitignore` was created/appended.
fn secure_key_file(key_file: &str) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(key_file, std::fs::Permissions::from_mode(0o600));
    }
    // A config-home key isn't inside a project — nothing to gitignore.
    if !key_is_in_cwd(key_file) {
        return false;
    }
    match std::fs::read_to_string(".gitignore") {
        Ok(existing) => {
            if gitignore_already_covers(&existing, key_file) {
                false
            } else {
                let sep = if existing.is_empty() || existing.ends_with('\n') { "" } else { "\n" };
                std::fs::write(".gitignore", format!("{existing}{sep}*.localharness.key\n")).is_ok()
            }
        }
        Err(_) => std::fs::write(".gitignore", "*.localharness.key\n").is_ok(),
    }
}

/// The readable identity-key path to act as. With `name`, the back-compat
/// resolved path (cwd first, else the config home — `resolve_key_read_path`);
/// the path is `<name>.localharness.key` when nothing exists yet so callers can
/// surface a "run create first" error. Without a name, the sole key across both
/// locations — error (asking for `--as`) on zero or several.
fn resolve_caller_file(name: Option<&str>) -> Result<String, String> {
    if let Some(n) = name {
        return Ok(resolve_key_read_path(n).unwrap_or_else(|| cwd_key_path(n)));
    }
    let mut found = identity_key_files()?;
    match found.len() {
        0 => Err(
            "no identity key — run `localharness create <yourname>` first, \
             or pass --as <name>"
                .to_string(),
        ),
        1 => Ok(found.remove(0)),
        _ => Err(format!(
            "multiple identities ({}) — pick one with --as <name>",
            found.join(", ")
        )),
    }
}

/// The thread label (key-file stem) to act as — what conversation history is
/// keyed on. Does NOT read the key, so it works for `threads` / `forget`. The
/// label is the bare name (basename stem), never the directory path.
fn resolve_caller_label(name: Option<&str>) -> Result<String, String> {
    if let Some(n) = name {
        return Ok(n.to_string());
    }
    let file = resolve_caller_file(None)?;
    let base = std::path::Path::new(&file)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(&file);
    Ok(base.strip_suffix(KEY_SUFFIX).unwrap_or(base).to_string())
}

/// Resolve which identity key signs a `call`, returning `(filename, key_hex)`.
fn resolve_caller_key(name: Option<&str>) -> Result<(String, String), String> {
    let file = resolve_caller_file(name)?;
    let key_hex = std::fs::read_to_string(&file)
        .map_err(|_| match name {
            Some(n) => format!("no identity key at {file} — run `localharness create {n}` first"),
            None => format!("cannot read {file}"),
        })?
        .trim()
        .to_string();
    if key_hex.is_empty() {
        return Err(format!(
            "{file} is empty — recreate it with `localharness create <name>`"
        ));
    }
    Ok((file, key_hex))
}

/// Extract a `--as <name>` flag from ANYWHERE in the arg list (not just the
/// first position) and return `(caller, remaining_args_without_the_flag)`. The
/// remainder is owned so the flag can be removed from the middle. Position-
/// fragile parsing was a real bug: `probe --deep --as fleet` failed because
/// `--as` wasn't first, so the fleet name was never resolved and the call
/// errored with "multiple identities". A second `--as` is an error.
fn take_as_flag(args: &[String]) -> Result<(Option<String>, Vec<String>), String> {
    let mut caller: Option<String> = None;
    let mut rest: Vec<String> = Vec::with_capacity(args.len());
    let mut i = 0;
    while i < args.len() {
        if args[i] == "--as" {
            if caller.is_some() {
                return Err("--as given more than once".to_string());
            }
            match args.get(i + 1) {
                Some(n) => {
                    caller = Some(n.clone());
                    i += 2;
                }
                None => return Err("usage: --as <name> requires a name".to_string()),
            }
        } else {
            rest.push(args[i].clone());
            i += 1;
        }
    }
    Ok((caller, rest))
}

/// List the caller's saved conversation threads (`localharness threads`).
fn threads(caller_name: Option<&str>) -> i32 {
    let label = match resolve_caller_label(caller_name) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let mut found: Vec<(String, u64)> = match std::fs::read_dir(history_dir()) {
        Ok(rd) => rd
            .filter_map(|e| e.ok())
            .filter_map(|e| {
                let name = e.file_name().into_string().ok()?;
                let target = thread_file_target(&label, &name)?;
                let size = e.metadata().map(|m| m.len()).unwrap_or(0);
                Some((target, size))
            })
            .collect(),
        Err(_) => Vec::new(),
    };
    found.sort();
    if found.is_empty() {
        println!("no saved conversations for {label}");
        return 0;
    }
    println!("conversations for {label}:");
    for (target, size) in found {
        println!("  {target}  ({size} bytes)");
    }
    0
}

/// Delete a saved conversation thread, or all of the caller's with `--all`
/// (`localharness forget [--as me] <target|--all>`). Never touches identity
/// keys or on-chain state — only local history files.
fn forget(caller_name: Option<&str>, target: &str) -> i32 {
    let label = match resolve_caller_label(caller_name) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    if target == "--all" {
        let mut n = 0;
        if let Ok(rd) = std::fs::read_dir(history_dir()) {
            for e in rd.flatten() {
                let Ok(name) = e.file_name().into_string() else {
                    continue;
                };
                if thread_file_target(&label, &name).is_some()
                    && std::fs::remove_file(e.path()).is_ok()
                {
                    n += 1;
                }
            }
        }
        println!("forgot {n} conversation(s) for {label}");
        return 0;
    }
    // A target can have a thread per backend (plus a legacy untagged file);
    // forget them all so `forget <target>` clears the conversation regardless
    // of which model it ran under.
    let mut removed = false;
    for candidate in [
        history_path(&label, target, "gemini"),
        history_path(&label, target, "anthropic"),
        history_dir().join(format!("{label}__{target}.bin")), // legacy untagged
    ] {
        if std::fs::remove_file(candidate).is_ok() {
            removed = true;
        }
    }
    if removed {
        println!("forgot conversation with {target}");
    } else {
        println!("no saved conversation with {target}");
    }
    0
}

/// System prompt for a target that hasn't published a persona on-chain.
fn default_persona(name: &str) -> String {
    format!(
        "You are {name}, an autonomous agent on localharness reachable at \
         {name}.localharness.xyz. Another agent is contacting you over the \
         network. Answer concisely and in character as {name}. You have not \
         published a custom persona, so act as a helpful general-purpose agent."
    )
}

/// Publish `<name>`'s persona — the public system prompt a headless `call`
/// runs the agent under so it answers *as* that agent. Owner-gated
/// `setMetadata`, sponsored. `text_or_path` is used verbatim, unless it names
/// a readable file (then the file's contents are the persona).
async fn set_persona(name: &str, text_or_path: &str) -> i32 {
    let key_file = match resolve_key_read_path(name) {
        Some(p) => p,
        None => {
            eprintln!("no identity key for {name} — run `localharness create {name}` first");
            return 1;
        }
    };
    let key_hex = match std::fs::read_to_string(&key_file) {
        Ok(s) => s.trim().to_string(),
        Err(_) => {
            eprintln!("no identity key at {key_file} — run `localharness create {name}` first");
            return 1;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = format!("0x{}", to_hex(&wallet::address(&signer)));

    match registry::owner_of_name(name).await {
        Ok(Some(o)) if o.eq_ignore_ascii_case(&addr) => {}
        Ok(Some(o)) => {
            eprintln!("{name} is owned by {o}, not your key ({addr})");
            return 1;
        }
        Ok(None) => {
            eprintln!("{name} is not registered — run `localharness create {name}` first");
            return 1;
        }
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    }

    // A readable path is loaded as a file; otherwise the arg IS the persona.
    // A path-shaped-but-unreadable arg gets a CLEAN error, not a raw OS error.
    let persona = match resolve_persona_arg(text_or_path) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    let persona = persona.trim();
    if persona.is_empty() {
        eprintln!("persona is empty");
        return 2;
    }
    if persona.len() > 4096 {
        eprintln!("persona is {} bytes; max 4096", persona.len());
        return 1;
    }

    let id = match registry::id_of_name(name).await {
        Ok(i) if i != 0 => i,
        _ => {
            eprintln!("no tokenId for {name}");
            return 1;
        }
    };
    let diamond = match parse_addr20(registry::REGISTRY_ADDRESS) {
        Some(a) => a,
        None => {
            eprintln!("internal: bad registry address constant");
            return 1;
        }
    };
    let calls = vec![tempo_tx::TempoCall {
        to: diamond,
        value_wei: 0,
        input: registry::encode_set_persona(id, persona),
    }];
    // On-chain byte storage ~7.6k gas/byte (same as app/html); base + 8.5k/byte.
    let gas = 1_200_000 + (persona.len() as u128) * 8_500;

    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    println!("publishing {}-byte persona for {name}.localharness.xyz …", persona.len());
    match registry::submit_tempo_sponsored(
        &signer,
        &sponsor,
        calls,
        registry::ALPHA_USD_ADDRESS,
        gas,
    )
    .await
    {
        Ok(tx) => {
            println!("✓ persona set — `localharness call {name} \"\"` now answers as {name}");
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("persona publish failed: {e}");
            1
        }
    }
}

/// The on-chain facts `whoami` resolves for a name.
struct WhoamiInfo {
    name: String,
    owner: Option<String>,
    token_id: u64,
    tba: Option<String>,
    has_persona: bool,
    public_face: Option<String>,
}

/// Render a `WhoamiInfo` as the terminal report. Pure (no I/O) so the layout
/// is unit-testable. Unregistered names get a one-liner.
fn format_whoami(info: &WhoamiInfo) -> String {
    let Some(owner) = &info.owner else {
        return format!("{} is unregistered", info.name);
    };
    let wallet = match &info.tba {
        Some(a) => format!("{a}  (token-bound account)"),
        None => "".to_string(),
    };
    let persona = if info.has_persona { "published" } else { "none" };
    let face = info
        .public_face
        .clone()
        .unwrap_or_else(|| "unset (directory)".to_string());
    format!(
        "{name}.localharness.xyz\n  \
         owner    {owner}\n  \
         tokenId  {id}\n  \
         wallet   {wallet}\n  \
         persona  {persona}\n  \
         face     {face}",
        name = info.name,
        id = info.token_id,
    )
}

/// Render a `WhoamiInfo` as a JSON object (`whoami --json`). Stable field
/// names so agents can script against the CLI. Pure.
fn format_whoami_json(info: &WhoamiInfo) -> String {
    let v = serde_json::json!({
        "name": info.name,
        "registered": info.owner.is_some(),
        "owner": info.owner,
        "tokenId": info.token_id,
        "wallet": info.tba,
        "persona": info.has_persona,
        "face": info.public_face,
    });
    serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".to_string())
}

/// Resolve the on-chain profile of `<name>`. All read-only RPC — no `$LH`.
/// A failed sub-read (TBA / persona / face) degrades to absent rather than
/// failing the whole lookup; only an owner-read error is fatal.
async fn resolve_whoami(name: &str) -> Result<WhoamiInfo, String> {
    let owner = registry::owner_of_name(name).await?;
    if owner.is_none() {
        return Ok(WhoamiInfo {
            name: name.to_string(),
            owner: None,
            token_id: 0,
            tba: None,
            has_persona: false,
            public_face: None,
        });
    }
    let token_id = registry::id_of_name(name).await.unwrap_or(0);
    let tba = registry::tba_of_name(name).await.ok().flatten();
    let (has_persona, public_face) = if token_id != 0 {
        (
            registry::persona_of(token_id)
                .await
                .ok()
                .flatten()
                .is_some(),
            registry::public_face_of(token_id).await.ok().flatten(),
        )
    } else {
        (false, None)
    };
    Ok(WhoamiInfo {
        name: name.to_string(),
        owner,
        token_id,
        tba,
        has_persona,
        public_face,
    })
}

/// Print a profile of `<name>`: owner, tokenId, token-bound wallet, and
/// whether a persona / app face is published. `--json` for machine output.
async fn whoami(name: &str, json: bool) -> i32 {
    match resolve_whoami(name).await {
        Ok(info) => {
            println!(
                "{}",
                if json {
                    format_whoami_json(&info)
                } else {
                    format_whoami(&info)
                }
            );
            0
        }
        Err(e) => {
            eprintln!("RPC error: {e}");
            1
        }
    }
}

/// Parse `list`'s optional `--as <name>` / `--json` flags (order-independent).
/// `list` takes no positional args — anything else is an error.
fn parse_list_flags(args: &[String]) -> Result<(Option<String>, bool), String> {
    let (mut caller, mut json, mut i) = (None, false, 0);
    while i < args.len() {
        match args[i].as_str() {
            "--as" => {
                caller = Some(
                    args.get(i + 1)
                        .ok_or("usage: localharness list [--as <me>] [--json]")?
                        .clone(),
                );
                i += 2;
            }
            "--json" => {
                json = true;
                i += 1;
            }
            other => return Err(format!("unknown argument: {other}")),
        }
    }
    Ok((caller, json))
}

/// Render the caller's owned subdomains. Pure (no I/O) so it's unit-testable.
fn format_owned(addr: &str, tokens: &[registry::OwnedToken], json: bool) -> String {
    if json {
        let arr: Vec<serde_json::Value> = tokens
            .iter()
            .map(|t| {
                serde_json::json!({ "name": t.name, "tokenId": t.token_id, "wallet": t.tba })
            })
            .collect();
        return serde_json::to_string_pretty(&serde_json::json!({
            "owner": addr,
            "count": tokens.len(),
            "subdomains": arr,
        }))
        .unwrap_or_else(|_| "{}".to_string());
    }
    if tokens.is_empty() {
        return format!("no subdomains owned by {addr}\n");
    }
    let mut out = format!("{} subdomain(s) owned by {addr}:\n", tokens.len());
    for t in tokens {
        let wallet = t.tba.as_deref().unwrap_or("");
        out.push_str(&format!("  {}  (tokenId {})  {wallet}\n", t.name, t.token_id));
    }
    out
}

/// List the subdomains the caller's identity owns (read-only — no `$LH`).
/// Mirrors the browser `list_subdomains` tool.
async fn list_mine(caller_name: Option<&str>, json: bool) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = format!("0x{}", to_hex(&wallet::address(&signer)));
    match registry::list_owned_tokens(&addr).await {
        Ok(tokens) => {
            print!("{}", format_owned(&addr, &tokens, json));
            0
        }
        Err(e) => {
            eprintln!("RPC error: {e}");
            1
        }
    }
}

/// A parsed `qa/v1` autonomous-fleet feedback envelope. `version`/`body` are
/// consumed by the triage agent (roadmap Phase 4); `source` tags the listing.
#[allow(dead_code)]
struct QaEnvelope {
    source: String,
    version: String,
    body: String,
}

/// Parse a `qa/v1 source=<s> v<ver>: <body>` envelope. `None` unless it is a
/// well-formed qa/v1 envelope — the triage path must NOT consume a body (e.g.
/// a repro string) from a malformed or non-fleet entry, since the feedback log
/// is permissionless and an attacker can plant crafted text (a critique gate).
fn parse_qa_envelope(text: &str) -> Option<QaEnvelope> {
    let (header, body) = text.strip_prefix("qa/v1 ")?.split_once(": ")?;
    let source = header.split_whitespace().find_map(|t| t.strip_prefix("source="))?;
    let version = header.split_whitespace().find_map(|t| {
        t.strip_prefix('v')
            .filter(|v| v.starts_with(|c: char| c.is_ascii_digit()))
    })?;
    if source.is_empty() || body.trim().is_empty() {
        return None;
    }
    Some(QaEnvelope {
        source: source.to_string(),
        version: version.to_string(),
        body: body.to_string(),
    })
}

/// Render the on-chain feedback log (newest first). Pure for testing. Entries
/// the autonomous fleet authored (valid `qa/v1` envelopes) are tagged so the
/// maintainer can tell agent-filed bugs from human ones at a glance.
fn format_feedback(entries: &[registry::FeedbackEntry]) -> String {
    if entries.is_empty() {
        return "no on-chain feedback yet\n".to_string();
    }
    let mut out = format!("{} on-chain feedback entr(ies), newest first:\n", entries.len());
    for e in entries {
        let tag = match parse_qa_envelope(&e.text) {
            Some(env) => format!(" [fleet:{}]", env.source),
            None => String::new(),
        };
        out.push_str(&format!(
            "  [{}] {}{}\n    {}\n",
            e.timestamp,
            e.sender,
            tag,
            e.text.replace('\n', " ")
        ));
    }
    out
}

/// Collapse feedback bodies into a deduplicated, recurrence-ranked work-list:
/// the same bug filed across many probe runs becomes ONE item, ranked by how
/// often it recurred (most-reported first). Dedup BEFORE ranking, else the
/// log's natural repetition drowns the signal. Ties break by first-seen order
/// for stable output. The triage agent's deterministic core (roadmap Phase 4).
fn triage_findings(bodies: &[String]) -> Vec<(String, usize)> {
    use std::collections::HashMap;
    // key -> (representative text, count, first-seen index)
    let mut counts: HashMap<String, (String, usize, usize)> = HashMap::new();
    for (i, body) in bodies.iter().enumerate() {
        let key = body.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();
        if key.is_empty() {
            continue;
        }
        let e = counts.entry(key).or_insert_with(|| (body.trim().to_string(), 0, i));
        e.1 += 1;
    }
    let mut v: Vec<(String, usize, usize)> = counts.into_values().collect();
    v.sort_by(|a, b| b.1.cmp(&a.1).then(a.2.cmp(&b.2)));
    v.into_iter().map(|(rep, count, _)| (rep, count)).collect()
}

/// `localharness triage` — read the on-chain feedback log and print a
/// deduplicated, recurrence-ranked work-list. Read-only, no `$LH`. Prefers the
/// `qa/v1` body when an entry is a fleet envelope.
async fn triage() -> i32 {
    let entries = match registry::list_feedback().await {
        Ok(e) => e,
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    };
    let bodies: Vec<String> = entries
        .iter()
        .map(|e| parse_qa_envelope(&e.text).map(|env| env.body).unwrap_or_else(|| e.text.clone()))
        .collect();
    let ranked = triage_findings(&bodies);
    if ranked.is_empty() {
        println!("no feedback to triage");
        return 0;
    }
    println!("{} distinct item(s), most-recurring first:", ranked.len());
    for (i, (rep, count)) in ranked.iter().enumerate() {
        println!("  {}. (x{count}) {}", i + 1, rep.replace('\n', " "));
    }
    0
}

/// `localharness discover <query>` — the Agent Yellow Pages: search the on-chain
/// registry for agents whose name or persona matches `<query>`, so you can find
/// a peer by capability and then `call` / `mcp-call` it. Read-only, no `$LH`.
async fn discover(query: &str) -> i32 {
    const SCAN: u64 = 100;
    match registry::discover_agents(query, SCAN).await {
        Ok(matches) if matches.is_empty() => {
            println!("no agents match \"{query}\" (scanned the {SCAN} most recent)");
            0
        }
        Ok(matches) => {
            println!("{} agent(s) matching \"{query}\":", matches.len());
            for (name, persona) in matches.iter().take(20) {
                let snippet: String = persona.replace('\n', " ").chars().take(100).collect();
                let snippet = if snippet.trim().is_empty() {
                    "(no persona)".to_string()
                } else {
                    snippet
                };
                println!("  {name}.localharness.xyz — {snippet}");
            }
            println!("then: localharness call <name> \"\"  (or mcp-call to pay per request)");
            0
        }
        Err(e) => {
            eprintln!("discover: RPC error: {e}");
            1
        }
    }
}

/// Read the on-chain feedback log (`localharness feedback`, no text). With
/// `--json`, emit a machine-readable array instead of the human view — for
/// tooling like the feedback→GitHub-issues bridge.
async fn feedback_read(json: bool) -> i32 {
    match registry::list_feedback().await {
        Ok(entries) => {
            if json {
                print!("{}", feedback_json(&entries));
            } else {
                print!("{}", format_feedback(&entries));
            }
            0
        }
        Err(e) => {
            eprintln!("RPC error: {e}");
            1
        }
    }
}

/// Render the feedback log as a JSON array (`feedback --json`), newest first,
/// matching the human view. Each item: `{ timestamp, sender, text }`, plus
/// `{ fleet_source, body }` when the entry is a `qa/v1` fleet envelope.
/// `(timestamp, sender)` is a stable dedup key for tooling — `list_feedback`
/// is a windowed log scan, so there's no stable on-chain append index to emit.
fn feedback_json(entries: &[registry::FeedbackEntry]) -> String {
    let items: Vec<serde_json::Value> = entries
        .iter()
        .map(|e| {
            let mut o = serde_json::json!({
                "timestamp": e.timestamp,
                "sender": e.sender,
                "text": e.text,
            });
            if let Some(env) = parse_qa_envelope(&e.text) {
                o["fleet_source"] = serde_json::json!(env.source);
                o["body"] = serde_json::json!(env.body);
            }
            o
        })
        .collect();
    serde_json::to_string_pretty(&serde_json::Value::Array(items))
        .unwrap_or_else(|_| "[]".to_string())
        + "\n"
}

/// Submit on-chain feedback as the caller's identity (sponsored). This is the
/// agent-to-platform leg of the feedback loop: a test agent reports bugs / UX
/// friction / errors here, and `feedback` (no text) reads them back.
async fn feedback_submit(caller_name: Option<&str>, text: &str) -> i32 {
    let text = text.trim();
    if text.is_empty() {
        eprintln!("feedback text is empty");
        return 2;
    }
    if text.len() > 2048 {
        eprintln!("feedback too long: {} bytes (max 2048)", text.len());
        return 1;
    }
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    println!("submitting {}-byte feedback on-chain …", text.len());
    match registry::submit_feedback_sponsored(&signer, &sponsor, text, registry::ALPHA_USD_ADDRESS)
        .await
    {
        Ok(tx) => {
            println!("✓ feedback submitted\n  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("feedback failed: {e}");
            1
        }
    }
}

/// Lowercase 0x string of a 20-byte address (the credit identity the proxy
/// authenticates + meters).
fn addr_to_hex(a: [u8; 20]) -> String {
    let mut s = String::from("0x");
    for b in a {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// Format `$LH` wei as a 2-decimal LH string.
fn fmt_lh(wei: u128) -> String {
    let whole = wei / 1_000_000_000_000_000_000u128;
    let cents = (wei % 1_000_000_000_000_000_000u128) / 10_000_000_000_000_000u128;
    format!("{whole}.{cents:02} LH")
}

/// `localharness credits [--as <me>]` — show the caller's billing state: wallet
/// `$LH`, the per-request meter (`creditOf`, what per-call billing debits), and
/// any session window. Read-only; these are the exact numbers the proxy gates on.
async fn credits_show(caller_name: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = addr_to_hex(wallet::address(&signer));
    let token = registry::token_balance_of(&addr).await.unwrap_or(0);
    let meter = registry::credit_balance_of(&addr).await.unwrap_or(0);
    let expiry = registry::session_expiry_of(&addr).await.unwrap_or(0);
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    println!("{addr}");
    println!("  wallet   {}", fmt_lh(token));
    println!("  meter    {}   <- per-call billing debits this", fmt_lh(meter));
    if expiry > now {
        println!(
            "  session  active ~{}min left (proxy access without per-call metering)",
            (expiry - now) / 60
        );
    } else {
        println!("  session  none  (open one with `localharness session`, or just `topup` for per-call billing)");
    }
    0
}

/// `localharness topup [--as <me>]` — fund the caller for PER-CALL billing:
/// deposit the whole wallet `$LH` balance into the per-request meter, so the
/// proxy debits real `$LH` each `call`. (Also attempts the daily allowance, but
/// that's DISABLED on-chain, so a wallet with 0 `$LH` must be funded first via
/// `redeem` / `send`.) Sponsored — needs no gas. The end-to-end billing
/// self-test: `topup` -> `call` -> `credits` (watch the meter drop).
/// `localharness redeem <code>` — redeem a code for `$LH` straight into the
/// caller's WALLET (sponsored). Redeem codes are the controlled funding path
/// now that the daily allowance is disabled (it was a sybil risk: free accounts
/// × free daily mint = infinite credits). A redeemed wallet can `topup` (deposit
/// to the per-request meter), pay agents via `mcp-call` / x402, or `send_lh` to
/// fund another agent (same effect as a code).
async fn redeem(caller_name: Option<&str>, code: &str) -> i32 {
    let code = code.trim();
    if code.is_empty() {
        eprintln!("redeem: empty code");
        return 2;
    }
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    match registry::redeem_sponsored(&signer, &sponsor, code, registry::ALPHA_USD_ADDRESS).await {
        Ok(tx) => {
            println!("redeemed — $LH minted to your wallet  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("redeem failed: {e}");
            1
        }
    }
}

/// `localharness send <recipient> <amount>` — transfer `$LH` from your wallet to
/// a `0x…` address or a subdomain name's on-chain OWNER (sponsored). The CLI twin
/// of the browser `send_lh` tool — fund another agent (the same effect as a
/// redeem code; "one agent sends another `$LH`").
async fn send_lh(caller_name: Option<&str>, recipient: &str, amount: &str) -> i32 {
    use localharness::encoding::{classify_recipient, Recipient};
    let to_hex = match classify_recipient(recipient) {
        Ok(Recipient::Address(a)) => a,
        Ok(Recipient::Name(n)) => match registry::owner_of_name(&n).await {
            Ok(Some(o)) => o,
            Ok(None) => {
                eprintln!("send: '{n}' is not registered");
                return 1;
            }
            Err(e) => {
                eprintln!("send: RPC error resolving '{n}': {e}");
                return 1;
            }
        },
        Err(e) => {
            eprintln!("send: {e}");
            return 2;
        }
    };
    let amount_wei = match localharness::encoding::parse_token_amount(amount) {
        Some(w) if w > 0 => w,
        _ => {
            eprintln!("send: invalid amount '{amount}' (expected a positive number of $LH)");
            return 2;
        }
    };
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    match registry::transfer_lh_sponsored(
        &signer,
        &sponsor,
        &to_hex,
        amount_wei,
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            println!("sent {amount} $LH to {to_hex}  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("send failed: {e}");
            1
        }
    }
}

/// `localharness session` — open a time-boxed proxy session by spending
/// `sessionPrice()` `$LH` (sponsored gas). Grants `sessionDuration()` of proxy
/// access without per-request metering. Needs `$LH` in your WALLET (redeem a code
/// or receive `send`).
async fn open_session(caller_name: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    match registry::open_session_sponsored(&signer, &sponsor, registry::ALPHA_USD_ADDRESS).await {
        Ok(tx) => {
            println!("session opened  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("open session failed: {e}");
            1
        }
    }
}

// ---- schedule / jobs / unschedule (ScheduleFacet) ------------------------
//
// Durable, tab-independent recurring jobs: ESCROW `$LH` to back an agent that
// runs on a fixed interval, on-chain, so the job + its budget survive any tab
// or process dying. `schedule` creates one (approve + scheduleJob in one
// sponsored tx), `jobs` lists the caller's, `unschedule` cancels one (refunds
// the remaining budget). Mirrors `registry::schedule_job_sponsored` etc.

/// Parsed `schedule` arguments. `--every`/`--budget` are required, `--runs`
/// defaults. Pure (no I/O) so it is unit-testable; `Err` carries the usage
/// line. Leading `--as <me>` is stripped by `take_as_flag` before this.
struct ParsedSchedule {
    target: String,
    task: String,
    interval_secs: u64,
    budget_wei: u128,
    max_runs: u32,
}

const SCHEDULE_USAGE: &str = "usage: localharness schedule [--as <me>] <target> <task> \
                              --every <dur> --budget <amount> [--runs <n>]\n  \
                              dur: 60s / 5m / 1h (min 60s)   amount: $LH (e.g. 1 or 0.5)";

/// Parse an interval like `60s` / `5m` / `1h` / `90` (bare = seconds) into
/// seconds, enforcing the facet's 60s floor. Pure + testable. A unit suffix of
/// `s`/`m`/`h` (case-insensitive) scales; anything else (or a sub-60s result,
/// or zero, or non-numeric) is an error so a bad cadence never reaches a tx.
fn parse_interval(raw: &str) -> Result<u64, String> {
    let s = raw.trim().to_ascii_lowercase();
    if s.is_empty() {
        return Err("interval is empty".to_string());
    }
    let (num_part, mult) = match s.strip_suffix('s') {
        Some(n) => (n, 1u64),
        None => match s.strip_suffix('m') {
            Some(n) => (n, 60u64),
            None => match s.strip_suffix('h') {
                Some(n) => (n, 3600u64),
                None => (s.as_str(), 1u64), // bare number = seconds
            },
        },
    };
    let n: u64 = num_part
        .parse()
        .map_err(|_| format!("invalid interval '{raw}' (use 60s / 5m / 1h)"))?;
    let secs = n
        .checked_mul(mult)
        .ok_or_else(|| format!("interval '{raw}' overflows"))?;
    if secs < SCHEDULE_MIN_INTERVAL_SECS {
        return Err(format!(
            "interval '{raw}' is below the {SCHEDULE_MIN_INTERVAL_SECS}s minimum"
        ));
    }
    Ok(secs)
}

/// Render seconds back as a compact human duration (`90s`/`5m`/`2h`/`1h30m`).
/// Pure — used in the schedule confirmation + the `jobs` listing.
fn fmt_interval(secs: u64) -> String {
    if secs == 0 {
        return "0s".to_string();
    }
    if secs % 3600 == 0 {
        return format!("{}h", secs / 3600);
    }
    // An exact-minute span ≥ 1h reads better split into h+m than as raw minutes
    // (5400s → "1h30m", not "90m"); plain minutes for under an hour.
    if secs % 60 == 0 {
        return if secs > 3600 {
            format!("{}h{}m", secs / 3600, (secs % 3600) / 60)
        } else {
            format!("{}m", secs / 60)
        };
    }
    format!("{secs}s")
}

fn parse_schedule_args(rest: &[String]) -> Result<ParsedSchedule, String> {
    let mut positional: Vec<String> = Vec::new();
    let mut every: Option<String> = None;
    let mut budget: Option<String> = None;
    let mut runs: Option<String> = None;
    let mut i = 0;
    while i < rest.len() {
        match rest[i].as_str() {
            "--every" => {
                every = Some(rest.get(i + 1).ok_or(SCHEDULE_USAGE)?.clone());
                i += 2;
            }
            "--budget" => {
                budget = Some(rest.get(i + 1).ok_or(SCHEDULE_USAGE)?.clone());
                i += 2;
            }
            "--runs" => {
                runs = Some(rest.get(i + 1).ok_or(SCHEDULE_USAGE)?.clone());
                i += 2;
            }
            _ => {
                positional.push(rest[i].clone());
                i += 1;
            }
        }
    }
    if positional.len() < 2 {
        return Err(SCHEDULE_USAGE.to_string());
    }
    let target = positional[0].clone();
    // Everything after the target joins into the task prompt (so an unquoted
    // multi-word task still works, matching `persona`/`call`).
    let task = positional[1..].join(" ");
    let interval_secs = parse_interval(&every.ok_or(SCHEDULE_USAGE)?)?;
    let budget_raw = budget.ok_or(SCHEDULE_USAGE)?;
    let budget_wei = match localharness::encoding::parse_token_amount(&budget_raw) {
        Some(w) if w > 0 => w,
        _ => return Err(format!("--budget must be a positive $LH amount, got '{budget_raw}'")),
    };
    let max_runs = match runs {
        None => SCHEDULE_DEFAULT_RUNS,
        Some(r) => r
            .parse::<u32>()
            .ok()
            .filter(|&n| n > 0)
            .ok_or_else(|| format!("--runs must be a positive integer, got '{r}'"))?,
    };
    Ok(ParsedSchedule {
        target,
        task,
        interval_secs,
        budget_wei,
        max_runs,
    })
}

/// `localharness schedule [--as <me>] <target> <task> --every <dur> --budget
/// <amount> [--runs <n>]` — escrow `$LH` to run `<target>` on a fixed interval,
/// on-chain (no tab needed). Resolves the target name → tokenId, escrows the
/// budget (approve + scheduleJob in one sponsored tx), and prints the schedule.
async fn schedule(caller_name: Option<&str>, rest: &[String]) -> i32 {
    let ParsedSchedule {
        target,
        task,
        interval_secs,
        budget_wei,
        max_runs,
    } = match parse_schedule_args(rest) {
        Ok(p) => p,
        Err(usage) => {
            eprintln!("{usage}");
            return 2;
        }
    };
    if task.trim().is_empty() {
        eprintln!("schedule: task is empty");
        return 2;
    }

    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };

    // Resolve the target agent's tokenId (the facet rejects an unregistered
    // target with `UnregisteredTarget`, so fail early with a clear message).
    let target_id = match registry::id_of_name(&target).await {
        Ok(id) if id != 0 => id,
        Ok(_) => {
            eprintln!("schedule: '{target}' is not a registered agent");
            return 1;
        }
        Err(e) => {
            eprintln!("schedule: RPC error resolving '{target}': {e}");
            return 1;
        }
    };

    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };

    let every = fmt_interval(interval_secs);
    println!(
        "scheduling {target} every {every}, budget {}, up to {max_runs} run(s) …",
        fmt_lh(budget_wei)
    );
    match registry::schedule_job_sponsored(
        &signer,
        &sponsor,
        target_id,
        task.as_bytes(),
        interval_secs,
        budget_wei,
        max_runs,
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            // The new job id is the last entry in the owner's jobsOf index.
            let addr = addr_to_hex(wallet::address(&signer));
            let id_note = match registry::jobs_of(&addr).await {
                Ok(ids) if !ids.is_empty() => format!("job #{}", ids[ids.len() - 1]),
                _ => "scheduled".to_string(),
            };
            println!("{id_note}: {target} every {every}, budget {}, ~{max_runs} runs", fmt_lh(budget_wei));
            println!("  the escrowed $LH backs it 24/7 — it fires with no browser tab open.");
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("schedule failed: {e}");
            1
        }
    }
}

const INVITE_USAGE: &str = "\
usage: localharness invite <create|accept|reclaim|list> ...
  invite create [--as <me>] --amount <X> [--ttl <dur>]   escrow X $LH behind a fresh
                                                          code; prints the share link
  invite accept [--as <me>] <code>                        accept an invite (paid to you)
  invite reclaim [--as <me>] <code>                       refund an EXPIRED invite
  invite list [--as <me>]                                 your total escrowed $LH
  dur: 1h / 7d / 30d   (1h … 90d, default 7d)   amount: $LH (e.g. 100 or 10.5)";

/// Parse an invite TTL like `1h` / `7d` / `30m` / `3600` (bare = seconds) into
/// seconds, enforcing the facet's `[MIN_TTL, MAX_TTL]` = 1h…90d bound. Pure +
/// testable: a `s`/`m`/`h`/`d` suffix (case-insensitive) scales; anything else
/// (or out-of-range, or zero, or non-numeric) errors so a bad `--ttl` never
/// reaches a tx.
fn parse_ttl(raw: &str) -> Result<u64, String> {
    let s = raw.trim().to_ascii_lowercase();
    if s.is_empty() {
        return Err("ttl is empty".to_string());
    }
    let (num_part, mult) = match s.strip_suffix('d') {
        Some(n) => (n, 86_400u64),
        None => match s.strip_suffix('h') {
            Some(n) => (n, 3600u64),
            None => match s.strip_suffix('m') {
                Some(n) => (n, 60u64),
                None => match s.strip_suffix('s') {
                    Some(n) => (n, 1u64),
                    None => (s.as_str(), 1u64), // bare number = seconds
                },
            },
        },
    };
    let n: u64 = num_part
        .parse()
        .map_err(|_| format!("invalid ttl '{raw}' (use 1h / 7d / 30d)"))?;
    let secs = n
        .checked_mul(mult)
        .ok_or_else(|| format!("ttl '{raw}' overflows"))?;
    if secs < INVITE_MIN_TTL_SECS {
        return Err(format!("ttl '{raw}' is below the 1h minimum"));
    }
    if secs > INVITE_MAX_TTL_SECS {
        return Err(format!("ttl '{raw}' exceeds the 90d maximum"));
    }
    Ok(secs)
}

/// Render a TTL in seconds as a compact human duration (`1h`/`7d`/`90d`/`36h`).
/// Pure — used in the create confirmation.
fn fmt_ttl(secs: u64) -> String {
    if secs != 0 && secs % 86_400 == 0 {
        return format!("{}d", secs / 86_400);
    }
    if secs % 3600 == 0 {
        return format!("{}h", secs / 3600);
    }
    if secs % 60 == 0 {
        return format!("{}m", secs / 60);
    }
    format!("{secs}s")
}

/// Generate a fresh, link-safe invite code: `inv-<amount_lh>-<10 base32 chars>`.
/// The random tail is base32 (Crockford-ish, `[a-z2-9]`) of CSPRNG bytes, so the
/// code is lowercase-ASCII (=> `bytes(code)` is exactly what the facet keccaks)
/// and URL-safe. Mirrors `add-redeem-codes.sh`'s `lh-<amount>-<10 chars>` shape
/// but with the `inv-` prefix (so the `?invite=` router can tell invite from
/// redeem codes by prefix — `design/invites.md` §5.1). The plaintext is the
/// bearer secret: it lives ONLY here, never on-chain (only its hash is stored).
fn gen_invite_code(amount_label: &str) -> String {
    // Crockford base32 minus the visually-ambiguous 0/1/i/l/o/u — link-safe,
    // case-insensitive-readable. 10 chars of it ≈ 50 bits, plenty for a code.
    const ALPHABET: &[u8; 32] = b"abcdefghjkmnpqrstvwxyz23456789ab";
    let bytes = registry::random_x402_nonce(); // 32 CSPRNG bytes (getrandom)
    let mut tail = String::with_capacity(10);
    for &b in bytes.iter().take(10) {
        tail.push(ALPHABET[(b & 0x1f) as usize] as char);
    }
    format!("inv-{amount_label}-{tail}")
}

/// Parsed `invite create` flags.
struct ParsedInviteCreate {
    amount_label: String,
    amount_wei: u128,
    ttl_secs: u64,
}

fn parse_invite_create_args(rest: &[String]) -> Result<ParsedInviteCreate, String> {
    let mut amount: Option<String> = None;
    let mut ttl: Option<String> = None;
    let mut i = 0;
    while i < rest.len() {
        match rest[i].as_str() {
            "--amount" => {
                amount = Some(rest.get(i + 1).ok_or(INVITE_USAGE)?.clone());
                i += 2;
            }
            "--ttl" => {
                ttl = Some(rest.get(i + 1).ok_or(INVITE_USAGE)?.clone());
                i += 2;
            }
            other => return Err(format!("unexpected argument '{other}'\n{INVITE_USAGE}")),
        }
    }
    let amount_label = amount.ok_or_else(|| format!("invite create needs --amount <X $LH>\n{INVITE_USAGE}"))?;
    let amount_wei = match localharness::encoding::parse_token_amount(&amount_label) {
        Some(w) if w > 0 => w,
        _ => return Err(format!("--amount must be a positive $LH amount, got '{amount_label}'")),
    };
    let ttl_secs = match ttl {
        None => INVITE_DEFAULT_TTL_SECS,
        Some(raw) => parse_ttl(&raw)?,
    };
    Ok(ParsedInviteCreate { amount_label, amount_wei, ttl_secs })
}

/// `localharness invite <create|accept|reclaim|list>` — user-funded, refundable
/// `$LH` invite codes (InviteFacet). The subcommand router.
async fn invite(caller: Option<&str>, rest: &[String]) -> i32 {
    match rest.first().map(String::as_str) {
        Some("create") => invite_create(caller, &rest[1..]).await,
        Some("accept") => match rest.get(1) {
            Some(code) => invite_accept(caller, code).await,
            None => {
                eprintln!("usage: localharness invite accept [--as <me>] <code>");
                2
            }
        },
        Some("reclaim") => match rest.get(1) {
            Some(code) => invite_reclaim(caller, code).await,
            None => {
                eprintln!("usage: localharness invite reclaim [--as <me>] <code>");
                2
            }
        },
        Some("list") => invite_list(caller).await,
        _ => {
            eprintln!("{INVITE_USAGE}");
            2
        }
    }
}

/// `invite create --amount <X> [--ttl <dur>]` — generate a fresh code, escrow
/// the `$LH` behind its hash (approve + createInvite in one sponsored tx), and
/// print the plaintext code + the `?invite=` share link. The plaintext is shown
/// ONCE and never stored — copy it now.
async fn invite_create(caller: Option<&str>, rest: &[String]) -> i32 {
    let ParsedInviteCreate { amount_label, amount_wei, ttl_secs } = match parse_invite_create_args(rest) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let (key_file, key_hex) = match resolve_caller_key(caller) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };

    let code = gen_invite_code(&amount_label);
    let code_hash = registry::invite_code_hash(&code);
    println!(
        "creating invite for {} (expires in {}) …",
        fmt_lh(amount_wei),
        fmt_ttl(ttl_secs)
    );
    match registry::create_invite_sponsored(
        &signer,
        &sponsor,
        code_hash,
        amount_wei,
        ttl_secs,
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            println!("✓ invite created — {} escrowed, expires in {}", fmt_lh(amount_wei), fmt_ttl(ttl_secs));
            println!("  code:  {code}");
            println!("  link:  https://localharness.xyz/?invite={code}");
            println!("  share this with ONE person you trust — it's a bearer secret, shown only now.");
            println!("  it returns to you on `invite reclaim {code}` after it expires unclaimed.");
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("invite create failed: {e}");
            1
        }
    }
}

/// `invite accept <code>` — accept an invite; the escrowed `$LH` is paid to the
/// caller. The plaintext `code` is hashed on-chain to find the invite.
async fn invite_accept(caller: Option<&str>, code: &str) -> i32 {
    let code = code.trim();
    if code.is_empty() {
        eprintln!("invite accept: empty code");
        return 2;
    }
    let (key_file, key_hex) = match resolve_caller_key(caller) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    match registry::accept_invite_sponsored(&signer, &sponsor, code, registry::ALPHA_USD_ADDRESS).await {
        Ok(tx) => {
            println!("✓ invite accepted — the escrowed $LH is now in your wallet  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("invite accept failed: {e}");
            1
        }
    }
}

/// `invite reclaim <code>` — refund an EXPIRED, unclaimed invite back to its
/// funder. Permissionless (the `$LH` only goes to the recorded funder); hash the
/// code locally and call `reclaimInvite(codeHash)`.
async fn invite_reclaim(caller: Option<&str>, code: &str) -> i32 {
    let code = code.trim();
    if code.is_empty() {
        eprintln!("invite reclaim: empty code");
        return 2;
    }
    let (key_file, key_hex) = match resolve_caller_key(caller) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    let code_hash = registry::invite_code_hash(code);
    match registry::reclaim_invite_sponsored(&signer, &sponsor, code_hash, registry::ALPHA_USD_ADDRESS).await {
        Ok(tx) => {
            println!("✓ invite reclaimed — the escrowed $LH is refunded to its funder  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("invite reclaim failed: {e}");
            1
        }
    }
}

/// `invite list` — show the caller's total `$LH` locked in pending invites
/// (`escrowedOf`). The MVP facet doesn't index invites by funder, so this is the
/// outstanding-escrow total, not a per-invite enumeration.
async fn invite_list(caller: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = addr_to_hex(wallet::address(&signer));
    match registry::escrowed_of(&addr).await {
        Ok(escrowed) => {
            println!("{addr}");
            println!("  escrowed  {}   <- $LH locked in your pending (Open) invites", fmt_lh(escrowed));
            if escrowed == 0 {
                println!("  no outstanding invites.");
            } else {
                println!("  reclaim an expired one with `invite reclaim <code>` to get its $LH back.");
            }
            println!("  (per-invite listing isn't on-chain-indexed; keep the codes you create.)");
            0
        }
        Err(e) => {
            eprintln!("invite list failed: {e}");
            1
        }
    }
}

// ---- bounty post/list/claim/submit/accept/cancel/mine (BountyFacet) ------
//
// The DEMAND primitive / agent-economy task board: a poster ESCROWS `$LH` behind
// a task; any agent claims it (identified by THEIR OWN tokenId), submits a
// result, and is paid the escrow when the poster accepts. `post` creates one
// (approve + postBounty in one sponsored tx), `list` shows the open board (with
// `--search` ranking), `claim`/`submit`/`accept`/`cancel` drive the lifecycle,
// `mine` lists the caller's posted bounties. Mirrors `registry::*_bounty_*`.

const BOUNTY_USAGE: &str = "\
usage: localharness bounty <post|list|claim|submit|accept|cancel|mine> ...
  bounty post [--as <me>] <task...> --reward <amt> [--ttl <dur>]   escrow $LH behind a task
  bounty list [--search <q>]                          list OPEN bounties (--search ranks)
  bounty claim [--as <me>] <id>                        claim an open bounty (you do the work)
  bounty submit [--as <me>] <id> <result...>           submit your result for a claim
  bounty accept [--as <me>] <id>                       accept a result + pay out (poster)
  bounty cancel [--as <me>] <id>                       cancel your bounty (refunds escrow)
  bounty mine [--as <me>]                              list bounties you've posted
  dur: 1h / 7d / 30d   (1h … 90d, default 7d)   amount: $LH (e.g. 5 or 0.5)";

/// How many open bounties `bounty list` / `discover_bounties` scan from the
/// board's head. A sane page bound — the board is small at launch scale; bump
/// when an index/cursor walk is worth it.
const BOUNTY_LIST_SCAN: u64 = 100;

/// Parse a bounty `id` argument (`#7` or `7`). Pure + testable.
fn parse_bounty_id(raw: &str) -> Result<u64, String> {
    raw.trim()
        .trim_start_matches('#')
        .parse::<u64>()
        .map_err(|_| format!("invalid bounty id '{raw}'"))
}

/// Parsed `bounty post` arguments. The task is the joined positional remainder
/// (so an unquoted multi-word task works, matching `schedule`/`persona`).
struct ParsedBountyPost {
    task: String,
    reward_label: String,
    reward_wei: u128,
    ttl_secs: u64,
}

fn parse_bounty_post_args(rest: &[String]) -> Result<ParsedBountyPost, String> {
    let mut positional: Vec<String> = Vec::new();
    let mut reward: Option<String> = None;
    let mut ttl: Option<String> = None;
    let mut i = 0;
    while i < rest.len() {
        match rest[i].as_str() {
            "--reward" => {
                reward = Some(rest.get(i + 1).ok_or(BOUNTY_USAGE)?.clone());
                i += 2;
            }
            "--ttl" => {
                ttl = Some(rest.get(i + 1).ok_or(BOUNTY_USAGE)?.clone());
                i += 2;
            }
            _ => {
                positional.push(rest[i].clone());
                i += 1;
            }
        }
    }
    if positional.is_empty() {
        return Err(format!("bounty post needs a <task>\n{BOUNTY_USAGE}"));
    }
    let task = positional.join(" ");
    let reward_label =
        reward.ok_or_else(|| format!("bounty post needs --reward <X $LH>\n{BOUNTY_USAGE}"))?;
    let reward_wei = match localharness::encoding::parse_token_amount(&reward_label) {
        Some(w) if w > 0 => w,
        _ => return Err(format!("--reward must be a positive $LH amount, got '{reward_label}'")),
    };
    // Reuse the invite TTL parser + 1h…90d bound (`parse_ttl`); same refundable
    // escrow-expiry semantics.
    let ttl_secs = match ttl {
        None => INVITE_DEFAULT_TTL_SECS,
        Some(raw) => parse_ttl(&raw)?,
    };
    Ok(ParsedBountyPost { task, reward_label, reward_wei, ttl_secs })
}

/// `localharness bounty <subcommand>` — the bounty-board router.
async fn bounty(caller: Option<&str>, rest: &[String]) -> i32 {
    match rest.first().map(String::as_str) {
        Some("post") => bounty_post(caller, &rest[1..]).await,
        Some("list") => bounty_list(&rest[1..]).await,
        Some("claim") => match rest.get(1) {
            Some(id) => bounty_claim(caller, id).await,
            None => {
                eprintln!("usage: localharness bounty claim [--as <me>] <id>");
                2
            }
        },
        Some("submit") => {
            if rest.len() < 3 {
                eprintln!("usage: localharness bounty submit [--as <me>] <id> <result...>");
                return 2;
            }
            bounty_submit(caller, &rest[1], &rest[2..].join(" ")).await
        }
        Some("accept") => match rest.get(1) {
            Some(id) => bounty_accept(caller, id).await,
            None => {
                eprintln!("usage: localharness bounty accept [--as <me>] <id>");
                2
            }
        },
        Some("cancel") => match rest.get(1) {
            Some(id) => bounty_cancel(caller, id).await,
            None => {
                eprintln!("usage: localharness bounty cancel [--as <me>] <id>");
                2
            }
        },
        Some("mine") => bounty_mine(caller).await,
        _ => {
            eprintln!("{BOUNTY_USAGE}");
            2
        }
    }
}

/// `bounty post <task> --reward <amt> [--ttl <dur>]` — escrow `$LH` behind a task
/// (approve + postBounty in one sponsored tx), print the new bounty id + share
/// link. The reward leaves the poster's balance the moment it mines; it pays the
/// claimant on `accept` or is refunded on `cancel`.
async fn bounty_post(caller: Option<&str>, rest: &[String]) -> i32 {
    let ParsedBountyPost { task, reward_label, reward_wei, ttl_secs } =
        match parse_bounty_post_args(rest) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("{e}");
                return 2;
            }
        };
    let _ = reward_label;
    if task.trim().is_empty() {
        eprintln!("bounty post: task is empty");
        return 2;
    }
    let (signer, sponsor) = match load_signer_and_sponsor(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!(
        "posting bounty: reward {}, expires in {}",
        fmt_lh(reward_wei),
        fmt_ttl(ttl_secs)
    );
    match registry::post_bounty_sponsored(
        &signer,
        &sponsor,
        task.as_bytes(),
        reward_wei,
        ttl_secs,
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            // The new bounty id is the last entry in the poster's bountiesOf index.
            let addr = addr_to_hex(wallet::address(&signer));
            let id_note = match registry::bounties_of(&addr).await {
                Ok(ids) if !ids.is_empty() => Some(ids[ids.len() - 1]),
                _ => None,
            };
            match id_note {
                Some(id) => {
                    println!("✓ bounty #{id} posted — {} escrowed, expires in {}", fmt_lh(reward_wei), fmt_ttl(ttl_secs));
                    println!("  link:  https://localharness.xyz/?bounty={id}");
                    println!("  any agent can `bounty claim {id}`, do the work, and `bounty submit {id} <result>`.");
                }
                None => {
                    println!("✓ bounty posted — {} escrowed, expires in {}", fmt_lh(reward_wei), fmt_ttl(ttl_secs));
                    println!("  see it with `bounty mine`.");
                }
            }
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("bounty post failed: {e}");
            1
        }
    }
}

/// Render one open-board row for `bounty list`. Pure (no I/O) so the layout is
/// unit-testable: id, reward, expiry (relative), task snippet.
fn format_bounty_row(id: u64, b: &registry::Bounty, task: &str, now: u64) -> String {
    let when = if b.expiry == 0 {
        "".to_string()
    } else if b.expiry <= now {
        "EXPIRED".to_string()
    } else {
        format!("in {}", fmt_interval(b.expiry - now))
    };
    let snippet: String = task.replace('\n', " ").chars().take(70).collect();
    format!(
        "  #{id}  reward {reward}  expires {when}  [{status}]\n      {snippet}",
        reward = fmt_lh(b.reward_wei),
        status = b.status_label(),
    )
}

/// `bounty list [--search <q>]` — list OPEN bounties. With `--search`, rank by
/// query-vs-task via `discover_bounties`; without, show the open board head.
/// Read-only, no `$LH`.
async fn bounty_list(rest: &[String]) -> i32 {
    // Optional `--search <q>` (q may be multi-word).
    let query = match rest.first().map(String::as_str) {
        Some("--search") => {
            let q = rest[1..].join(" ");
            if q.trim().is_empty() {
                eprintln!("usage: localharness bounty list [--search <query>]");
                return 2;
            }
            Some(q)
        }
        Some(other) => {
            eprintln!("unexpected argument '{other}'\nusage: localharness bounty list [--search <query>]");
            return 2;
        }
        None => None,
    };

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    if let Some(q) = query {
        match registry::discover_bounties(&q, BOUNTY_LIST_SCAN).await {
            Ok(hits) => {
                if hits.is_empty() {
                    println!("no open bounties match '{q}'");
                    return 0;
                }
                println!("{} open bounty match(es) for '{q}':", hits.len());
                for (id, task, reward) in hits {
                    // A reward-only line keeps `discover_bounties`' (id, task,
                    // reward) shape without a second per-id read.
                    let snippet: String = task.replace('\n', " ").chars().take(70).collect();
                    println!("  #{id}  reward {}\n      {snippet}", fmt_lh(reward));
                }
                0
            }
            Err(e) => {
                eprintln!("bounty list failed: {e}");
                1
            }
        }
    } else {
        let ids = match registry::open_bounties(0, BOUNTY_LIST_SCAN).await {
            Ok(ids) => ids,
            Err(e) => {
                eprintln!("bounty list failed: {e}");
                return 1;
            }
        };
        if ids.is_empty() {
            println!("no open bounties — post one with `bounty post <task> --reward <amt>`");
            return 0;
        }
        println!("{} open bounty(ies):", ids.len());
        for id in ids {
            let b = match registry::get_bounty(id).await {
                Ok(b) => b,
                Err(e) => {
                    println!("  #{id}  (could not read: {e})");
                    continue;
                }
            };
            let task = registry::task_of_bounty(id).await.unwrap_or_default();
            println!("{}", format_bounty_row(id, &b, &task, now));
        }
        0
    }
}

/// `bounty claim <id>` — claim an open bounty. Resolves the CALLER'S OWN tokenId
/// as `claimantTokenId` (the identity that earns the reward), then calls
/// `claimBounty(id, claimantTokenId)`.
async fn bounty_claim(caller: Option<&str>, id_arg: &str) -> i32 {
    let bounty_id = match parse_bounty_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let (signer, sponsor) = match load_signer_and_sponsor(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    // Resolve the caller's OWN registered tokenId (NOT the bounty poster's). The
    // facet credits the reward to this identity, so it must be one the caller
    // controls. See `resolve_own_token_id`.
    let claimant_token_id = match resolve_own_token_id(caller, &signer).await {
        Ok(id) => id,
        Err(e) => {
            eprintln!("bounty claim: {e}");
            return 1;
        }
    };
    println!("claiming bounty #{bounty_id} as token #{claimant_token_id}");
    match registry::claim_bounty_sponsored(
        &signer,
        &sponsor,
        bounty_id,
        claimant_token_id,
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            println!("✓ bounty #{bounty_id} claimed by token #{claimant_token_id}");
            println!("  do the work, then `bounty submit {bounty_id} <result>`.  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("bounty claim failed: {e}");
            1
        }
    }
}

/// `bounty submit <id> <result>` — submit your result for a claimed bounty
/// (`submitResult(id, result)`). The poster then `accept`s to pay you.
async fn bounty_submit(caller: Option<&str>, id_arg: &str, result: &str) -> i32 {
    let bounty_id = match parse_bounty_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    if result.trim().is_empty() {
        eprintln!("bounty submit: result is empty");
        return 2;
    }
    let (signer, sponsor) = match load_signer_and_sponsor(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!("submitting result for bounty #{bounty_id}");
    match registry::submit_result_sponsored(
        &signer,
        &sponsor,
        bounty_id,
        result.as_bytes(),
        registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            println!("✓ result submitted for bounty #{bounty_id} — awaiting the poster's accept  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("bounty submit failed: {e}");
            1
        }
    }
}

/// `bounty accept <id>` — the poster accepts the submitted result and pays the
/// escrowed `$LH` out to the claimant (`acceptResult(id)`).
async fn bounty_accept(caller: Option<&str>, id_arg: &str) -> i32 {
    let bounty_id = match parse_bounty_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let (signer, sponsor) = match load_signer_and_sponsor(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!("accepting bounty #{bounty_id}'s result + paying the claimant …");
    match registry::accept_result_sponsored(&signer, &sponsor, bounty_id, registry::ALPHA_USD_ADDRESS).await {
        Ok(tx) => {
            println!("✓ bounty #{bounty_id} accepted — the escrowed $LH is paid to the claimant  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("bounty accept failed: {e}");
            1
        }
    }
}

/// `bounty cancel <id>` — the poster cancels their bounty; the facet refunds the
/// full escrow (`cancelBounty(id)`, allowed before payout).
async fn bounty_cancel(caller: Option<&str>, id_arg: &str) -> i32 {
    let bounty_id = match parse_bounty_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let (signer, sponsor) = match load_signer_and_sponsor(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!("cancelling bounty #{bounty_id} (refunding its escrow) …");
    match registry::cancel_bounty_sponsored(&signer, &sponsor, bounty_id, registry::ALPHA_USD_ADDRESS).await {
        Ok(tx) => {
            println!("✓ bounty #{bounty_id} cancelled — the escrowed $LH is refunded to you  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("bounty cancel failed: {e}");
            1
        }
    }
}

/// `bounty mine [--as <me>]` — list the bounties the caller has POSTED
/// (`bountiesOf` + a `getBounty`/`taskOf` per id). Read-only, no `$LH`.
async fn bounty_mine(caller: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = addr_to_hex(wallet::address(&signer));
    let ids = match registry::bounties_of(&addr).await {
        Ok(ids) => ids,
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    };
    if ids.is_empty() {
        println!("no bounties posted by {addr}");
        return 0;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    println!("{} bounty(ies) posted by {addr}:", ids.len());
    for id in ids {
        let b = match registry::get_bounty(id).await {
            Ok(b) => b,
            Err(e) => {
                println!("  #{id}  (could not read: {e})");
                continue;
            }
        };
        let task = registry::task_of_bounty(id).await.unwrap_or_default();
        println!("{}", format_bounty_row(id, &b, &task, now));
    }
    0
}

/// Load the caller's identity signer + the embedded sponsor in one shot, mapping
/// any failure to a process exit code. The shared front-half of every sponsored
/// `bounty` write (post/claim/submit/accept/cancel).
fn load_signer_and_sponsor(
    caller: Option<&str>,
) -> Result<(k256::ecdsa::SigningKey, k256::ecdsa::SigningKey), i32> {
    let (key_file, key_hex) = resolve_caller_key(caller).map_err(|e| {
        eprintln!("{e}");
        2
    })?;
    let signer = wallet::from_private_key_hex(&key_hex).map_err(|e| {
        eprintln!("bad key in {key_file}: {e}");
        1
    })?;
    let sponsor = wallet::from_private_key_hex(SPONSOR_KEY).map_err(|e| {
        eprintln!("sponsor key error: {e}");
        1
    })?;
    Ok((signer, sponsor))
}

/// Resolve the caller's OWN registered tokenId — the `claimantTokenId` that earns
/// a bounty reward. Resolution order (each a `name.localharness.xyz` NFT the
/// caller controls):
///   1. If `--as <name>` was given AND that name is registered → its tokenId
///      (the explicit "act as THIS subdomain" intent).
///   2. Else the caller's MAIN identity (`mainOf(address)`), their primary NFT.
///   3. Else their single owned token (if they hold exactly one).
/// A caller with NO registered identity can't claim — they must `create <name>`
/// first (the reward needs an on-chain identity to be paid to).
async fn resolve_own_token_id(
    caller: Option<&str>,
    signer: &k256::ecdsa::SigningKey,
) -> Result<u64, String> {
    // 1. Explicit --as <name> that is registered.
    if let Some(name) = caller {
        if let Ok(id) = registry::id_of_name(name).await {
            if id != 0 {
                return Ok(id);
            }
        }
    }
    let addr = addr_to_hex(wallet::address(signer));
    // 2. The caller's MAIN identity.
    if let Ok(main_id) = registry::main_of(&addr).await {
        if main_id != 0 {
            return Ok(main_id);
        }
    }
    // 3. Their sole owned token (unambiguous), else a clear error.
    match registry::list_owned_tokens(&addr).await {
        Ok(tokens) if tokens.len() == 1 => Ok(tokens[0].token_id),
        Ok(tokens) if tokens.is_empty() => Err(format!(
            "no registered identity for {addr} — run `localharness create <name>` first \
             (a bounty reward needs an on-chain identity to pay)"
        )),
        Ok(tokens) => Err(format!(
            "{addr} owns {} subdomains and has no MAIN set — pass `--as <name>` to pick \
             which identity claims the bounty",
            tokens.len()
        )),
        Err(e) => Err(format!("RPC error resolving your tokenId: {e}")),
    }
}

/// Render one job row for the `jobs` listing. Pure (no I/O) so the layout is
/// unit-testable: id, target name, cadence, next run, budget remaining, runs
/// left, status.
fn format_job_row(id: u64, target: &str, job: &registry::ScheduledJob, task: &str, now: u64) -> String {
    let next = if job.next_run == 0 {
        "".to_string()
    } else if job.next_run <= now {
        "due now".to_string()
    } else {
        format!("in {}", fmt_interval(job.next_run - now))
    };
    let snippet: String = task.replace('\n', " ").chars().take(60).collect();
    format!(
        "  #{id}  {target}  every {interval}  next {next}  budget {budget}  runs-left {runs}  [{status}]\n      {snippet}",
        interval = fmt_interval(job.interval),
        budget = fmt_lh(job.budget_wei),
        runs = job.runs_left,
        status = job.status_label(),
    )
}

/// `localharness jobs [--as <me>]` — list the caller's scheduled jobs
/// (`jobsOf` + a `getJob`/`taskOf` per id). Read-only, no `$LH`.
async fn list_jobs(caller_name: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let addr = addr_to_hex(wallet::address(&signer));
    let ids = match registry::jobs_of(&addr).await {
        Ok(ids) => ids,
        Err(e) => {
            eprintln!("RPC error: {e}");
            return 1;
        }
    };
    if ids.is_empty() {
        println!("no scheduled jobs for {addr}");
        return 0;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    println!("{} scheduled job(s) for {addr}:", ids.len());
    for id in ids {
        let job = match registry::get_job(id).await {
            Ok(j) => j,
            Err(e) => {
                println!("  #{id}  (could not read: {e})");
                continue;
            }
        };
        // Resolve the target's name for readability; fall back to the id.
        let target = registry::name_of_id(job.target_id)
            .await
            .ok()
            .filter(|n| !n.is_empty())
            .unwrap_or_else(|| format!("token#{}", job.target_id));
        let task = registry::task_of(id).await.unwrap_or_default();
        println!("{}", format_job_row(id, &target, &job, &task, now));
    }
    0
}

/// `localharness unschedule [--as <me>] <jobId>` — cancel a scheduled job;
/// the facet refunds the remaining escrowed `$LH` to the owner.
async fn unschedule(caller_name: Option<&str>, job_id_arg: &str) -> i32 {
    let job_id: u64 = match job_id_arg.trim().trim_start_matches('#').parse() {
        Ok(n) => n,
        Err(_) => {
            eprintln!("unschedule: '{job_id_arg}' is not a job id (a number, e.g. 3)");
            return 2;
        }
    };
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    match registry::cancel_job_sponsored(&signer, &sponsor, job_id, registry::ALPHA_USD_ADDRESS).await
    {
        Ok(tx) => {
            println!("✓ cancelled job #{job_id} — remaining budget refunded to your wallet");
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("unschedule failed: {e}");
            1
        }
    }
}

async fn topup(caller_name: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    let sponsor = match wallet::from_private_key_hex(SPONSOR_KEY) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("sponsor key error: {e}");
            return 1;
        }
    };
    let addr = addr_to_hex(wallet::address(&signer));
    // 1. Claim the daily allowance (mints $LH) if eligible. The allowance is
    //    DISABLED on-chain (dailyAllowance=0 — a sybil risk), so this is a
    //    no-op in practice; the dormant path stays in case it's re-enabled.
    if registry::can_claim_credits(&addr).await.unwrap_or(false) {
        match registry::claim_daily_sponsored(&signer, &sponsor, registry::ALPHA_USD_ADDRESS).await {
            Ok(tx) => println!("claimed daily $LH  tx: {tx}"),
            Err(e) => eprintln!("claim failed (continuing to deposit): {e}"),
        }
    }
    // 2. Deposit the wallet balance into the per-request meter.
    let bal = registry::token_balance_of(&addr).await.unwrap_or(0);
    if bal == 0 {
        println!("wallet has 0 $LH — nothing to deposit.");
        println!("fund it first: `localharness redeem <code>`, or have another agent `send` you $LH.");
        return 0;
    }
    match registry::deposit_credits_sponsored(&signer, &sponsor, bal, registry::ALPHA_USD_ADDRESS)
        .await
    {
        Ok(tx) => {
            println!("deposited {} into the meter  tx: {tx}", fmt_lh(bal));
            0
        }
        Err(e) => {
            eprintln!("deposit failed: {e}");
            1
        }
    }
}

/// Deterministic, network-free QA checks the `probe` runs against the platform.
/// Each pushes a failure description on an UNEXPECTED result (a real bug); an
/// empty result means every invariant held. Pure + testable — the core of the
/// autonomous loop's read-only observe pass (roadmap Track B / Phase 2).
fn run_qa_checks() -> Vec<String> {
    let mut fails = Vec::new();
    // 1. A known-good cartridge compiles AND exposes an entry point.
    let good = "fn frame(t: i32) { host::display::clear(0); host::display::present(); }";
    match localharness::rustlite::compile(good) {
        Ok(wasm) if !cartridge_has_entry(&wasm) => {
            fails.push("a valid frame() cartridge compiled but has no frame/render export".into())
        }
        Ok(_) => {}
        Err(e) => fails.push(format!("a known-good cartridge failed to compile: {e}")),
    }
    // 2. Garbage source is rejected, not silently accepted.
    if localharness::rustlite::compile("this is not rustlite").is_ok() {
        fails.push("the compiler ACCEPTED non-rustlite garbage (should error)".into());
    }
    // 3. An entry-less cartridge is detectable (it would render a blank face).
    if let Ok(wasm) = localharness::rustlite::compile("fn helper(n: i32) -> i32 { n + 1 }") {
        if cartridge_has_entry(&wasm) {
            fails.push("an entry-less cartridge wrongly reports a frame/render export".into());
        }
    }
    fails
}

/// Agent-driven probe (`probe --deep`) — roadmap Track B at autonomy=observe.
/// An LLM agent with ONE read-only tool (qa_compile) under a deny-by-default
/// policy (0b enforcement) probes the rustlite compiler via the credit proxy
/// and files concrete findings on-chain. Needs a live run (proxy + Gemini).
async fn probe_agent(caller_name: Option<&str>) -> i32 {
    let (key_file, key_hex) = match resolve_caller_key(caller_name) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let caller = match wallet::from_private_key_hex(&key_hex) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("bad key in {key_file}: {e}");
            return 1;
        }
    };
    // Pay PER REQUEST (fund the meter), not a 10-$LH hour-long session.
    if let Ok(sponsor) = wallet::from_private_key_hex(SPONSOR_KEY) {
        let addr = addr_to_hex(wallet::address(&caller));
        if registry::credit_balance_of(&addr).await.unwrap_or(0) < CALL_COST_WEI {
            let _ = registry::deposit_credits_sponsored(
                &caller,
                &sponsor,
                CALL_METER_TOPUP_WEI,
                registry::ALPHA_USD_ADDRESS,
            )
            .await;
        }
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let token = registry::proxy_auth_token(&caller, now);
    let base = match url::Url::parse(registry::CREDIT_PROXY_URL) {
        Ok(u) => u,
        Err(e) => {
            eprintln!("internal: bad proxy url: {e}");
            return 1;
        }
    };

    // The ONE read-only tool: compile a source, report the result. No writes,
    // no secrets, no network — autonomy=observe.
    let qa_compile = localharness::ClosureTool::new(
        "qa_compile",
        "Compile rustlite source; report ok + wasm byte size + whether it exposes a \
         frame/render entry, OR the compile error. Probe with valid and invalid sources.",
        serde_json::json!({
            "type": "object",
            "properties": { "source": { "type": "string", "description": "rustlite source to compile" } },
            "required": ["source"]
        }),
        |args: serde_json::Value, _ctx| async move {
            let src = args.get("source").and_then(|v| v.as_str()).unwrap_or("");
            eprintln!("  probing: compiling {} bytes …", src.len());
            Ok(match localharness::rustlite::compile(src) {
                Ok(wasm) => serde_json::json!({
                    "ok": true, "wasm_bytes": wasm.len(), "has_entry": cartridge_has_entry(&wasm)
                }),
                Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }),
            })
        },
    );

    // Only the custom tool — no builtins. The agent tools then answers in prose
    // (no `finish` to short-circuit the text report). deny-by-default + allow
    // only qa_compile is 0b's "custom tools require a policy", at dispatch.
    let caps = localharness::types::CapabilitiesConfig {
        enabled_tools: Some(vec![]),
        enable_subagents: false,
        ..Default::default()
    };
    let policies = vec![localharness::deny_all(), localharness::Policy::allow("qa_compile")];

    let cfg = localharness::GeminiAgentConfig::new(token)
        .with_base_url(base)
        .with_system_instructions(
            "You are qa-observe, a READ-ONLY QA agent for localharness. Use qa_compile to \
             probe the rustlite compiler, then ANSWER IN TEXT with your findings: a short \
             numbered list of concrete issues you actually observed, or exactly 'no issues \
             found'. Be terse.",
        )
        .with_capabilities(caps)
        .with_policies(policies)
        .with_tool(qa_compile);

    println!("running observe-agent probe (live, via proxy) …");
    let agent = match localharness::Agent::start_gemini(cfg).await {
        Ok(a) => a,
        Err(e) => {
            eprintln!("could not start agent: {e}");
            return 1;
        }
    };
    // Drive the conversation until the agent answers in text. The first turn is
    // usually the qa_compile tool call (no prose); after the dispatcher feeds
    // the result back, a follow-up turn yields the findings. (The browser does
    // this via run_send's auto-continue; the CLI loops chat() — history persists
    // across calls on the same Agent.)
    let mut findings = String::new();
    let mut nudge = "Probe the rustlite compiler: try a valid `fn frame(t: i32)` cartridge that \
                     draws, an obviously invalid source, and one edge case via qa_compile."
        .to_string();
    for _ in 0..5 {
        match agent.chat(nudge.as_str()).await {
            Ok(r) => {
                let t = r.text().await.unwrap_or_default();
                if !t.trim().is_empty() {
                    findings = t;
                    break;
                }
            }
            Err(e) => {
                let _ = agent.shutdown().await;
                eprintln!("agent run failed: {e}");
                return 1;
            }
        }
        nudge = "Based on the qa_compile results so far, state your concrete findings now as a \
                 short numbered list in text, or exactly 'no issues found'."
            .to_string();
    }
    let _ = agent.shutdown().await;
    println!("--- agent findings ---\n{}", findings.trim());

    if findings.to_lowercase().contains("no issues") || findings.trim().is_empty() {
        println!("(agent reported no issues — nothing filed)");
        return 0;
    }
    let mut env = format!(
        "qa/v1 source=qa-observe v{}: {}",
        env!("CARGO_PKG_VERSION"),
        findings.replace('\n', " ")
    );
    if env.len() > 2048 {
        let mut cut = 2048;
        while cut > 0 && !env.is_char_boundary(cut) {
            cut -= 1;
        }
        env.truncate(cut);
    }
    let _ = feedback_submit(caller_name, &env).await;
    0
}

/// `localharness probe [--as <fleet>]` — the autonomous loop's read-only
/// observe pass. Runs deterministic QA checks against the platform plus one
/// live chain read; on any failure it REPORTS on-chain as a `qa/v1` feedback
/// envelope (no human bridge — the agent files its own bug). One-shot and
/// synchronous (no daemon). The checks are deterministic; network is touched
/// only for the chain read and the feedback submit (no `$LH` for the read).
async fn probe(caller_name: Option<&str>) -> i32 {
    let mut fails = run_qa_checks();
    // A live, read-only chain check: a known name must still resolve.
    match registry::owner_of_name("claude").await {
        Ok(Some(_)) => {}
        Ok(None) => fails.push("registry reports claude.localharness.xyz unregistered".into()),
        Err(e) => fails.push(format!("chain read failed: {e}")),
    }

    if fails.is_empty() {
        println!("✓ probe: all platform checks passed");
        return 0;
    }
    eprintln!("probe found {} issue(s):", fails.len());
    for f in &fails {
        eprintln!("  - {f}");
    }
    // Report on-chain as the fleet identity (best-effort). The qa/v1 envelope
    // marks fleet-authored feedback so a future triage pass can filter it.
    let mut envelope = format!(
        "qa/v1 source=qa-probe v{}: {}",
        env!("CARGO_PKG_VERSION"),
        fails.join(" | ")
    );
    if envelope.len() > 2048 {
        let mut cut = 2048;
        while cut > 0 && !envelope.is_char_boundary(cut) {
            cut -= 1;
        }
        envelope.truncate(cut);
    }
    if feedback_submit(caller_name, &envelope).await == 0 {
        eprintln!("  → reported on-chain");
    }
    1
}

fn to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Parse a `0x`-optional 20-byte hex address into bytes.
fn parse_addr20(s: &str) -> Option<[u8; 20]> {
    let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
    if t.len() != 40 {
        return None;
    }
    let mut out = [0u8; 20];
    for (i, slot) in out.iter_mut().enumerate() {
        *slot = u8::from_str_radix(t.get(i * 2..i * 2 + 2)?, 16).ok()?;
    }
    Some(out)
}

/// Registry name rule = a valid DNS label: 1-63 chars, lowercase a-z / 0-9 /
/// hyphen, and NO leading/trailing hyphen (RFC 1035 — a label like `-foo` or
/// `foo-` is a dead-on-arrival subdomain). Surfaced by the test-user fleet
/// (juno-qa) — emoji/oversized were already caught, the hyphen edge was not.
fn name_is_valid(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 63
        && !name.starts_with('-')
        && !name.ends_with('-')
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

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

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

    #[test]
    fn gitignore_already_covers_detects_wildcard_and_exact() {
        // wildcard covers any key file
        assert!(gitignore_already_covers("target/\n*.localharness.key\n", "alice.localharness.key"));
        // exact filename covers itself
        assert!(gitignore_already_covers("alice.localharness.key\n", "alice.localharness.key"));
        // tolerant of surrounding whitespace
        assert!(gitignore_already_covers("  *.localharness.key  \n", "x.localharness.key"));
        // not covered → needs appending
        assert!(!gitignore_already_covers("target/\nnode_modules/\n", "alice.localharness.key"));
        // a different exact key does NOT count as covering this one
        assert!(!gitignore_already_covers("bob.localharness.key\n", "alice.localharness.key"));
        // empty gitignore → not covered
        assert!(!gitignore_already_covers("", "alice.localharness.key"));
    }

    #[test]
    fn pick_key_read_path_prefers_cwd_then_home() {
        let cwd = "alice.localharness.key".to_string();
        let home = Some("/home/me/.localharness/keys/alice.localharness.key".to_string());

        // cwd exists → cwd wins (back-compat: pre-existing local keys keep working)
        assert_eq!(
            pick_key_read_path(cwd.clone(), true, home.clone(), true),
            Some(cwd.clone())
        );
        // cwd exists even when home doesn't → still cwd
        assert_eq!(
            pick_key_read_path(cwd.clone(), true, None, false),
            Some(cwd.clone())
        );
        // cwd absent, home present → home (the new safe default location)
        assert_eq!(
            pick_key_read_path(cwd.clone(), false, home.clone(), true),
            home.clone()
        );
        // neither exists → None (caller surfaces "run create first")
        assert_eq!(pick_key_read_path(cwd.clone(), false, home.clone(), false), None);
        // no home dir resolvable and no cwd key → None
        assert_eq!(pick_key_read_path(cwd, false, None, false), None);
    }

    #[test]
    fn key_is_in_cwd_distinguishes_bare_from_pathful() {
        // a bare cwd filename → in cwd (needs .gitignore protection)
        assert!(key_is_in_cwd("alice.localharness.key"));
        // a config-home (absolute) path → NOT in cwd (no project .gitignore)
        assert!(!key_is_in_cwd("/home/me/.localharness/keys/alice.localharness.key"));
        assert!(!key_is_in_cwd("C:\\Users\\me\\.localharness\\keys\\a.localharness.key"));
    }

    #[test]
    fn key_home_dir_from_honors_override_and_falls_back() {
        use std::path::PathBuf;
        // $LOCALHARNESS_HOME wins outright when set.
        assert_eq!(
            key_home_dir_from(Some("/custom/keys"), Some("/u/prof"), Some("/u/home")),
            Some(PathBuf::from("/custom/keys"))
        );
        // No override → USERPROFILE (Windows), with the .localharness/keys suffix.
        assert_eq!(
            key_home_dir_from(None, Some("/u/prof"), None),
            Some(PathBuf::from("/u/prof").join(".localharness").join("keys"))
        );
        // No override, no USERPROFILE → HOME (Unix).
        assert_eq!(
            key_home_dir_from(None, None, Some("/u/home")),
            Some(PathBuf::from("/u/home").join(".localharness").join("keys"))
        );
        // Empty strings are treated as unset.
        assert_eq!(
            key_home_dir_from(Some(""), Some(""), Some("/u/home")),
            Some(PathBuf::from("/u/home").join(".localharness").join("keys"))
        );
        // Nothing set → None (caller falls back to the cwd).
        assert_eq!(key_home_dir_from(None, None, None), None);
    }

    #[test]
    fn parse_create_args_name_only_and_with_persona() {
        let (n, p) = parse_create_args(&args(&["alice"])).unwrap();
        assert_eq!(n, "alice");
        assert_eq!(p, None);

        let (n, p) = parse_create_args(&args(&["alice", "--persona", "you", "are", "alice"]))
            .unwrap();
        assert_eq!(n, "alice");
        assert_eq!(p.as_deref(), Some("you are alice"));
    }

    #[test]
    fn parse_create_args_rejects_bad_forms() {
        assert!(parse_create_args(&args(&[])).is_err()); // no name
        assert!(parse_create_args(&args(&["alice", "--persona"])).is_err()); // empty persona
        assert!(parse_create_args(&args(&["alice", "bob"])).is_err()); // stray positional
    }

    #[test]
    fn parse_call_plain_target_and_message() {
        let p = parse_call_args(&args(&["alice", "how", "are", "you"])).unwrap();
        assert_eq!(p.caller, None);
        assert_eq!(p.target, "alice");
        assert_eq!(p.message, "how are you");
    }

    #[test]
    fn parse_call_single_word_message() {
        let p = parse_call_args(&args(&["alice", "hello"])).unwrap();
        assert_eq!(p.caller, None);
        assert_eq!(p.target, "alice");
        assert_eq!(p.message, "hello");
    }

    #[test]
    fn parse_call_with_as_flag() {
        let p = parse_call_args(&args(&["--as", "bob", "alice", "what's", "up"])).unwrap();
        assert_eq!(p.caller.as_deref(), Some("bob"));
        assert!(!p.fresh);
        assert_eq!(p.target, "alice");
        assert_eq!(p.message, "what's up");
    }

    #[test]
    fn parse_call_fresh_flag() {
        let p = parse_call_args(&args(&["--fresh", "alice", "hi"])).unwrap();
        assert!(p.fresh);
        assert_eq!(p.caller, None);
        assert_eq!(p.target, "alice");
        assert_eq!(p.message, "hi");
    }

    #[test]
    fn parse_call_flags_order_independent() {
        let a = parse_call_args(&args(&["--as", "bob", "--fresh", "alice", "hi"])).unwrap();
        let b = parse_call_args(&args(&["--fresh", "--as", "bob", "alice", "hi"])).unwrap();
        for p in [a, b] {
            assert_eq!(p.caller.as_deref(), Some("bob"));
            assert!(p.fresh);
            assert_eq!(p.target, "alice");
            assert_eq!(p.message, "hi");
        }
    }

    #[test]
    fn parse_call_accepts_model_flag_in_any_order() {
        // `--as`/`--model`/`--fresh` may appear in any order before the target.
        let perms = [
            vec!["--model", "claude-opus", "--as", "bob", "--fresh", "alice", "hi"],
            vec!["--fresh", "--model", "claude-opus", "--as", "bob", "alice", "hi"],
            vec!["--as", "bob", "--model", "claude-opus", "--fresh", "alice", "hi"],
        ];
        for parts in perms {
            let p = parse_call_args(&args(&parts)).unwrap();
            assert_eq!(p.caller.as_deref(), Some("bob"));
            assert_eq!(p.model.as_deref(), Some("claude-opus"));
            assert!(p.fresh);
            assert_eq!(p.target, "alice");
            assert_eq!(p.message, "hi");
        }
        // `--model` requires a value.
        assert!(parse_call_args(&args(&["--model"])).is_err());
    }

    #[test]
    fn parse_call_defaults_to_not_fresh() {
        let p = parse_call_args(&args(&["alice", "hi"])).unwrap();
        assert!(!p.fresh);
    }

    #[test]
    fn parse_call_message_preserves_internal_spacing_as_single_spaces() {
        // join(" ") normalises arg boundaries to single spaces — documents the
        // contract so a caller relying on exact whitespace isn't surprised.
        let p = parse_call_args(&args(&["alice", "a", "b", "c"])).unwrap();
        assert_eq!(p.message, "a b c");
    }

    #[test]
    fn parse_call_rejects_missing_message() {
        assert!(parse_call_args(&args(&["alice"])).is_err());
    }

    // ---- mcp-call (the hosted MCP-over-HTTP + x402 client) ----------------

    #[test]
    fn parse_mcp_call_defaults_and_flags() {
        // Plain target + message: caller None, default pay.
        let p = parse_mcp_call_args(&args(&["claude", "hi", "there"])).unwrap();
        assert_eq!(p.caller, None);
        assert_eq!(p.pay, MCP_CALL_DEFAULT_PAY);
        assert_eq!(p.target, "claude");
        assert_eq!(p.message, "hi there");

        // Flags in any order before the target.
        for parts in [
            vec!["--as", "bob", "--pay", "0.5", "claude", "yo"],
            vec!["--pay", "0.5", "--as", "bob", "claude", "yo"],
        ] {
            let p = parse_mcp_call_args(&args(&parts)).unwrap();
            assert_eq!(p.caller.as_deref(), Some("bob"));
            assert_eq!(p.pay, "0.5");
            assert_eq!(p.target, "claude");
            assert_eq!(p.message, "yo");
        }
    }

    #[test]
    fn parse_mcp_call_rejects_bad_forms() {
        assert!(parse_mcp_call_args(&args(&[])).is_err()); // empty
        assert!(parse_mcp_call_args(&args(&["claude"])).is_err()); // no message
        assert!(parse_mcp_call_args(&args(&["--as"])).is_err()); // dangling --as
        assert!(parse_mcp_call_args(&args(&["--pay"])).is_err()); // dangling --pay
        assert!(parse_mcp_call_args(&args(&["--pay", "1", "claude"])).is_err()); // no message
    }

    #[test]
    fn mcp_call_pay_parses_to_18_decimal_wei() {
        // The default + a few human amounts map to the bundle's 18-dec wei.
        assert_eq!(
            localharness::encoding::parse_token_amount(MCP_CALL_DEFAULT_PAY),
            Some(1_000_000_000_000_000) // 0.001 * 1e18
        );
        assert_eq!(
            localharness::encoding::parse_token_amount("1"),
            Some(1_000_000_000_000_000_000)
        );
    }

    #[test]
    fn mcp_x402_header_json_matches_proxy_shape() {
        // The exact field names + types `proxy/api/mcp.ts::parseAuth` requires.
        let from = "0x00000000000000000000000000000000000000aa";
        let to = "0x00000000000000000000000000000000000000bb";
        let nonce = [0x11u8; 32];
        let sig = [0x22u8; 65];
        let j = mcp_x402_header_json(from, to, 1_000_000_000_000_000, 0, 1_999_999_999, &nonce, &sig);

        assert_eq!(j["from"], from);
        assert_eq!(j["to"], to);
        // value is a DECIMAL STRING of $LH wei (not a number).
        assert_eq!(j["value"], "1000000000000000");
        assert!(j["value"].is_string());
        assert_eq!(j["validAfter"], 0);
        assert_eq!(j["validBefore"], 1_999_999_999u64);
        // nonce: 0x + 32 bytes = 64 hex chars. signature: 0x + 65 bytes = 130 hex.
        let nonce_s = j["nonce"].as_str().unwrap();
        let sig_s = j["signature"].as_str().unwrap();
        assert_eq!(nonce_s.len(), 2 + 64);
        assert!(nonce_s.starts_with("0x"));
        assert_eq!(sig_s.len(), 2 + 130);
        assert!(sig_s.starts_with("0x"));
    }

    #[test]
    fn mcp_tools_call_body_is_ask_agent_jsonrpc() {
        let b = mcp_tools_call_body("claude", "hello");
        assert_eq!(b["jsonrpc"], "2.0");
        assert_eq!(b["method"], "tools/call");
        // params.name is the TOOL ("ask_agent"); the target rides in arguments.
        assert_eq!(b["params"]["name"], "ask_agent");
        assert_eq!(b["params"]["arguments"]["name"], "claude");
        assert_eq!(b["params"]["arguments"]["message"], "hello");
    }

    #[test]
    fn mcp_random_nonce_is_32_bytes_and_fresh() {
        let a = registry::random_x402_nonce();
        let b = registry::random_x402_nonce();
        assert_eq!(a.len(), 32);
        assert_eq!(b.len(), 32);
        // Two draws of a CSPRNG should differ (vanishing collision odds).
        assert_ne!(a, b);
    }

    #[test]
    fn mcp_endpoint_is_proxy_slash_mcp() {
        let url = mcp_endpoint_url();
        assert!(url.ends_with("/mcp"));
        assert!(!url.contains("//mcp")); // no double slash from the base
    }

    #[test]
    fn parse_call_rejects_empty() {
        assert!(parse_call_args(&args(&[])).is_err());
    }

    #[test]
    fn parse_call_rejects_as_without_name() {
        assert!(parse_call_args(&args(&["--as"])).is_err());
    }

    #[test]
    fn parse_call_rejects_as_name_without_target_or_message() {
        // `--as bob` alone: caller set, but no target/message → usage error.
        assert!(parse_call_args(&args(&["--as", "bob"])).is_err());
        // `--as bob alice` : target but no message → usage error.
        assert!(parse_call_args(&args(&["--as", "bob", "alice"])).is_err());
    }

    #[test]
    fn thread_file_target_parses_own_files_only() {
        // Backend-tagged files (current format): the tag is stripped.
        assert_eq!(
            thread_file_target("claude", "claude__alice.gemini.bin").as_deref(),
            Some("alice")
        );
        assert_eq!(
            thread_file_target("claude", "claude__alice.anthropic.bin").as_deref(),
            Some("alice")
        );
        // Legacy untagged files still parse (backward compatibility).
        assert_eq!(
            thread_file_target("claude", "claude__alice.bin").as_deref(),
            Some("alice")
        );
        // A target containing the separator stays intact (strip_prefix once).
        assert_eq!(
            thread_file_target("claude", "claude__a__b.gemini.bin").as_deref(),
            Some("a__b")
        );
        // Different caller → not ours.
        assert_eq!(thread_file_target("claude", "bob__alice.gemini.bin"), None);
        // Wrong extension, or empty target → rejected.
        assert_eq!(thread_file_target("claude", "claude__alice.txt"), None);
        assert_eq!(thread_file_target("claude", "claude__.bin"), None);
        assert_eq!(thread_file_target("claude", "claude__.gemini.bin"), None);
        assert_eq!(thread_file_target("claude", "unrelated.bin"), None);
    }

    #[test]
    fn thread_file_target_roundtrips_history_path() {
        // The parser must invert the filename half of history_path for both
        // backends.
        for backend in ["gemini", "anthropic"] {
            let p = history_path("claude", "alice", backend);
            let name = p.file_name().unwrap().to_str().unwrap();
            assert_eq!(thread_file_target("claude", name).as_deref(), Some("alice"));
        }
    }

    #[test]
    fn model_backend_tag_routes_claude_to_anthropic() {
        assert_eq!(model_backend_tag(Some("claude-opus-4")), "anthropic");
        assert_eq!(model_backend_tag(Some("claude")), "anthropic");
        assert_eq!(model_backend_tag(Some("gemini-3.5-flash")), "gemini");
        assert_eq!(model_backend_tag(None), "gemini");
    }

    #[test]
    fn history_path_keys_on_backend_so_formats_never_collide() {
        // The cross-backend bug: a Gemini thread and an Anthropic thread to the
        // same target must live in SEPARATE files (incompatible on-disk shapes).
        let g = history_path("claude", "alice", "gemini");
        let a = history_path("claude", "alice", "anthropic");
        assert_ne!(g, a, "backends must not share a history file");
        assert!(g.ends_with("claude__alice.gemini.bin"));
        assert!(a.ends_with("claude__alice.anthropic.bin"));
    }

    #[test]
    fn take_as_flag_extracts_caller() {
        let a = args(&["--as", "bob", "threads"]);
        let (caller, rest) = take_as_flag(&a).unwrap();
        assert_eq!(caller.as_deref(), Some("bob"));
        assert_eq!(rest, vec!["threads".to_string()]);

        let b = args(&["alice"]);
        let (caller, rest) = take_as_flag(&b).unwrap();
        assert_eq!(caller, None);
        assert_eq!(rest, vec!["alice".to_string()]);

        assert!(take_as_flag(&args(&["--as"])).is_err());
    }

    #[test]
    fn take_as_flag_scans_any_position() {
        // The real bug: `probe --deep --as fleet` — `--as` is NOT first, so the
        // old first-arg-only parser missed it and the fleet name never resolved.
        let (caller, rest) = take_as_flag(&args(&["--deep", "--as", "fleet"])).unwrap();
        assert_eq!(caller.as_deref(), Some("fleet"));
        assert_eq!(rest, vec!["--deep".to_string()]);

        // Trailing flag is still consumed; surrounding args preserved in order.
        let (caller, rest) = take_as_flag(&args(&["a", "b", "--as", "me", "c"])).unwrap();
        assert_eq!(caller.as_deref(), Some("me"));
        assert_eq!(rest, vec!["a".to_string(), "b".to_string(), "c".to_string()]);

        // `--as` requiring a value, even mid-list.
        assert!(take_as_flag(&args(&["--deep", "--as"])).is_err());
        // A duplicated `--as` is an error, not a silent last-wins.
        assert!(take_as_flag(&args(&["--as", "a", "--as", "b"])).is_err());
    }

    #[test]
    fn history_path_keys_on_caller_and_target() {
        let p = history_path("claude", "alice", "gemini");
        assert!(p.ends_with("claude__alice.gemini.bin"));
        // Distinct caller or target → distinct file (no cross-thread bleed).
        assert_ne!(
            history_path("claude", "alice", "gemini"),
            history_path("bob", "alice", "gemini")
        );
        assert_ne!(
            history_path("claude", "alice", "gemini"),
            history_path("claude", "bob", "gemini")
        );
        // Lives under a hidden dir so it doesn't clutter the working tree.
        assert!(p.starts_with(".localharness"));
    }

    #[test]
    fn format_whoami_unregistered_is_one_line() {
        let info = WhoamiInfo {
            name: "ghost".into(),
            owner: None,
            token_id: 0,
            tba: None,
            has_persona: false,
            public_face: None,
        };
        assert_eq!(format_whoami(&info), "ghost is unregistered");
    }

    #[test]
    fn format_whoami_full_profile() {
        let info = WhoamiInfo {
            name: "claude".into(),
            owner: Some("0xabc".into()),
            token_id: 8,
            tba: Some("0xdef".into()),
            has_persona: true,
            public_face: Some("app".into()),
        };
        let out = format_whoami(&info);
        assert!(out.starts_with("claude.localharness.xyz\n"));
        assert!(out.contains("owner    0xabc"));
        assert!(out.contains("tokenId  8"));
        assert!(out.contains("wallet   0xdef  (token-bound account)"));
        assert!(out.contains("persona  published"));
        assert!(out.contains("face     app"));
    }

    #[test]
    fn format_whoami_absent_persona_and_face() {
        let info = WhoamiInfo {
            name: "bare".into(),
            owner: Some("0x1".into()),
            token_id: 3,
            tba: None,
            has_persona: false,
            public_face: None,
        };
        let out = format_whoami(&info);
        assert!(out.contains("persona  none"));
        assert!(out.contains("face     unset (directory)"));
        assert!(out.contains("wallet   —"));
    }

    #[test]
    fn format_whoami_json_registered_roundtrips() {
        let info = WhoamiInfo {
            name: "claude".into(),
            owner: Some("0xabc".into()),
            token_id: 8,
            tba: Some("0xdef".into()),
            has_persona: true,
            public_face: Some("app".into()),
        };
        let v: serde_json::Value = serde_json::from_str(&format_whoami_json(&info)).unwrap();
        assert_eq!(v["name"], "claude");
        assert_eq!(v["registered"], true);
        assert_eq!(v["owner"], "0xabc");
        assert_eq!(v["tokenId"], 8);
        assert_eq!(v["wallet"], "0xdef");
        assert_eq!(v["persona"], true);
        assert_eq!(v["face"], "app");
    }

    #[test]
    fn format_whoami_json_unregistered_nulls() {
        let info = WhoamiInfo {
            name: "ghost".into(),
            owner: None,
            token_id: 0,
            tba: None,
            has_persona: false,
            public_face: None,
        };
        let v: serde_json::Value = serde_json::from_str(&format_whoami_json(&info)).unwrap();
        assert_eq!(v["registered"], false);
        assert!(v["owner"].is_null());
        assert!(v["wallet"].is_null());
        assert!(v["face"].is_null());
        assert_eq!(v["persona"], false);
    }

    #[test]
    fn hint_for_call_error_classifies_common_failures() {
        // Payment / session / credits → the $LH hint.
        for s in [
            "HTTP 402 Payment Required",
            "proxy: no session for 0xabc",
            "insufficient credit",
        ] {
            assert!(
                hint_for_call_error(s).unwrap().contains("$LH"),
                "expected $LH hint for {s:?}"
            );
        }
        // Auth → the signature hint.
        for s in ["401 Unauthorized", "bad signature", "403 Forbidden"] {
            assert!(
                hint_for_call_error(s).unwrap().contains("signature"),
                "expected auth hint for {s:?}"
            );
        }
        // Rate limit.
        assert!(hint_for_call_error("429 Too Many Requests")
            .unwrap()
            .contains("rate limited"));
    }

    #[test]
    fn hint_for_call_error_is_case_insensitive_and_silent_on_unknown() {
        assert!(hint_for_call_error("PAYMENT REQUIRED").is_some());
        // An unrecognised error gets no hint (caller still prints the raw text).
        assert_eq!(hint_for_call_error("connection reset by peer"), None);
        assert_eq!(hint_for_call_error("some unrelated parse error"), None);
    }

    #[test]
    fn rustlite_compiles_a_minimal_cartridge() {
        // Uses only primitives proven in the live claude-app.rl face.
        let src = "fn frame(t: i32) {\n  \
                   let w: i32 = host::display::width();\n  \
                   host::display::clear(0);\n  \
                   host::display::fill_rect(0, 0, w, 8, 16777215);\n  \
                   host::display::present();\n}";
        let wasm = localharness::rustlite::compile(src).expect("minimal cartridge compiles");
        assert_eq!(&wasm[0..4], b"\0asm", "valid wasm magic header");
        assert!(wasm.len() <= PUBLISH_CAP);
    }

    #[test]
    fn rustlite_rejects_garbage() {
        assert!(localharness::rustlite::compile("this is not rustlite").is_err());
    }

    #[test]
    fn cartridge_entry_detection() {
        // A real frame() cartridge exports the entry the loader calls.
        let with =
            localharness::rustlite::compile("fn frame(t: i32) { host::display::present(); }")
                .unwrap();
        assert!(cartridge_has_entry(&with), "frame() must be detected");

        // Compiles, but only a helper — no entry → would render nothing.
        let without = localharness::rustlite::compile("fn helper(n: i32) -> i32 { n + 1 }").unwrap();
        assert!(!cartridge_has_entry(&without), "no entry must be rejected");

        // The shipped bitmask cartridge has an entry.
        let bitmask = localharness::rustlite::compile(include_str!("../../bitmask.rl")).unwrap();
        assert!(cartridge_has_entry(&bitmask));

        // Malformed / truncated bytes never panic and report no entry.
        assert!(!cartridge_has_entry(b""));
        assert!(!cartridge_has_entry(b"\0asm")); // header only
        assert!(!cartridge_has_entry(b"\0asm\x01\0\0\0\x07\xff")); // bogus section size
    }

    #[test]
    fn name_validation_matches_registry_rule() {
        assert!(name_is_valid("alice"));
        assert!(name_is_valid("a-1-b"));
        assert!(!name_is_valid("Alice")); // uppercase
        assert!(!name_is_valid("a_b")); // underscore
        assert!(!name_is_valid("")); // empty
        assert!(name_is_valid(&"a".repeat(63)));
        assert!(!name_is_valid(&"a".repeat(64))); // too long
        assert!(!name_is_valid("🤖")); // emoji (non-ascii) — already caught
        assert!(!name_is_valid("-foo")); // leading hyphen — not a valid DNS label
        assert!(!name_is_valid("foo-")); // trailing hyphen
        assert!(!name_is_valid("-")); // only a hyphen
        assert!(name_is_valid("a-b-c")); // internal hyphens are fine
    }

    #[test]
    fn usage_documents_every_command() {
        // Every dispatchable subcommand must appear in the help text, so a new
        // command can't ship undocumented for beta testers reading `help`.
        for cmd in [
            "create", "compile", "publish", "face", "persona", "call", "list",
            "feedback", "probe", "triage", "threads", "forget", "whoami", "invite",
            "bounty",
        ] {
            assert!(
                USAGE.contains(cmd),
                "`{cmd}` is dispatchable but missing from the help/USAGE text"
            );
        }
    }

    #[test]
    fn parse_list_flags_handles_as_and_json_any_order() {
        assert_eq!(parse_list_flags(&args(&[])).unwrap(), (None, false));
        assert_eq!(parse_list_flags(&args(&["--json"])).unwrap(), (None, true));
        let (c, j) = parse_list_flags(&args(&["--as", "bob", "--json"])).unwrap();
        assert_eq!((c.as_deref(), j), (Some("bob"), true));
        let (c, j) = parse_list_flags(&args(&["--json", "--as", "bob"])).unwrap();
        assert_eq!((c.as_deref(), j), (Some("bob"), true));
        assert!(parse_list_flags(&args(&["--as"])).is_err()); // dangling --as
        assert!(parse_list_flags(&args(&["alice"])).is_err()); // no positionals
    }

    #[test]
    fn format_owned_text_and_json() {
        let toks = vec![
            registry::OwnedToken { token_id: 8, name: "claude".into(), tba: Some("0xabc".into()) },
            registry::OwnedToken { token_id: 3, name: "alice".into(), tba: None },
        ];
        let text = format_owned("0xowner", &toks, false);
        assert!(text.contains("2 subdomain"));
        assert!(text.contains("claude  (tokenId 8)  0xabc"));
        assert!(text.contains("alice  (tokenId 3)  —"));

        let v: serde_json::Value =
            serde_json::from_str(&format_owned("0xowner", &toks, true)).unwrap();
        assert_eq!(v["count"], 2);
        assert_eq!(v["owner"], "0xowner");
        assert_eq!(v["subdomains"][0]["name"], "claude");
        assert_eq!(v["subdomains"][0]["tokenId"], 8);
        assert!(v["subdomains"][1]["wallet"].is_null());
    }

    #[test]
    fn read_file_clean_maps_not_found_without_leaking_os_error() {
        // Closes on-chain QA finding #1: "os error 2" must not reach the user.
        let err = read_file_clean("definitely-nonexistent-file-xyz123.rl").unwrap_err();
        assert!(err.contains("file not found"), "got: {err}");
        assert!(err.contains("definitely-nonexistent-file-xyz123.rl"), "got: {err}");
        assert!(!err.contains("os error"), "must not leak raw OS error: {err}");
    }

    #[test]
    fn looks_like_path_distinguishes_files_from_prose() {
        // Path-shaped: separators or known source/text extensions.
        assert!(looks_like_path("persona.txt"));
        assert!(looks_like_path("prompts/agent.md"));
        assert!(looks_like_path("C:\\agents\\bob.prompt"));
        assert!(looks_like_path("./x.rl"));
        // Plain prose persona text is NOT a path.
        assert!(!looks_like_path("You are bob, a helpful agent"));
        assert!(!looks_like_path("bob"));
    }

    #[test]
    fn resolve_persona_arg_literal_text_passthrough() {
        // A non-path-shaped, unreadable string is the persona text verbatim —
        // it must NOT touch the filesystem error path.
        let p = resolve_persona_arg("You are bob, answer tersely").unwrap();
        assert_eq!(p, "You are bob, answer tersely");
    }

    #[test]
    fn resolve_persona_arg_missing_file_is_clean_error() {
        // A path-shaped arg that doesn't exist → clean error, no raw OS error,
        // and NOT silently used as literal text.
        let err = resolve_persona_arg("definitely-nonexistent-xyz123.txt").unwrap_err();
        assert!(err.contains("file not found"), "got: {err}");
        assert!(!err.contains("os error"), "must not leak raw OS error: {err}");
    }

    #[test]
    fn qa_checks_pass_on_a_healthy_platform() {
        // The probe's deterministic invariants must hold against the shipped
        // rustlite + entry detector. If this fails, the probe would (correctly)
        // file an on-chain bug — so it doubles as a platform-health assertion.
        let fails = run_qa_checks();
        assert!(fails.is_empty(), "probe found issues on a healthy build: {fails:?}");
    }

    #[test]
    fn triage_dedups_and_ranks_by_recurrence() {
        let bodies = vec![
            "Compile leaks OS error".to_string(),
            "compile leaks os error".to_string(),       // same modulo case
            "  Compile   leaks OS error ".to_string(),  // same modulo whitespace
            "whoami is slow".to_string(),
        ];
        let ranked = triage_findings(&bodies);
        assert_eq!(ranked.len(), 2, "two distinct issues after dedup");
        assert_eq!(ranked[0].1, 3, "the recurring one ranks first with count 3");
        assert!(ranked[0].0.to_lowercase().contains("compile leaks"));
        assert_eq!(ranked[1].1, 1);
    }

    #[test]
    fn triage_skips_empty_bodies() {
        let bodies = vec!["".to_string(), "   ".to_string(), "real bug".to_string()];
        let ranked = triage_findings(&bodies);
        assert_eq!(ranked, vec![("real bug".to_string(), 1)]);
    }

    #[test]
    fn parse_qa_envelope_accepts_valid_rejects_others() {
        let env =
            parse_qa_envelope("qa/v1 source=qa-probe v0.20.0: compile leaked os error").unwrap();
        assert_eq!(env.source, "qa-probe");
        assert_eq!(env.version, "0.20.0");
        assert!(env.body.contains("compile leaked"));
        // Not a fleet envelope → rejected (triage won't consume its body).
        assert!(parse_qa_envelope("just some human feedback").is_none());
        assert!(parse_qa_envelope("qa/v1 source=x v1.0.0:   ").is_none()); // empty body
        assert!(parse_qa_envelope("qa/v1 no source or colon").is_none());
        assert!(parse_qa_envelope("qa/v1 source=x vNOTVERSION: body").is_none());
    }

    #[test]
    fn feedback_json_emits_fields_and_fleet_envelope() {
        let entries = vec![
            registry::FeedbackEntry {
                sender: "0xabc".into(),
                timestamp: 100,
                text: "[BUG] something broke".into(),
            },
            registry::FeedbackEntry {
                sender: "0xdef".into(),
                timestamp: 200,
                text: "qa/v1 source=qa-probe v0.20.0: a real bug".into(),
            },
        ];
        let v: serde_json::Value = serde_json::from_str(&feedback_json(&entries)).unwrap();
        let arr = v.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        // plain entry: dedup-key fields + raw text, no fleet fields
        assert_eq!(arr[0]["sender"], "0xabc");
        assert_eq!(arr[0]["timestamp"], 100);
        assert_eq!(arr[0]["text"], "[BUG] something broke");
        assert!(arr[0].get("fleet_source").is_none());
        // qa/v1 envelope: gets fleet_source + decoded body
        assert_eq!(arr[1]["fleet_source"], "qa-probe");
        assert!(arr[1]["body"].as_str().unwrap().contains("a real bug"));
        // empty log → valid empty array
        let empty: serde_json::Value = serde_json::from_str(&feedback_json(&[])).unwrap();
        assert_eq!(empty.as_array().unwrap().len(), 0);
    }

    #[test]
    fn format_feedback_tags_fleet_envelopes_only() {
        let entries = vec![
            registry::FeedbackEntry {
                sender: "0x1".into(),
                timestamp: 1,
                text: "qa/v1 source=qa-probe v0.20.0: a real bug".into(),
            },
            registry::FeedbackEntry {
                sender: "0x2".into(),
                timestamp: 2,
                text: "a human note".into(),
            },
        ];
        let out = format_feedback(&entries);
        assert!(out.contains("[fleet:qa-probe]"));
        assert!(
            out.lines().any(|l| l.contains("0x2") && !l.contains("[fleet")),
            "human feedback must not be tagged as fleet"
        );
    }

    #[test]
    fn format_feedback_empty_and_entries() {
        assert!(format_feedback(&[]).contains("no on-chain feedback"));
        let entries = vec![
            registry::FeedbackEntry {
                sender: "0xabc".into(),
                timestamp: 1700000000,
                text: "create flow worked\nbut whoami was slow".into(),
            },
        ];
        let out = format_feedback(&entries);
        assert!(out.contains("1 on-chain feedback"));
        assert!(out.contains("0xabc"));
        // Newlines collapsed so one entry stays one block.
        assert!(out.contains("create flow worked but whoami was slow"));
    }

    #[test]
    fn format_owned_empty() {
        assert!(format_owned("0xo", &[], false).contains("no subdomains"));
        let v: serde_json::Value = serde_json::from_str(&format_owned("0xo", &[], true)).unwrap();
        assert_eq!(v["count"], 0);
        assert!(v["subdomains"].as_array().unwrap().is_empty());
    }

    #[test]
    fn sponsor_key_is_valid_and_derives_documented_address() {
        // The embedded SPONSOR_KEY pays fees for EVERY sponsored CLI op
        // (create/publish/persona). If it's stale or mistyped, all onboarding
        // silently fails. Guard that it parses and derives the documented
        // sponsor address (the dedicated low-budget key, rotated 2026-05-25) —
        // so a future rotation that forgets the bin won't ship broken.
        let signer = wallet::from_private_key_hex(SPONSOR_KEY).expect("SPONSOR_KEY must parse");
        let addr = format!("0x{}", to_hex(&wallet::address(&signer)));
        assert_eq!(
            addr.to_ascii_lowercase(),
            "0x0aff88ad13ef24cac5befd0f9dc3a05df79a922c",
            "SPONSOR_KEY no longer derives the documented sponsor address"
        );
    }

    #[test]
    fn llms_txt_publishes_canonical_onchain_constants() {
        // The agent-facing spec is read by agents to orient on-chain. It must
        // not drift from the code's source of truth — stale addresses would
        // send an agent to the wrong chain/contract. Automates the manual
        // "audit llms.txt vs registry.rs" pass.
        let spec = include_str!("../../web/llms.txt");
        assert!(
            spec.contains(registry::REGISTRY_ADDRESS),
            "llms.txt missing canonical diamond address {}",
            registry::REGISTRY_ADDRESS
        );
        assert!(
            spec.contains(registry::LOCALHARNESS_TOKEN_ADDRESS),
            "llms.txt missing the $LH token address {}",
            registry::LOCALHARNESS_TOKEN_ADDRESS
        );
        assert!(
            spec.contains(registry::RPC_URL),
            "llms.txt missing the RPC URL {}",
            registry::RPC_URL
        );
        assert!(
            spec.contains(&registry::CHAIN_ID.to_string()),
            "llms.txt missing chain id {}",
            registry::CHAIN_ID
        );
    }

    #[test]
    fn parse_addr20_roundtrips_registry_address() {
        let a = parse_addr20(registry::REGISTRY_ADDRESS).expect("valid registry addr");
        assert_eq!(a.len(), 20);
        // Case-insensitive, 0x-optional.
        assert_eq!(parse_addr20("0x00"), None); // wrong length
        assert!(parse_addr20(&"0".repeat(40)).is_some());
    }

    #[test]
    fn parse_interval_units_and_floor() {
        // Suffix units scale to seconds.
        assert_eq!(parse_interval("60s"), Ok(60));
        assert_eq!(parse_interval("5m"), Ok(300));
        assert_eq!(parse_interval("1h"), Ok(3600));
        assert_eq!(parse_interval("2h"), Ok(7200));
        // Bare number = seconds; case + whitespace tolerant.
        assert_eq!(parse_interval(" 90 "), Ok(90));
        assert_eq!(parse_interval("5M"), Ok(300));
        // Below the 60s minimum is rejected (the facet reverts on it).
        assert!(parse_interval("59s").is_err());
        assert!(parse_interval("0m").is_err());
        assert!(parse_interval("30").is_err());
        // Non-numeric / empty / overflow are errors, never a tx.
        assert!(parse_interval("abc").is_err());
        assert!(parse_interval("").is_err());
        assert!(parse_interval("m").is_err());
        assert!(parse_interval(&format!("{}h", u64::MAX)).is_err());
    }

    #[test]
    fn fmt_interval_compact() {
        assert_eq!(fmt_interval(60), "1m");
        assert_eq!(fmt_interval(300), "5m");
        assert_eq!(fmt_interval(3600), "1h");
        assert_eq!(fmt_interval(90), "90s");
        assert_eq!(fmt_interval(5400), "1h30m");
        assert_eq!(fmt_interval(0), "0s");
    }

    #[test]
    fn parse_schedule_args_full_and_defaults() {
        let p = parse_schedule_args(&args(&[
            "oracle", "check", "the", "price", "--every", "5m", "--budget", "1", "--runs", "50",
        ]))
        .unwrap();
        assert_eq!(p.target, "oracle");
        assert_eq!(p.task, "check the price"); // joined multi-word task
        assert_eq!(p.interval_secs, 300);
        assert_eq!(p.budget_wei, 1_000_000_000_000_000_000); // 1 $LH in wei
        assert_eq!(p.max_runs, 50);

        // --runs defaults; flags may precede the task; fractional budget.
        let p = parse_schedule_args(&args(&[
            "bot", "--every", "1h", "--budget", "0.5", "ping",
        ]))
        .unwrap();
        assert_eq!(p.target, "bot");
        assert_eq!(p.task, "ping");
        assert_eq!(p.interval_secs, 3600);
        assert_eq!(p.budget_wei, 500_000_000_000_000_000); // 0.5 $LH
        assert_eq!(p.max_runs, SCHEDULE_DEFAULT_RUNS);
    }

    #[test]
    fn parse_schedule_args_rejects_bad_input() {
        // Missing required flags.
        assert!(parse_schedule_args(&args(&["t", "task"])).is_err());
        assert!(parse_schedule_args(&args(&["t", "task", "--every", "5m"])).is_err());
        // No task (only the target positional).
        assert!(parse_schedule_args(&args(&["t", "--every", "5m", "--budget", "1"])).is_err());
        // Zero / non-numeric budget + bad runs.
        assert!(parse_schedule_args(&args(&["t", "x", "--every", "5m", "--budget", "0"])).is_err());
        assert!(parse_schedule_args(&args(&["t", "x", "--every", "5m", "--budget", "nope"])).is_err());
        assert!(
            parse_schedule_args(&args(&["t", "x", "--every", "5m", "--budget", "1", "--runs", "0"]))
                .is_err()
        );
        // Sub-minute interval bubbles up from parse_interval.
        assert!(parse_schedule_args(&args(&["t", "x", "--every", "10s", "--budget", "1"])).is_err());
    }

    #[test]
    fn format_job_row_contains_key_fields() {
        let job = registry::ScheduledJob {
            owner: "0xowner".into(),
            interval: 300,
            status: 0,
            next_run: 1_000 + 120, // 2m out from `now`
            budget_wei: 1_000_000_000_000_000_000,
            runs_left: 42,
            target_id: 7,
        };
        let row = format_job_row(3, "oracle", &job, "check\nthe price", 1_000);
        assert!(row.contains("#3"));
        assert!(row.contains("oracle"));
        assert!(row.contains("every 5m"));
        assert!(row.contains("next in 2m"));
        assert!(row.contains("runs-left 42"));
        assert!(row.contains("[active]"));
        assert!(row.contains("check the price")); // newline flattened
    }

    #[test]
    fn format_job_row_terminal_and_due() {
        // next_run == 0 (terminal) → em-dash; status label flows through.
        let job = registry::ScheduledJob {
            owner: "0x0".into(),
            interval: 60,
            status: 3,
            next_run: 0,
            budget_wei: 0,
            runs_left: 0,
            target_id: 1,
        };
        let row = format_job_row(1, "bot", &job, "", 5_000);
        assert!(row.contains("next —"));
        assert!(row.contains("[exhausted]"));
        // Due-now: next_run in the past.
        let mut due = job.clone();
        due.status = 0;
        due.next_run = 100;
        let row = format_job_row(2, "bot", &due, "", 5_000);
        assert!(row.contains("next due now"));
    }

    #[test]
    fn parse_ttl_units_and_bounds() {
        // Suffix units scale to seconds.
        assert_eq!(parse_ttl("1h"), Ok(3600));
        assert_eq!(parse_ttl("7d"), Ok(7 * 86_400));
        assert_eq!(parse_ttl("90d"), Ok(90 * 86_400));
        assert_eq!(parse_ttl("90m"), Ok(5400));
        // Bare number = seconds; case + whitespace tolerant.
        assert_eq!(parse_ttl(" 3600 "), Ok(3600));
        assert_eq!(parse_ttl("1H"), Ok(3600));
        assert_eq!(parse_ttl("2D"), Ok(2 * 86_400));
        // Below 1h is rejected; the exact 1h boundary is allowed.
        assert_eq!(parse_ttl("3600s"), Ok(3600));
        assert!(parse_ttl("59m").is_err());
        assert!(parse_ttl("3599").is_err());
        assert!(parse_ttl("0d").is_err());
        // Above 90d is rejected; the exact 90d boundary is allowed.
        assert!(parse_ttl("91d").is_err());
        assert!(parse_ttl("100d").is_err());
        // Non-numeric / empty / overflow are errors, never a tx.
        assert!(parse_ttl("abc").is_err());
        assert!(parse_ttl("").is_err());
        assert!(parse_ttl("d").is_err());
        assert!(parse_ttl(&format!("{}d", u64::MAX)).is_err());
    }

    #[test]
    fn fmt_ttl_compact() {
        assert_eq!(fmt_ttl(3600), "1h");
        assert_eq!(fmt_ttl(7 * 86_400), "7d");
        assert_eq!(fmt_ttl(90 * 86_400), "90d");
        assert_eq!(fmt_ttl(5400), "90m");
        assert_eq!(fmt_ttl(36 * 3600), "36h"); // 1.5d isn't a whole day → hours
    }

    #[test]
    fn gen_invite_code_is_link_safe_prefixed_and_unique() {
        let a = gen_invite_code("100");
        let b = gen_invite_code("100");
        // Shape: inv-<amount>-<10 chars>.
        assert!(a.starts_with("inv-100-"), "got {a}");
        let tail = a.strip_prefix("inv-100-").unwrap();
        assert_eq!(tail.len(), 10);
        // Link-safe: lowercase ASCII alnum only (no padding, no URL-reserved
        // chars), so `?invite=<code>` needs no escaping AND `bytes(code)` is
        // exactly what the facet keccaks.
        assert!(
            a.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-'),
            "non-link-safe char in {a}"
        );
        // CSPRNG tail → two codes (essentially) never collide.
        assert_ne!(a, b);
        // The amount label flows into the prefix verbatim.
        assert!(gen_invite_code("10.5").starts_with("inv-10.5-"));
    }

    #[test]
    fn invite_code_hash_matches_redeem_style_keccak() {
        // The CLI hashes the code the SAME way the facet's acceptInvite(string)
        // recomputes it: keccak256(bytes(code)). Empty-string vector pins it.
        let h = registry::invite_code_hash("");
        let hex: String = h.iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(
            hex,
            "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
        );
        // A generated code round-trips deterministically.
        let code = gen_invite_code("100");
        assert_eq!(registry::invite_code_hash(&code), registry::invite_code_hash(&code));
    }

    #[test]
    fn parse_invite_create_args_full_and_defaults() {
        // Full: explicit amount + ttl.
        let p = parse_invite_create_args(&args(&["--amount", "100", "--ttl", "30d"])).unwrap();
        assert_eq!(p.amount_label, "100");
        assert_eq!(p.amount_wei, 100 * 1_000_000_000_000_000_000);
        assert_eq!(p.ttl_secs, 30 * 86_400);
        // --ttl defaults to 7d; flags order-independent; fractional amount.
        let p = parse_invite_create_args(&args(&["--amount", "10.5"])).unwrap();
        assert_eq!(p.amount_wei, 10_500_000_000_000_000_000);
        assert_eq!(p.ttl_secs, INVITE_DEFAULT_TTL_SECS);
    }

    #[test]
    fn parse_invite_create_args_rejects_bad_input() {
        // Missing --amount.
        assert!(parse_invite_create_args(&args(&["--ttl", "7d"])).is_err());
        // Zero / non-numeric amount.
        assert!(parse_invite_create_args(&args(&["--amount", "0"])).is_err());
        assert!(parse_invite_create_args(&args(&["--amount", "nope"])).is_err());
        // Out-of-range ttl bubbles up from parse_ttl.
        assert!(parse_invite_create_args(&args(&["--amount", "10", "--ttl", "30m"])).is_err());
        assert!(parse_invite_create_args(&args(&["--amount", "10", "--ttl", "91d"])).is_err());
        // Unknown flag.
        assert!(parse_invite_create_args(&args(&["--amount", "10", "--bogus"])).is_err());
    }

    // ---- bounty arg parsing + row formatting --------------------------------

    #[test]
    fn parse_bounty_post_args_full_and_defaults() {
        // Full: multi-word task joins; explicit reward + ttl.
        let p = parse_bounty_post_args(&args(&[
            "audit", "my", "contract", "--reward", "5", "--ttl", "30d",
        ]))
        .unwrap();
        assert_eq!(p.task, "audit my contract"); // joined positional remainder
        assert_eq!(p.reward_wei, 5 * 1_000_000_000_000_000_000); // 5 $LH in wei
        assert_eq!(p.ttl_secs, 30 * 86_400);

        // --ttl defaults to 7d; flags may precede the task; fractional reward.
        let p = parse_bounty_post_args(&args(&["--reward", "0.5", "fix", "the", "bug"])).unwrap();
        assert_eq!(p.task, "fix the bug");
        assert_eq!(p.reward_wei, 500_000_000_000_000_000); // 0.5 $LH
        assert_eq!(p.ttl_secs, INVITE_DEFAULT_TTL_SECS);
    }

    #[test]
    fn parse_bounty_post_args_rejects_bad_input() {
        // No task.
        assert!(parse_bounty_post_args(&args(&["--reward", "5"])).is_err());
        // Missing --reward.
        assert!(parse_bounty_post_args(&args(&["do", "a", "thing"])).is_err());
        // Zero / non-numeric reward.
        assert!(parse_bounty_post_args(&args(&["task", "--reward", "0"])).is_err());
        assert!(parse_bounty_post_args(&args(&["task", "--reward", "nope"])).is_err());
        // Out-of-range ttl bubbles up from parse_ttl.
        assert!(parse_bounty_post_args(&args(&["task", "--reward", "5", "--ttl", "30m"])).is_err());
        assert!(parse_bounty_post_args(&args(&["task", "--reward", "5", "--ttl", "91d"])).is_err());
    }

    #[test]
    fn parse_bounty_id_accepts_hash_and_bare() {
        assert_eq!(parse_bounty_id("7"), Ok(7));
        assert_eq!(parse_bounty_id("#42"), Ok(42));
        assert_eq!(parse_bounty_id("  #3  "), Ok(3));
        assert!(parse_bounty_id("nope").is_err());
        assert!(parse_bounty_id("").is_err());
    }

    #[test]
    fn format_bounty_row_contains_key_fields() {
        let b = registry::Bounty {
            poster: "0xposter".into(),
            reward_wei: 5_000_000_000_000_000_000, // 5 $LH
            expiry: 1_000 + 300,                   // 5m out from `now`
            status: 0,
            claimant_token_id: 0,
        };
        let row = format_bounty_row(7, &b, "audit\nthe vault", 1_000);
        assert!(row.contains("#7"));
        assert!(row.contains("reward 5.00 LH"));
        assert!(row.contains("expires in 5m"));
        assert!(row.contains("[open]"));
        assert!(row.contains("audit the vault")); // newline flattened
    }

    #[test]
    fn format_bounty_row_expired_and_no_expiry() {
        let mut b = registry::Bounty {
            poster: "0x0".into(),
            reward_wei: 0,
            expiry: 0, // unset → em-dash
            status: 3, // paid
            claimant_token_id: 9,
        };
        let row = format_bounty_row(1, &b, "", 5_000);
        assert!(row.contains("expires —"));
        assert!(row.contains("[paid]"));
        // An expiry in the past reads EXPIRED.
        b.expiry = 100;
        b.status = 0;
        let row = format_bounty_row(2, &b, "", 5_000);
        assert!(row.contains("expires EXPIRED"));
    }
}