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
use rust_anything::walk::Canonical;
use std::io::Write as _;
use std::path::PathBuf;
use std::process::ExitCode;
/// `println!` that stops quietly when stdout is closed (`rust-anything ... | head`).
macro_rules! say {
($($arg:tt)*) => {{
let _ = writeln!(std::io::stdout().lock(), $($arg)*);
}};
}
macro_rules! say_raw {
($($arg:tt)*) => {{
let _ = write!(std::io::stdout().lock(), $($arg)*);
}};
}
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use rust_anything::{analyze, app, bridge, front_door, gate, harness, lift, mcp, report, shadow};
#[derive(Parser)]
#[command(
name = "rust-anything",
version,
about = "Rewrite TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C# or PowerShell apps in Rust, one verified piece at a time",
after_help = "Loop per unit: analyze -> bridge -> record -> port src/port.rs -> build -> diff -> shadow -> gate\nOnly the slow part: go --agent claude -- <workload>, then enable/disable and report"
)]
struct Cli {
#[command(subcommand)]
command: Cmd,
}
#[derive(Clone, Copy, ValueEnum)]
enum KindArg {
Napi,
Wasm,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum Profile {
/// Run on this machine.
Host,
/// Run on Android: the JNI library for the ABIs in `jniLibs/`, and on a connected device when
/// replaying.
Android,
}
#[derive(Subcommand)]
enum Cmd {
/// 1. Map a repository and write a ranked, ordered migration plan.
Analyze {
/// Repository root.
#[arg(default_value = ".")]
root: PathBuf,
/// Print the machine-readable report (schema `rust-anything/analyze@1`) instead of Markdown.
#[arg(long)]
json: bool,
/// Write to this file instead of stdout.
#[arg(long, short)]
out: Option<PathBuf>,
/// Source language; detected from the repository when omitted.
#[arg(long, value_enum)]
lang: Option<rust_anything::lang::Lang>,
/// Plan a whole-app port: entry points and shape, every dependency (imported or
/// declared) with its crate, pieces in port order, and decisions for the user.
#[arg(long)]
whole_app: bool,
},
/// 2. Scaffold a Rust crate with bindings for one unit.
Bridge {
/// Repository root.
root: PathBuf,
/// Unit id, as `analyze` lists it.
unit: String,
/// Bridge to generate; defaults to the plan's choice.
#[arg(long, value_enum)]
kind: Option<KindArg>,
/// Crate folder; defaults to `<root>/rust/<name>`.
#[arg(long, short)]
out: Option<PathBuf>,
/// Crate name; defaults to `<unit>-rs`.
#[arg(long)]
name: Option<String>,
/// Bridge a unit the plan marks blocked or keep.
#[arg(long)]
force: bool,
/// Keep an export in the original language: `name` or `"name: reason"`. Repeatable.
#[arg(long)]
keep: Vec<String>,
/// Add a batch class: `function:param` runs `function` over many `param` values kept in
/// Rust, on all cores (what `profile` recommends for leaves called in loops).
#[arg(long)]
batch: Vec<String>,
/// Bridge a type parameter as JSON values (`--as-json T`) when the app only fills it
/// with data, instead of keeping the generic export in TS. Repeatable.
#[arg(long, value_name = "TYPE_PARAM")]
as_json: Vec<String>,
/// Global allocator for crates with batches: `mimalloc` (C; wasm keeps Rust's default)
/// or `rusty_alloc` (pure Rust, no C compiler; wasm too). Kept in `rust-anything.json`.
#[arg(long, value_enum, default_value = "mimalloc")]
allocator: bridge::Allocator,
},
/// 2b. Regenerate the bindings (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in `port.rs`.
Refresh {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Add a batch class: `function:param` runs `function` over many `param` values kept in
/// Rust, on all cores. Repeat for more.
#[arg(long)]
batch: Vec<String>,
},
/// 3a. Record what the original's functions return on generated and given inputs.
Record {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Generated cases per function.
#[arg(long, default_value_t = 200)]
count: usize,
/// Extra cases: JSONL of `{"fn": name, "args": [...]}`, plus `"kwargs": {...}` for Python
/// and Ruby arguments passed by keyword.
#[arg(long)]
inputs: Option<PathBuf>,
/// Import the original from this JS module (e.g. built output) instead of the TS source.
#[arg(long)]
module: Option<PathBuf>,
/// Resolve npm packages from this folder's `node_modules` (when the repo has none installed).
#[arg(long)]
resolve_from: Option<PathBuf>,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
/// Floats match when they differ by at most this times the larger magnitude (absolute
/// below 1), e.g. 1e-9 for numeric code. Saved with the crate for diff and gate; 0 removes it.
#[arg(long)]
float_tolerance: Option<f64>,
/// Also record every call the original's own test suite makes to the unit's functions:
/// `--from-tests -- npx jest` (TS/JS, any runner) or `-- pytest` (Python).
#[arg(long)]
from_tests: bool,
/// The test command for `--from-tests`, after `--`; it runs in the original's folder.
#[arg(last = true)]
test_command: Vec<String>,
/// Target: this machine, or a connected Android device (for JVM crates).
#[arg(long, value_enum, default_value_t = Profile::Host)]
profile: Profile,
/// Android device serial; picked automatically when only one is connected.
#[arg(long)]
device: Option<String>,
/// Pin the clock and random numbers while recording and diffing (TS/JS with napi,
/// Python): `Date.now()`, `new Date()` and `Math.random` (`time.time`, `datetime.now`
/// and `random`) get fixed values, saved in `pinned.json`, and the port reads them from
/// `src/port/pinned.rs`. Kept for later runs until `--no-pin-clock`.
#[arg(long, conflicts_with = "no_pin_clock")]
pin_clock: bool,
/// Stop pinning the clock and random numbers.
#[arg(long)]
no_pin_clock: bool,
},
/// 3b. Build the crate's JS module (napi-rs `.node`, wasm-bindgen output) or, with
/// `--profile android`, the JNI library for Android ABIs into `jniLibs/`.
Build {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Target: this machine, or Android (needs the NDK and the Rust Android targets).
#[arg(long, value_enum, default_value_t = Profile::Host)]
profile: Profile,
/// Android ABI to build; repeatable. Defaults to arm64-v8a, armeabi-v7a and x86_64.
#[arg(long)]
abi: Vec<String>,
/// Android API level the libraries target (at least 26; defaults to 26).
#[arg(long)]
api: Option<u32>,
/// Android NDK root; found from ANDROID_NDK_HOME or the SDK when omitted.
#[arg(long)]
ndk: Option<PathBuf>,
/// Where to install the Android libraries; defaults to `<crate>/jniLibs`.
#[arg(long)]
jni_libs: Option<PathBuf>,
},
/// 3c. Replay recorded cases against the Rust module.
Diff {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Target: this machine, or a connected Android device (for JVM crates).
#[arg(long, value_enum, default_value_t = Profile::Host)]
profile: Profile,
/// Android device serial; picked automatically when only one is connected.
#[arg(long)]
device: Option<String>,
/// Android libraries folder to diff; defaults to `<crate>/jniLibs`.
#[arg(long)]
jni_libs: Option<PathBuf>,
/// Test this JS module instead of the crate's `index.cjs`.
#[arg(long)]
module: Option<PathBuf>,
/// Compare objects regardless of key order.
#[arg(long)]
ignore_key_order: bool,
/// Floats match within this tolerance for this run (the one saved by `record` otherwise).
#[arg(long)]
float_tolerance: Option<f64>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// 3d. Time the recorded cases on the original and on Rust, bridge included.
Bench {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Minimum measured time per function and side, in milliseconds.
#[arg(long, default_value_t = 200)]
min_ms: u64,
/// Resolve npm packages the original imports from this folder's `node_modules`.
#[arg(long)]
resolve_from: Option<PathBuf>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// 3e. Run fresh inputs from a new seed through the original and the port and report where
/// they differ: what the recorded cases did not cover.
Fuzz {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Fresh cases per function (and scenarios per class) in each round.
#[arg(long, default_value_t = 200)]
cases: usize,
/// Seed of the first round; random (and printed) when omitted. Later rounds count up.
#[arg(long)]
seed: Option<u64>,
/// Keep running new rounds until this many seconds have passed (one round otherwise).
#[arg(long, value_name = "SECS")]
time: Option<f64>,
/// Append the mismatching cases (`--keep`) or every fresh case (`--keep=all`) to
/// `cases.jsonl`, so the next diff and gate check them.
#[arg(long, value_enum, num_args = 0..=1, require_equals = true, default_missing_value = "mismatches")]
keep: Option<rust_anything::fuzz::Keep>,
/// Resolve npm packages the original imports from this folder's `node_modules`.
#[arg(long)]
resolve_from: Option<PathBuf>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// Run a real workload under the language's profiler and say what to port: hot functions,
/// their callers, and loops to batch. `rust-anything profile <repo> -- node bench.mjs` (also
/// `python3 x.py`, `go test -bench . ./pkg`, `java ...`, `ruby x.rb`)
Profile {
/// Repository root.
root: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Source language; detected from the repository when omitted.
#[arg(long, value_enum)]
lang: Option<rust_anything::lang::Lang>,
/// The workload, after `--`.
#[arg(last = true, required = true)]
command: Vec<String>,
},
/// The hot-path loop in one command: profile the workload, bridge the top portable function,
/// record it, hand the port to an agent, then build, diff and gate it, and switch it on only
/// when everything matches. `rust-anything go --agent claude -- python3 app.py`
Go {
/// Repository root, as `profile` takes it.
#[arg(value_name = "ROOT", conflicts_with = "root")]
path: Option<PathBuf>,
/// Repository root.
#[arg(long)]
root: Option<PathBuf>,
/// `claude`, `codex`, or any command that reads a prompt on stdin. Without it, `go` writes
/// the crate's TASK.md and stops; run it again once `src/port.rs` is ported.
#[arg(long)]
agent: Option<String>,
/// Port this function instead of the profile's pick.
#[arg(long)]
function: Option<String>,
/// Source language; detected from the repository when omitted.
#[arg(long, value_enum)]
lang: Option<rust_anything::lang::Lang>,
/// Generated cases per function, on top of the calls the workload makes.
#[arg(long, default_value_t = 200)]
count: usize,
/// Agent turns: the port, then one more per failing diff or gate.
#[arg(long, default_value_t = 3)]
rounds: usize,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// The workload, after `--`.
#[arg(last = true, required = true)]
command: Vec<String>,
},
/// Switch a ported unit on: one marked block in the original source files rebinds its
/// functions to the Rust module, for every caller (TS/JS and Python). `disable` removes it.
Enable {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Switch it on even when recorded cases differ.
#[arg(long)]
force: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Switch a unit off: removes exactly the lines `enable` added.
Disable {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Write a unit's result for a pull request or README: REPORT.md and card.svg with the
/// recorded cases matched, the speedup from bench, the fallback rate and the machine.
Report {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Output folder; defaults to `<crate>/report`.
#[arg(long, short, value_parser = absolute)]
out: Option<PathBuf>,
/// Minimum measured time per function and side, in milliseconds.
#[arg(long, default_value_t = 200)]
min_ms: u64,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// Remove the build cache every port and bridge shares (CARGO_TARGET_DIR when set, else
/// rust-anything/target in your cache folder). Ports rebuild on their next build.
Clean {
/// Only print the folder and its size.
#[arg(long)]
dry_run: bool,
/// Remove it even when CARGO_TARGET_DIR names it (other cargo projects may build there).
#[arg(long)]
force: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// 4. Generate a drop-in module that runs the original and Rust side by side.
Shadow {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Where to write the module; defaults to `<crate>/shadow/<name>.shadow.ts`.
#[arg(long, short)]
out: Option<PathBuf>,
},
/// 5. Check the definition of done for a port.
Gate {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// 6. Lay out installable packages and a CI workflow for every platform; never publishes.
Package {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Package name on npm or PyPI; defaults to the crate name.
#[arg(long)]
name: Option<String>,
/// Package version; defaults to the original package's.
#[arg(long)]
version: Option<String>,
/// Output folder; defaults to `<crate>/package`.
#[arg(long, value_parser = absolute)]
out: Option<PathBuf>,
/// napi: the module to load where no binary fits (defaults to the original file when it
/// imports nothing).
#[arg(long)]
fallback: Option<String>,
/// CLI front door: a command the package installs (repeat for more); defaults to the
/// package name without its scope.
#[arg(long = "bin")]
bin: Vec<String>,
/// CLI front door: the original npm package it falls back to, as <name>@<version>;
/// defaults to the one in the repository's node_modules.
#[arg(long)]
original: Option<String>,
/// List the files, write nothing.
#[arg(long)]
dry_run: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Record the whole app's behavior and replay any build against it (CLIs and servers).
App {
#[command(subcommand)]
command: AppCmd,
},
/// Serve every step as MCP tools over stdio.
Mcp,
/// Register rust-anything with your coding agents (Claude Code, Codex, Cursor, Gemini CLI,
/// OpenCode): the MCP server and, where the agent reads skills, the workflow skill. Keeps your
/// other settings; run it again any time.
Setup {
/// Agents to set up (repeatable); every agent found by default.
#[arg(long = "agent", value_enum)]
agents: Vec<rust_anything::setup::Agent>,
/// Take the rust-anything entries out again.
#[arg(long)]
remove: bool,
/// Show what would change, write nothing.
#[arg(long)]
dry_run: bool,
/// Change settings files in place without saving a `.rust-anything.bak` copy first.
#[arg(long)]
no_backup: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Map the port: every unit of the original, the crate that ports it, its cases and last
/// diff, the whole app's glue, and which recordings the original changed past since they
/// were made. Commit the map (`--write`) to see upstream changes in it.
Map {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Also look for crates in this folder (crates kept outside the repository).
#[arg(long = "crates")]
crates: Vec<PathBuf>,
/// Write the map to rust/PORT_MAP.md in the repository instead of printing it.
#[arg(long, conflicts_with = "json")]
write: bool,
/// Exit 1 when the original changed since any port was recorded.
#[arg(long)]
check: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Check the language runtimes, the agent setup and the MCP server, with the command that
/// fixes each problem. Exits 1 when something required is missing.
Doctor {
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum AppCmd {
/// Run the original CLI on cases (its own examples, `--inputs`, semantic traps), twice
/// each, and store them as trycmd files in `<repo>/rust/app-cases/`.
/// `rust-anything app record . -- python3 cli.py`
Record {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Extra cases: JSONL of `{"name", "args": [...], "stdin", "env": {...}, "files": {path: text}}`.
#[arg(long)]
inputs: Option<PathBuf>,
/// Normalizer: `timestamps`, `uuids`, `key-order`, or `name=regex` for your own. Repeatable;
/// saved with the cases.
#[arg(long)]
normalize: Vec<String>,
/// The name the app is invoked by in its docs (found from the command and manifests when omitted).
#[arg(long)]
name: Option<String>,
/// Leave out the semantic-trap inputs.
#[arg(long)]
no_traps: bool,
/// Seconds before a run is killed (default 30).
#[arg(long)]
timeout: Option<u64>,
/// The app is a server: the command starts it, taking its port from PORT or `{port}`;
/// cases are requests (curl lines in its docs, `--inputs`, traps), kept in `http/`.
#[arg(long)]
http: bool,
/// A port the server always listens on (implies --http).
#[arg(long)]
port: Option<u16>,
/// An argument every server start gets after its command, the original's and every
/// build's, so the Rust binary is started as the original is (`--arg db.json`).
/// Repeatable; implies --http; saved with the cases.
#[arg(long = "arg", value_name = "ARG", allow_hyphen_values = true)]
server_args: Vec<String>,
/// A file or folder of the repository the app reads or writes (a project tree, a
/// database file, a public folder): snapshotted into `files/` (`http/files/` for a
/// server) and copied into a fresh working directory before every case (CLIs) or start
/// (servers). A CLI's written files are what differs from it afterwards, and the files
/// it removed are compared too. Repeatable; saved with the cases.
#[arg(long)]
fresh: Vec<String>,
/// Milliseconds to wait after each response before the next request, for work a server
/// does after answering (a file watcher reloading what it just wrote). Implies --http;
/// saved with the cases and used by replay; 0 removes it.
#[arg(long, value_name = "MS")]
pace: Option<u64>,
/// Numbers in the output match when they differ by at most this times the larger
/// magnitude (absolute below 1), e.g. 1e-9 for numeric code. Saved with the cases; 0
/// removes it.
#[arg(long)]
float_tolerance: Option<f64>,
/// A written file of raw floats, compared value by value within --float-tolerance
/// instead of byte for byte: `PATH=f32le` or `PATH=f64le`. Repeatable; saved with the
/// cases.
#[arg(long = "float-file", value_name = "PATH=FORMAT")]
float_files: Vec<String>,
/// Record what leaves the process too: `http` runs a local sink that answers every
/// request (set as HTTP_PROXY, http_proxy and RUST_ANYTHING_HTTP_SINK), `smtp` a local
/// mail server (SMTP_HOST, SMTP_PORT). Each case stores what reached them, in order,
/// and replay compares it. Comma-separated or repeated. Saved with the cases.
#[arg(long, value_name = "KINDS")]
effects: Vec<String>,
/// Point one of the app's own settings at a sink: VAR=http-url, VAR=smtp-host,
/// VAR=smtp-port or VAR=smtp-url (e.g. WEBHOOK_URL=http-url). Implies that effect.
#[arg(long, value_name = "VAR=KIND")]
effect_env: Vec<String>,
/// A shell command run before each case (CLIs) or each start (servers) that resets the
/// database to a known state. Cases then run one at a time.
#[arg(long, value_name = "COMMAND")]
db_reset: Option<String>,
/// A shell command that prints the database's state (e.g. `sqlite3 app.db .dump`), run
/// after each case or request; its output is recorded with the effects.
#[arg(long, value_name = "COMMAND")]
db_dump: Option<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// The command that runs the original, after `--`; paths are relative to the repository.
/// Taken from the saved cases when omitted.
#[arg(last = true)]
run: Vec<String>,
},
/// Run a build against `<repo>/rust/app-cases/`, print passed/total, write a report with a
/// diff per failing case; exits non-zero on any mismatch.
Replay {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Command line of the build to test (the original, the front door, the final binary);
/// the original when omitted.
#[arg(long)]
build: Option<String>,
/// Seconds before a run is killed (default: the one saved by `app record`, 30 seconds
/// unless it was changed).
#[arg(long)]
timeout: Option<u64>,
/// Servers: the port the build always listens on; otherwise it gets a free one through
/// PORT and `{port}`.
#[arg(long)]
port: Option<u16>,
/// Replay only this case, by the name the report gives it (a library: only this unit).
/// The fast, repeatable loop for fixing one mismatch.
#[arg(long)]
case: Option<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Scaffold `<repo>/rust/app`, the Rust binary that owns the CLI's entry point: a clap parser
/// for the recorded commands and flags, every command running the original until a unit is
/// wired. Builds it and replays the cases (100% passed, 100% fallback).
FrontDoor {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Only write the files; skip the build and replay.
#[arg(long)]
no_check: bool,
/// Treat the repository as a library even if it has a `main`: the front door is a Rust
/// crate with the public API (found by default when there is no main and no server).
#[arg(long)]
library: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Hand commands to a unit's `port.rs` (after it passes gate): adds the crate to `rust/app`,
/// a glue file to write once, the routing and a kill switch
/// (`RUST_ANYTHING_UNIT_<NAME>=original`), then builds and replays.
Wire {
/// Repository root.
repo: PathBuf,
/// Unit crate: its folder, its name under `rust/`, or the unit id it was bridged from.
unit: String,
/// A command the unit answers. Repeatable; kept from the last wire when omitted.
#[arg(long = "command")]
commands: Vec<String>,
/// Servers: a route the unit answers, axum syntax (`GET /users/{id}`, `/path` for any
/// method, `*` for everything else). Repeatable; kept from the last wire when omitted.
#[arg(long = "route")]
routes: Vec<String>,
/// Do not run gate on the unit first (it just passed).
#[arg(long)]
skip_gate: bool,
/// Only write the files; skip the build and replay.
#[arg(long)]
no_check: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Make `rust/app` a pure Rust app, once replay passes with fallback rate 0 and every unit
/// passes gate: removes the fallback and the kill switches, turns the units into plain
/// libraries, runs the lift checklist and replays the pure binary. Checked on a copy first;
/// the original stays in place.
Lift {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
}
fn say_replay(replay: &app::ReplayOutcome) {
say!("{}/{} cases passed", replay.passed, replay.total);
if let Some(f) = &replay.fallback {
say!(
"Fallback rate: {:.1}% ({}/{})",
f.rate * 100.0,
f.cases,
f.total
);
}
for f in replay.failures.iter().take(20) {
let fields: Vec<&str> = f.problems.iter().map(|p| p.field.as_str()).collect();
say!("- {}: {}", f.case, fields.join(", "));
}
if replay.failures.len() > 20 {
say!("- ... and {} more", replay.failures.len() - 20);
}
say!("Report: {}", replay.report.display());
}
/// `n` and `word`, with an `s` unless `n` is one.
fn counted(n: usize, word: &str) -> String {
if n == 1 {
format!("1 {word}")
} else {
format!("{n} {word}s")
}
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e:#}");
ExitCode::from(2)
}
}
}
fn run() -> Result<ExitCode> {
match Cli::parse().command {
Cmd::Analyze {
root,
json,
out,
lang,
whole_app,
} => {
// Said here, not under "analyzing X", so the path is named once (#267).
if !root
.try_exists()
.with_context(|| format!("reading {}", root.display()))?
{
anyhow::bail!("no folder {}", root.display());
}
let lang = lang.unwrap_or_else(|| rust_anything::lang::Lang::detect(&root));
let mut report = analyze::analyze_lang(&root, lang)
.with_context(|| format!("analyzing {}", root.display()))?;
if whole_app {
report.whole_app = Some(rust_anything::whole_app::whole_app(&root, &report));
}
let text = if json {
serde_json::to_string_pretty(&report)? + "\n"
} else {
let title = root
.canonical()
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.unwrap_or_else(|| root.display().to_string());
report::markdown(&report, &title)
};
match out {
Some(path) => std::fs::write(&path, text)
.with_context(|| format!("writing {}", path.display()))?,
None => say_raw!("{text}"),
}
}
Cmd::Bridge {
root,
unit,
kind,
out,
name,
force,
keep,
batch,
as_json,
allocator,
} => {
let outcome = bridge::bridge(&bridge::Options {
root: &root,
unit: &unit,
kind: kind.map(|k| match k {
KindArg::Napi => bridge::Kind::Napi,
KindArg::Wasm => bridge::Kind::Wasm,
}),
out,
name,
force,
keep,
lang: None,
batch,
as_json,
allocator,
})?;
say!(
"Created {} ({:?}) for {}",
outcome.crate_dir.display(),
outcome.kind,
outcome.exports.join(", ")
);
for file in &outcome.files {
say!(" {file}");
}
for note in &outcome.notes {
say!("- {note}");
}
}
Cmd::Record {
crate_dir,
count,
inputs,
module,
resolve_from,
node_args,
float_tolerance,
from_tests,
test_command,
profile,
device,
pin_clock,
no_pin_clock,
} => {
anyhow::ensure!(
from_tests || test_command.is_empty(),
"a command after `--` is the test suite for `--from-tests`; add the flag"
);
let inputs = if from_tests {
let c = rust_anything::from_tests::capture(&crate_dir, &test_command)?;
say!(
"Captured {} call(s) from the tests{}:",
c.per_function.values().sum::<usize>(),
if c.tests_passed {
""
} else {
" (the test command failed; calls made before that are kept)"
}
);
for (name, n) in &c.per_function {
say!(" {name}: {n}");
}
for s in &c.skipped {
say!(" not captured: {s}");
}
Some(rust_anything::from_tests::with_own_inputs(
&crate_dir,
inputs.as_deref(),
&c.inputs,
)?)
} else {
inputs
};
if let Some(t) = float_tolerance {
let mut manifest = bridge::Manifest::load(&crate_dir)?;
manifest.float_tolerance = (rust_anything::tolerance::check(t)? > 0.0).then_some(t);
manifest.save(&crate_dir)?;
}
if (pin_clock || no_pin_clock)
&& let Some(helper) = rust_anything::pin::set(&crate_dir, pin_clock)?
{
say!(
"Wrote {}: add `mod pinned;` to port.rs and call `pinned::now_ms()` and \
`pinned::random()` where the original reads the clock or draws a number",
helper.display()
);
}
let opts = harness::RecordOptions {
crate_dir: &crate_dir,
count,
inputs: inputs.as_deref(),
module: module.as_deref(),
resolve_from: resolve_from.as_deref(),
node_args: &node_args,
};
let outcome = match profile {
Profile::Host => {
if device.is_some() {
anyhow::bail!("`--device` needs `--profile android`");
}
harness::record(&opts)?
}
Profile::Android => harness::record_android(&opts, device.as_deref())?,
};
say!(
"Recorded {} ({} threw) in {}",
counted(outcome.cases, "case"),
outcome.errors,
outcome.path.display()
);
for (name, n) in &outcome.per_function {
say!(" {name}: {n}");
}
if let Some(pin) = &outcome.pinned {
say!(
"Clock pinned at {} ms (UTC), random numbers from seed {} ({})",
pin.now_ms,
pin.seed,
rust_anything::pin::FILE
);
}
if !outcome.regex_functions.is_empty() {
say!(
"Regex traps (non-ASCII \\w, \\b and case folding) added for: {}",
outcome.regex_functions.join(", ")
);
}
if !outcome.timed_out.is_empty() {
say!(
"Left out {} input(s) the original ran too long on (over the per-case limit, \
RUST_ANYTHING_CASE_TIMEOUT seconds, 10 by default). The original does this \
itself, so the port need not match it there:",
outcome.timed_out.len()
);
for c in &outcome.timed_out {
say!(" {}({})", c["fn"].as_str().unwrap_or("?"), c["args"]);
}
}
if let Some(line) = outcome
.coverage
.as_ref()
.and_then(rust_anything::recording::coverage_line)
{
say!("Coverage: {line}");
}
}
Cmd::Refresh { crate_dir, batch } => {
let r = if batch.is_empty() {
bridge::refresh(&crate_dir)?
} else {
bridge::add_batches(&crate_dir, &batch)?
};
say!(
"Regenerated {} for {}",
r.files.join(", "),
r.functions.join(", ")
);
}
Cmd::Build {
crate_dir,
profile,
abi,
api,
ndk,
jni_libs,
} => match profile {
Profile::Host => {
if !abi.is_empty() || api.is_some() || jni_libs.is_some() || ndk.is_some() {
anyhow::bail!(
"`--abi`, `--api`, `--ndk` and `--jni-libs` need `--profile android`"
);
}
say!("Built {}", harness::build(&crate_dir)?.display());
}
Profile::Android => {
let report = harness::build_android(
&crate_dir,
&rust_anything::android::Options {
abis: abi,
api: api.unwrap_or(rust_anything::android::DEFAULT_API),
ndk,
out: jni_libs,
},
)?;
for library in &report.libraries {
say!(
"Built {} ({} JNI entry points checked, API {})",
library.path.display(),
library.entry_points,
report.api
);
}
}
},
Cmd::Diff {
crate_dir,
profile,
device,
jni_libs,
module,
ignore_key_order,
float_tolerance,
json,
node_args,
} => {
// The same missing-folder hint the other commands give before they
// read the manifest. Otherwise a missing crate reaches the harness
// and reports "run record first", which cannot work yet.
let manifest_path = crate_dir.join(rust_anything::bridge::MANIFEST);
if !manifest_path.exists() {
anyhow::bail!(
"reading {} (run `rust-anything bridge` first)",
manifest_path.display()
);
}
let opts = harness::DiffOptions {
crate_dir: &crate_dir,
module: module.as_deref(),
ignore_key_order,
node_args: &node_args,
float_tolerance,
};
let d = match profile {
Profile::Host => {
if device.is_some() || jni_libs.is_some() {
anyhow::bail!("`--device` and `--jni-libs` need `--profile android`");
}
harness::diff(&opts)?
}
Profile::Android => {
harness::diff_android(&opts, device.as_deref(), jni_libs.as_deref())?
}
};
let stale = rust_anything::bridge::Manifest::load(&crate_dir)
.ok()
.and_then(|m| rust_anything::recording::stale(&crate_dir, &m));
if json {
say!("{}", serde_json::to_string_pretty(&d)?);
} else {
if let Some(why) = &stale {
say!("Stale recording: {why}");
}
if d.accepted > 0 {
say!(
"{}/{} cases match ({} by {})",
d.passed,
d.total,
d.accepted,
rust_anything::recording::KNOWN_DIFFS
);
} else {
say!("{}/{} cases match", d.passed, d.total);
}
if let Some(t) = d.trend.as_ref().filter(|t| t.stalled) {
let shown: Vec<String> = t.passed.iter().map(ToString::to_string).collect();
say!(
"Stalled: the last {} changes to port.rs gained no matching case ({} of {}). \
Stop and look at the remaining mismatches with a person, or keep these \
functions in the original for now.",
rust_anything::recording::STALL_AFTER,
shown.join(", "),
t.total
);
}
for e in &d.stale_known {
say!(
"Known diff no longer happens, remove it from {}: {}({})",
rust_anything::recording::KNOWN_DIFFS,
e["fn"].as_str().unwrap_or_default(),
e["args"]
);
}
if !d.missing.is_empty() {
say!("Missing exports: {}", d.missing.join(", "));
}
for m in &d.mismatches {
say!(
"- {}({}): expected {}, got {}",
m["fn"].as_str().unwrap_or_default(),
m["args"]
.as_array()
.map(|a| a
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", "))
.unwrap_or_default(),
m["expected"],
m["actual"]
);
}
}
if d.failed > 0 || stale.is_some() {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Fuzz {
crate_dir,
cases,
seed,
time,
keep,
resolve_from,
json,
node_args,
} => {
// `--time 0` means "one round", so zero is a valid value here: the helper rejects it,
// and a value `Duration` cannot hold is an error rather than a panic.
let time = time
.map(|t| {
anyhow::ensure!(t.is_finite() && t >= 0.0, "`--time` takes seconds");
if t == 0.0 {
return Ok(std::time::Duration::ZERO);
}
rust_anything::process::seconds(t).context("`--time` is too large")
})
.transpose()?;
let f = rust_anything::fuzz::fuzz(&rust_anything::fuzz::FuzzOptions {
crate_dir: &crate_dir,
cases,
seed,
time,
keep,
resolve_from: resolve_from.as_deref(),
node_args: &node_args,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&f)?);
} else {
say!("Seed {} (replay with --seed {})", f.seed, f.seed);
say!(
"{}/{} fresh cases match ({} round{})",
f.passed,
f.cases,
f.rounds,
if f.rounds == 1 { "" } else { "s" }
);
if !f.missing.is_empty() {
say!("Missing exports: {}", f.missing.join(", "));
}
for m in &f.mismatches {
say!(
"- {}({}): expected {}, got {}",
m["fn"].as_str().unwrap_or_default(),
m["args"]
.as_array()
.map(|a| a
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", "))
.unwrap_or_default(),
m["expected"],
m["actual"]
);
}
if f.kept > 0 {
say!(
"Kept {} case(s) in {}: the next diff and gate check them",
f.kept,
f.recording.display()
);
}
}
if f.failed > 0 {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Bench {
crate_dir,
min_ms,
resolve_from,
json,
node_args,
} => {
let rows = harness::bench(&harness::BenchOptions {
crate_dir: &crate_dir,
min_ms,
resolve_from: resolve_from.as_deref(),
node_args: &node_args,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&rows)?);
} else {
say!(
"{:<24} {:>6} {:>12} {:>12} {:>9}",
"function",
"cases",
"orig ns/call",
"Rust ns/call",
"speedup"
);
for r in &rows {
say!(
"{:<24} {:>6} {:>12.0} {:>12.0} {:>8.2}x",
r.name,
r.cases,
r.original_ns,
r.rust_ns,
r.speedup
);
}
let lang = bridge::Manifest::load(&crate_dir)
.map(|m| m.language)
.unwrap_or_default();
let v = harness::verdict(&rows, lang);
say!(
"\nTimed as callers call it, crossing included. Overall {:.2}x (geometric mean); {} of {} functions at least 1.1x faster.",
v.speedup,
v.faster.len(),
rows.len()
);
say!("{}", v.advice);
}
}
Cmd::Profile {
root,
json,
lang,
command,
} => {
let report = rust_anything::profile::profile(&root, &command, lang)?;
if json {
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say!("{}", rust_anything::profile::markdown(&report));
}
}
Cmd::Go {
path,
root,
agent,
function,
lang,
count,
rounds,
json,
command,
} => {
let root = path.or(root).unwrap_or_else(|| PathBuf::from("."));
let outcome = rust_anything::go::go(&rust_anything::go::Options {
root: &root,
command: &command,
lang,
agent: agent.as_deref(),
function: function.as_deref(),
count,
rounds,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
for problem in &outcome.failed_checks {
say!("{problem}\n");
}
say!("{}", outcome.next);
}
use rust_anything::go::Stage;
return Ok(match outcome.stage {
Stage::On | Stage::Passed | Stage::WaitingForPort => ExitCode::SUCCESS,
Stage::Mismatch | Stage::GateFailed | Stage::Slower => ExitCode::FAILURE,
});
}
Cmd::Enable {
crate_dir,
force,
json,
} => {
if !force {
harness::build(&crate_dir)?;
let d = harness::diff(&harness::DiffOptions {
crate_dir: &crate_dir,
module: None,
ignore_key_order: false,
node_args: &[],
float_tolerance: None,
})?;
if d.failed > 0 || !d.missing.is_empty() {
anyhow::bail!(
"{}/{} recorded cases match; switch it on once they all do (`rust-anything diff` shows them), or pass --force",
d.passed,
d.total
);
}
}
let on = rust_anything::enable::enable(&crate_dir)?;
if json {
say!("{}", serde_json::to_string_pretty(&on)?);
} else {
say!(
"On: {} {} in Rust",
on.functions.join(", "),
if on.functions.len() == 1 {
"runs"
} else {
"run"
}
);
for f in &on.files {
say!(" {}", f.display());
}
for s in &on.skipped {
say!("- {s}");
}
say!(
"{}=original (or RUST_ANYTHING_MODE=old) runs the original for one run; `rust-anything disable {}` removes the block.",
on.switch,
crate_dir.display()
);
}
}
Cmd::Disable { crate_dir, json } => {
let off = rust_anything::enable::disable(&crate_dir)?;
if json {
say!("{}", serde_json::to_string_pretty(&off)?);
} else if off.files.is_empty() {
say!("{} was not on; nothing changed", off.crate_name);
} else {
say!(
"Off: {} {} in the original again",
off.functions.join(", "),
if off.functions.len() == 1 {
"runs"
} else {
"run"
}
);
for f in &off.files {
say!(" {}", f.display());
}
}
}
Cmd::Report {
crate_dir,
out,
min_ms,
json,
node_args,
} => {
let card = rust_anything::card::report(&rust_anything::card::Options {
crate_dir: &crate_dir,
out: out.as_deref(),
min_ms,
node_args: &node_args,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&card)?);
} else {
say_raw!("{}", rust_anything::card::markdown(&card));
say!(
"\nWrote {} and {}",
card.markdown.display(),
card.svg.display()
);
}
}
Cmd::Clean {
dry_run,
force,
json,
} => {
let c = rust_anything::cache::clean(dry_run, force)?;
if json {
say!("{}", serde_json::to_string_pretty(&c)?);
} else if c.removed {
say!(
"Removed {} ({})",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
} else if c.from_env && !dry_run {
say!(
"{} ({}) is CARGO_TARGET_DIR, which other cargo projects may share; pass --force to remove it",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
} else {
say!(
"{} ({})",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
}
}
Cmd::Shadow { crate_dir, out } => {
let outcome = shadow::shadow(&crate_dir, out.as_deref())?;
say!(
"Wrote {} ({})",
outcome.path.display(),
outcome.exports.join(", ")
);
if outcome.path.extension().is_some_and(|e| e == "java") {
say!(
"Call the <Class>Shadow classes in place of the originals; compile them with the originals and java/rust-anything. -Drust-anything.mode=old|shadow|new switches at runtime."
);
} else if outcome.path.extension().is_some_and(|e| e == "rb") {
say!(
"Require it after the original files. RUST_ANYTHING_MODE=old|shadow|new switches at runtime."
);
} else if outcome.path.extension().is_some_and(|e| e == "go") {
say!(
"Import it in place of the original package (require and replace both modules in go.mod). RUST_ANYTHING_MODE=old|shadow|new switches at runtime."
);
} else if outcome.path.extension().is_some_and(|e| e == "c") {
say!(
"Compile the original with the -D flags in shadow/flags.txt, build the crate with --features shadow, and link all three."
);
} else {
say!(
"Import it in place of the original. RUST_ANYTHING_MODE=old|shadow|new switches at runtime."
);
}
}
Cmd::Package {
crate_dir,
name,
version,
out,
fallback,
bin,
original,
dry_run,
json,
} => {
let outcome = rust_anything::package::package(&rust_anything::package::Options {
crate_dir: &crate_dir,
name,
version,
out,
dry_run,
fallback,
bin,
original,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"{} {} {}@{} in {}:",
if outcome.dry_run {
"Would write"
} else {
"Wrote"
},
outcome.files.len(),
outcome.name,
outcome.version,
outcome.out.display()
);
for file in &outcome.files {
say!(" {file}");
}
for note in &outcome.notes {
say!("{note}");
}
}
}
Cmd::Gate {
crate_dir,
json,
node_args,
} => {
let outcome = gate::gate(&crate_dir, &node_args)?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
for check in &outcome.checks {
let mark = if check.passed { "pass" } else { "FAIL" };
let first = check.detail.lines().next().unwrap_or_default();
say!("{mark} {:<10} {first}", check.name);
if !check.passed {
for line in check.detail.lines().skip(1) {
say!(" {line}");
}
if let Some(fix) = &check.fix {
say!(" fix: {fix}");
}
}
}
say!(
"{}",
if outcome.passed {
"Gate passed."
} else {
"Gate failed."
}
);
}
if !outcome.passed {
return Ok(ExitCode::FAILURE);
}
}
Cmd::App { command } => return run_app(command),
Cmd::Mcp => mcp::serve()?,
Cmd::Setup {
agents,
remove,
dry_run,
no_backup,
json,
} => {
let home = rust_anything::setup::home()?;
let command = std::env::current_exe()
.and_then(|p| p.canonical())
.context("finding the rust-anything executable")?;
let report = rust_anything::setup::setup(&rust_anything::setup::Options {
home: &home,
agents,
command,
remove,
dry_run,
backup: !no_backup,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
print!("{}", rust_anything::setup::text(&report));
}
}
Cmd::Map {
repo,
crates,
write,
check,
json,
} => {
let map = rust_anything::port_map::map(&repo, &crates)?;
if json {
say!("{}", serde_json::to_string_pretty(&map)?);
} else if write {
let path = map.root.join(rust_anything::port_map::MAP_FILE);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(&path, rust_anything::port_map::markdown(&map))?;
say!("Wrote {}", path.display());
} else {
say_raw!("{}", rust_anything::port_map::markdown(&map));
}
if check && map.changed() > 0 {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Doctor { json } => {
let report = rust_anything::doctor::run();
if json {
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say_raw!("{}", rust_anything::doctor::text(&report));
}
if !report.ok() {
return Ok(ExitCode::FAILURE);
}
}
}
Ok(ExitCode::SUCCESS)
}
fn run_app(command: AppCmd) -> Result<ExitCode> {
match command {
AppCmd::Record {
repo,
inputs,
normalize,
name,
no_traps,
timeout,
http,
port,
server_args,
fresh,
pace,
float_tolerance,
float_files,
effects,
effect_env,
db_reset,
db_dump,
json,
run,
} => {
let effects = rust_anything::effects::EffectsConfig::from_args(
&effects,
&effect_env,
db_reset.as_deref(),
db_dump.as_deref(),
)?;
let outcome = app::record(&app::RecordOptions {
repo: &repo,
run: &run,
inputs: inputs.as_deref(),
normalize: &normalize,
name: name.as_deref(),
traps: !no_traps,
timeout_secs: timeout,
http,
port,
server_args: &server_args,
fresh: &fresh,
pace_ms: pace,
float_tolerance,
float_files: &float_files,
effects,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
return Ok(ExitCode::SUCCESS);
}
say!(
"Recorded {} in {} ({} from examples, {} from inputs, {} traps)",
counted(outcome.cases, "case"),
outcome.dir.display(),
outcome.examples,
outcome.inputs,
outcome.traps
);
for (kind, what) in [
(
app::NoiseKind::Lines,
"Lines (a different number of lines between two runs; now `...`, which matches anything: check these first)",
),
(
app::NoiseKind::Order,
"Order (the same lines in another order between two runs; replay compares them in any order)",
),
(
app::NoiseKind::Values,
"Values (parts of lines differed between two runs; now `[..]` wildcards)",
),
] {
let hits: Vec<String> = outcome
.noise
.iter()
.filter(|n| n.kind == kind)
.map(|n| format!("{} ({})", n.case, n.field))
.collect();
if !hits.is_empty() {
say!("Noise, {what}: {}", hits.join(", "));
}
}
if !outcome.unstable.is_empty() {
say!(
"Unstable (exit code or files differed between runs; check them): {}",
outcome.unstable.join(", ")
);
}
if !outcome.timed_out.is_empty() {
say!("Timed out, not recorded: {}", outcome.timed_out.join(", "));
}
}
AppCmd::Replay {
repo,
build,
timeout,
port,
case,
json,
} => {
let outcome = app::replay(&app::ReplayOptions {
repo: &repo,
build: build.as_deref(),
timeout_secs: timeout,
port,
case: case.as_deref(),
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say_replay(&outcome);
}
if !outcome.failures.is_empty() {
return Ok(ExitCode::FAILURE);
}
}
AppCmd::FrontDoor {
repo,
no_check,
library,
json,
} => {
let outcome = front_door::front_door(&front_door::FrontDoorOptions {
repo: &repo,
library,
check: !no_check,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"Created {} ({} `{}`), {}",
outcome.dir.display(),
if outcome.api.is_empty() {
"binary"
} else {
"crate"
},
outcome.binary,
if !outcome.api.is_empty() {
format!(
"a library; public API: {}",
outcome
.api
.iter()
.map(|a| format!(
"{} ({})",
a.unit,
counted(a.exports.len(), "export")
))
.collect::<Vec<_>>()
.join(", ")
)
} else if !outcome.routes.is_empty() {
format!("requests recorded: {}", outcome.routes.join(", "))
} else if outcome.commands.is_empty() {
"commands: none (one root command)".to_string()
} else {
format!("commands: {}", outcome.commands.join(", "))
}
);
for file in &outcome.files {
say!(" {file}");
}
if let Some(replay) = &outcome.replay {
say_replay(replay);
}
if !outcome.api.is_empty() {
say!(
"Every export is still only in the original. After a unit's crate (from `bridge`) passes gate: rust-anything app wire {} <unit crate>",
repo.display()
);
} else if outcome.routes.is_empty() {
say!(
"Every command runs the original. After a unit passes gate: rust-anything app wire {} <unit> --command <name>",
repo.display()
);
} else {
say!(
"Every request goes to the original. After a unit passes gate: rust-anything app wire {} <unit> --route 'GET /path/{{param}}'",
repo.display()
);
}
}
if outcome
.replay
.as_ref()
.is_some_and(|r| !r.failures.is_empty())
{
return Ok(ExitCode::FAILURE);
}
}
AppCmd::Wire {
repo,
unit,
commands,
routes,
skip_gate,
no_check,
json,
} => {
let outcome = front_door::wire(&front_door::WireOptions {
repo: &repo,
unit: &unit,
commands: &commands,
routes: &routes,
skip_gate,
check: !no_check,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"Wired {} ({}) to {}; {}=original sends it back to the original",
outcome.unit,
outcome.crate_dir.display(),
if outcome.shadow.is_some() {
"the public API".to_string()
} else if outcome.routes.is_empty() {
outcome.commands.join(", ")
} else {
outcome.routes.join(", ")
},
outcome.switch
);
if let Some(shadow) = &outcome.shadow {
say!(
"The original package imports {} in place of the unit until the lift.",
shadow.display()
);
if shadow.extension().is_some_and(|e| e == "c") {
say!(
"C switches at build time: compile without the -D flags in shadow/flags.txt to send it back."
);
}
}
if outcome.glue_pending {
say!(
"Write the glue in {}, then run this again.",
outcome.glue.display()
);
}
if let Some(replay) = &outcome.replay {
say_replay(replay);
}
}
if outcome
.replay
.as_ref()
.is_some_and(|r| !r.failures.is_empty())
{
return Ok(ExitCode::FAILURE);
}
}
AppCmd::Lift { repo, json } => {
let outcome = lift::lift(&lift::LiftOptions { repo: &repo })?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
for item in &outcome.checklist {
let mark = match item.mark {
lift::Mark::Pass => "pass",
lift::Mark::Warn => "warn",
lift::Mark::Fail => "FAIL",
lift::Mark::Skip => "skip",
};
let mut lines = item.detail.lines();
say!(
"{mark} {:<24} {}",
item.name,
lines.next().unwrap_or_default()
);
if item.mark == lift::Mark::Fail {
for line in lines {
say!(" {line}");
}
}
}
if outcome.lifted {
say!(
"Lifted: {} is a pure Rust app ({}). Removed {} generated files; the original is untouched.",
repo.join(front_door::APP_DIR).display(),
outcome
.binary
.as_ref()
.map(|b| b.display().to_string())
.unwrap_or_default(),
outcome.removed.len()
);
} else {
say!("Not lifted:");
for b in &outcome.blockers {
say!("- {b}");
}
if let Some(stage) = &outcome.stage {
say!("The lifted copy is in {} for a look.", stage.display());
}
}
}
if !outcome.lifted {
return Ok(ExitCode::FAILURE);
}
}
}
Ok(ExitCode::SUCCESS)
}
/// A path argument made absolute: the tools run compilers and cargo from scratch folders, where
/// a relative crate path points nowhere.
fn absolute(arg: &str) -> Result<PathBuf, String> {
std::path::absolute(arg).map_err(|e| e.to_string())
}