Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
How it works
How rust-anything checks a port, what its commands decide, and where its limits are. Back to the README.
How it works
profile ──> analyze ──> bridge ──> record ──> port.rs ──> diff ──> bench ──> shadow ──> gate
where the what to the Rust what the you or every faster? both side done means
time goes port first crate and original your agent recorded the by side in this passes
wrapper does write it case verdict production
The original stays the source of truth: record runs it on edge cases (and your own inputs) and
saves what it returns or throws; diff replays every case against the Rust; nothing ships until
they all match and gate passes. Callers keep the original API throughout.
A whole app goes through the same loop unit by unit, inside a frame that checks the whole program (Port a whole app):
analyze --whole-app ──> app record ──> app front-door ──> per unit: the loop above, then app wire ──> app lift
shape, every what the app Rust owns the gate passes, so the unit answers in pure Rust,
dependency, the does from the entry point; the Rust: replay 100%, fallback rate down checked by
decisions to make outside original answers replay
The loop
| Step | Command | What it does |
|---|---|---|
| All in one | rust-anything go --agent claude -- python3 app.py |
The hot-path loop end to end: profile, pick the outermost portable function (batched where profile says so), bridge it into rust/<function>-rs, record generated cases plus the calls the run makes, hand src/port.rs to the agent (claude, codex, or any command reading a prompt on stdin; without --agent it writes TASK.md and stops), then build, diff, gate and bench, and enable only when all pass and the port is not slower as its callers call it (otherwise it says where the speed is: the batch class to call from the loop, or the caller to port with it). Run it again after porting by hand: finished steps are kept |
| 0. Profile | rust-anything profile <repo> -- node bench.mjs |
Runs a real workload under the language's profiler (node, cProfile, go test pprof, JFR, a Ruby tracer): hot functions by inclusive time, their callers, and which loops to batch; flags code that is already compiled (numba, Cython, JAX), where Rust gains little, and time spent waiting (child processes, and in Python sleeps, sockets, locks, queues and thread joins), which porting does not shorten; it says how long the run was and warns when it is short, and a function under 5% of the run, or any function of a run under 100 ms, is not advised as "port it" |
| 1. Plan | rust-anything analyze <repo> |
Units, port order, risks with file:line, bridge per unit, dependency-to-crate fit, best first ports; --whole-app adds entry points and shape, every dependency (imported or declared) with its crate, pieces (units that import each other move together) and numbered decisions with a recommended answer |
| 2. Bridge | rust-anything bridge <repo> <unit> |
Crate with the bindings (lib.rs, plus the wrapper the source language loads) and stubs to port (port.rs); --batch fn:param adds a class that keeps many param values in Rust; --as-json T bridges a type parameter the app only fills with data as JSON values |
| 3. Record | rust-anything record <crate> |
Runs the original on generated edge cases (non-ASCII, emoji, -0, NaN, ints where floats are expected, ...) and on every semantic trap in every parameter (string length and case, signed division, overflow edges, float printing, map and sort order), and saves cases.jsonl; a string argument of an --inputs case that holds JSON, or base64 or base64url JSON, also gets cases with each inner value changed and encoded back the same way (dates in the shapes JS, Python and others parse, numbers, strings); --from-tests -- npx jest (or -- pytest) also records every call the original's own test suite makes; --float-tolerance 1e-9 lets floats match within that share for numeric code; --pin-clock (TS/JS with napi, Python) sets TZ=UTC for the original and the port and fixes the clock and random numbers during record and diff (Date.now(), new Date(), Math.random in JS; time.time(), time.time_ns(), datetime.now()/today(), datetime.utcnow(), date.today() and random in Python), and src/port/pinned.rs gives the port the same ones (pinned::now_ms(), pinned::now_secs(), pinned::random() for random.random(), and pinned::randbelow()/getrandbits() for randint, randrange, choice and shuffle). For TS/JS, Python, Ruby, Go, Java, Kotlin, PHP and C# functions it also keeps what each call did besides returning: the arguments after it (args_after, only when they changed) and what it wrote to standard output (stdout), marked "post": true (What a call is compared on) |
| 3. Build | rust-anything build <crate> |
Builds the Rust side: .node, wasm package, Python extension or shared library |
| 3. Diff | rust-anything diff <crate> |
Replays the recorded cases against Rust, called the way the original's callers call it; lists mismatches, each with where it first differs (return, throw or call N, the JSON path such as $.items[2].name, the kind of difference, and for text the character with a little context), and the distinct differences with how many cases each covers under a short stable id, so 40 failing cases from one bug read as one line; a thrown error matches on its class, and on its message too for a unit recorded with record --messages; for TS/JS, Python, Ruby, Go, Java, Kotlin, PHP and C# functions it also compares the arguments after the call and what it printed (the difference is located at arguments after the call or stdout); --redact prints all of it as shapes only (types, lengths and unsalted FNV-64 hashes, no values or arguments). That is not anonymisation: a hash of a short or guessable value (a small list, an id, a password) can be found by trying candidates, so read it before pasting it anywhere public |
| 3. Fuzz | rust-anything fuzz <crate> |
Fresh inputs from a new seed (--seed, --cases, --time) through the original and Rust, including recorded JSON and base64 JSON string arguments with random inner values; reports what the recording missed, and --keep adds those cases to it; --generator <command> takes each round's inputs from your own program instead (Fuzz with your own inputs) |
| 3. Bench | rust-anything bench <crate> |
Times the recorded cases on the original and on Rust, bridge included |
| 4. Shadow | rust-anything shadow <crate> |
Drop-in that runs both, returns the original's result, reports mismatches; RUST_ANYTHING_MODE=old|shadow|new. Not for PHP, C#, PowerShell and Swift: shadow refuses them and says what to do instead |
| 5. Gate | rust-anything gate <crate> |
fmt, clippy -D warnings, tests, unsafe audit, nothing unported, a recorded failing case for every error path of the original, no unwrap/expect/panic! where the original returns an error (unless marked // INFALLIBLE: <why>), build, API, behavior (no known-diffs.jsonl entry that no longer differs), held-out inputs (fresh ones from a new seed and recorded arguments with one change each, --held-out-cases N, 0 turns it off; see What gate refuses to count), a recording that is neither stale (the original or a file it imports changed since record) nor altered (a recorded case edited or removed; cases fuzz --keep appended are fine), nor missing its recorded-from.json (that fails closed), nor smaller than at the last passing gate, nor short of inputs record could not record, accepted diffs (known differences added since the last pass, or more than a tenth of the cases), runtime (the port runs, loads or links something outside itself), spawns (the port's own Rust starts another program), size (no more than 3x the original's lines plus 50, or the max a size decision allows the unit), and the cheat guard. It also reports coverage (how many of the original's lines the recorded cases ran, for TS/JS and Python), and only warns, without failing, about a missing or out-of-date Cargo.lock and about advisories from cargo deny or cargo audit when one is installed |
| Selftest | rust-anything selftest |
Checks the checking: plants wrong ports and tampers with a recording of a tiny built-in original in a scratch folder, and requires diff or gate to refuse each one and to pass a correct port; prints each planted bug and whether it was caught (Does the checking work?) |
| 6. Switch | rust-anything enable <crate> / disable <crate> |
Turns a gated TS/JS, Python or PowerShell port on for every caller, and off again byte for byte (Switch a port on and off) |
| 7. Report | rust-anything report <crate> |
report/REPORT.md and report/card.svg for a pull request: recorded cases matched, speedup from bench, fallback rate, on or off, the machine and its cores |
| Cache | rust-anything clean |
Removes the build folder every port and bridge shares (One build cache) |
| Agents | rust-anything setup |
Registers the MCP server (rust-anything mcp, every step as a tool) and the workflow skill (skills/rust-anything/SKILL.md) with your coding agents |
Fuzz with your own inputs
The built-in generator does not know a function's real input domain: dates in many formats, a
wire format, a config file. fuzz --generator <command> runs your command once per round, with
RUST_ANYTHING_SEED (the round's seed) and RUST_ANYTHING_CASES (--cases) set, and reads what
it prints as record --inputs reads a file: one {"fn": .., "args": [..]} line per call, with
kwargs and class lines too. Cases already in the recording are left out, and the rest are
recorded, diffed and kept (--keep) as the built-in generator's are. A generator that reads its
randomness from the seed replays with --seed. A non-zero exit, or a line that is not a valid
input, fails the run and names the line.
// gen.mjs
const seed = Number(process.env.RUST_ANYTHING_SEED)
const count = Number(process.env.RUST_ANYTHING_CASES)
for (let i = 0; i < count; i++) {
const day = new Date(Date.UTC(2000, 0, 1) + ((seed * 7919 + i * 104729) % 1e4) * 864e5)
console.log(JSON.stringify({ fn: 'parseDate', args: [day.toUTCString()] }))
}
rust-anything fuzz rust/parse-rs --generator "node gen.mjs" --seed 42 --keep
What a call is compared on
record and diff compare what a call gives back. For a TS/JS, Python, Ruby, Go, Java, Kotlin, PHP or C# function (not a method)
they also compare what it did besides returning:
- The arguments after the call.
recordserialises each decoded argument before the call and again after it, with the same lossless codec as results, and keeps the second copy asargs_afterwhen it differs from the first (a Python or Ruby call's keyword arguments askwargs_after).diffdoes the same to the port's arguments and compares the two. It is done whether the call returned or threw, since a function can change its argument before it fails. - What it printed to standard output, as
stdout:console.log,console.info,console.debugandprocess.stdout.writein TS/JS,printandsys.stdout.writein Python,puts,print,ppand$stdoutin Ruby (theSTDOUTconstant is not swapped, so a function that writes there stays in the original),fmt.Print*in Go (os.Stdoutis swapped for a pipe),System.outin Java and Kotlin (printlntoo),echo,print,printf,var_dumpandprint_rin PHP andConsole.Write*in C#. PHP and C# kept this asoutputbefore and still do. Standard error andprint(..., file=f)are not captured, so a function that writes there stays in the original (bridgesays why). - Every line
recordwrites for a function carries"post": true. A line without it comes from a recording made before this was kept, or fromrecord --from-tests' own capture:diffcompares such a case by return value only and says so (legacy recording: N of M cases hold no post-call state ...). Record again to compare both.
How a port does it. bridge gives a parameter the body changes in place a &mut type in
port.rs (xs: &mut Vec<f64>), and a function that prints an extra stdout: &mut String; the
port changes the first as the original does and writes what the original prints to the second.
The generated bindings hand both back to the caller in one answer: the wrapper (index.cjs, or
the package's __init__.py, or the Ruby wrapper) writes each changed argument into the caller's own list, object, map
or set (nested ones keep their identity where the shape did not change), prints stdout through
process.stdout or sys.stdout, then returns the result or raises the error. A function that
changes arguments is not sent over the binary wire, not batched, and not used as a method: those
paths answer with a result only. Which parameters are &mut is judged from the text of the
function; a miss is still caught, because diff compares the arguments after the call whatever the
signature says, and refresh reads the &mut you add to port.rs.
A port that prints with println! instead of writing to stdout writes to the real file
descriptor, which the capture does not see: the case shows stdout empty and fails.
What counts as a changed argument depends on the language: a Go slice or map, a Java or C# array
or collection, a PHP parameter taken by reference (array &$xs), a Ruby string, array or hash. A
value the language copies (a Go struct, a PHP array passed by value) is not one. PowerShell and
Swift still record the return value only (C records its out and buffer arguments back, but
its printed text cannot come back through the C ABI), so bridge keeps in the original every
export of those that returns nothing, prints or changes an argument. A language moves to the list above only with a test that plants a no-op port
of a mutator and a printer and expects diff to fail (src/lang/effects.rs, observes).
Hot paths: keep the data in Rust
A port called once per item pays the bridge once per item, and loses to a JIT. What wins is
moving the loop: profile finds it, and --batch generates a class that takes the items once
and runs the function over all of them per call, on all cores, with typed-array results.
rust-anything profile ../x18n -- node --experimental-strip-types $PWD/demo/x18n-search/search.ts .
# -> fuzzyScore: a quarter of the run, called per key by `matched`: batch it
rust-anything bridge ../x18n packages/core/src/fuzzy.ts --batch fuzzyScore:text
const search = new FuzzyScoreBatch(keys) // once
const order = search.rank(query, 0) // per keystroke: indexes, best first
A FuzzyScoreIndex struct in port.rs replaces the default loop with one that prepares the
items once, and can rank by itself (rank): it keeps the keys lowercased with a character mask
each, a table of each key's first position of every common character (a one-letter query is one
column), and the last query's matches (typing se after s rescores only what s matched). On
x18n's sidebar search over 50,000 keys, typed letter by letter, with identical results:
| Per query | vs TS | |
|---|---|---|
TS: map(fuzzyScore), filter, sort |
10 ms | 1x |
| TS with the same narrowing as the index | 4.1-5.4 ms | 2x |
| The same port, called per key | - | 0.2-0.4x |
FuzzyScoreBatch, default index (4 cores) |
5.1 ms | 1.7x |
FuzzyScoreBatch with FuzzyScoreIndex (napi, 4 cores) |
0.45-0.56 ms | 18-22x |
| The same with wasm (one thread) | 0.95 ms | 11.5x |
Against TS doing the same narrowing, Rust is still 7-12x faster (wasm 5x). Turn the returned
indexes into keys with a plain loop: Array.from(order, i => keys[i]) cost 20x more, 0.4 ms.
Every language except C, PHP, C#, PowerShell and Swift gets batches. Below, the Rust batch runs on 4 cores and the original on one thread, as the original code is written. Identical results and errors (benchmarks in each demo folder):
| Language | Workload | Original (1 thread) | Per-call port vs original | Batch (4 cores) vs original |
|---|---|---|---|---|
| TS | x18n search, 50,000 keys | 10 ms | 0.2-0.4x | 20x |
| Python | slugify, 20,000 strings |
98 ms | - | 17x |
| Ruby | slugify, 20,000 strings |
110 ms | - | 12.7x |
| Ruby | shellescape (stdlib), 50,000 mixed values |
88 ms | - | 11.8x |
Go and Java are left out: they can run the original on 4 threads just as easily, and measured
that way the Java original beats the Rust batch (#110). Batch crates allocate with
mimalloc: with the system allocator the Go batch was slower than one thread. bridge --allocator rusty_alloc opts into a pure-Rust allocator instead. Demo: demo/x18n-search.
Switch a port on and off
For PHP, C# and Swift, enable points to the generated wrapper and explains how to switch
manually.
Every way to switch, in one place:
| What | On | Off |
|---|---|---|
| A TS/JS, Python or PowerShell unit, in place | rust-anything enable <crate>: one marked block in each original file rebinds the ported functions to the Rust module, so every caller gets Rust and no import changes. It refuses while a recorded case differs (--force skips that check); go runs it only after diff and gate pass |
rust-anything disable <crate>: removes exactly the lines enable added, so the files are byte for byte what they were |
| That unit, for one run | (on by default once enabled) | RUST_ANYTHING_UNIT_<NAME>=original (<NAME> is the crate name without -rs, upper case: RUST_ANYTHING_UNIT_DEDUPE), or RUST_ANYTHING_MODE=old for every unit |
| A unit with a shadow module | Import it where the app imported the original; RUST_ANYTHING_MODE=new runs only Rust |
RUST_ANYTHING_MODE=old; the default, shadow, returns the original's result and compares Rust |
A unit wired into a front door (app wire) |
Wired units answer in Rust | RUST_ANYTHING_UNIT_<NAME>=original sends that unit's commands to the original |
An installed package (package) |
The platform's binary | RUST_ANYTHING_MODE=old runs the original it depends on |
The enable block names the crate by a path relative to the source file, so it holds no path
of your machine, and it falls back to the original when the module does not load (with
RUST_ANYTHING_MODE=new that is an error instead). record, diff, bench and fuzz set the
unit's switch to original for the original's side, so an enabled unit is still measured
against the original.
Every switch is logged. enable, disable, app wire, app lift and go (when it switches a
unit on) append a line to rust/audit.jsonl, and so does every gate, passed or failed: the time
in UTC, the command, the unit and crate, the functions switched, gate's check and case counts, the
rust-anything version and the repository's commit. An enable --force is marked "forced": true
(FORCED in rust-anything log), with the last diff it skipped past. The file is only appended to,
holds no user name, email or absolute path, and is meant to be committed with the port.
rust-anything log <repo> prints it (--json for the entries), and map shows each port's
last switch.
One build cache
Ports and bridges build into one cargo target folder: CARGO_TARGET_DIR when it is set, else
rust-anything/target in your cache folder (~/Library/Caches on macOS, $XDG_CACHE_HOME or
~/.cache on Linux, %LOCALAPPDATA% on Windows). napi-rs, PyO3, serde and the rest compile once
for every crate instead of once per crate. rust-anything clean removes the folder
(--dry-run prints its size; a folder named by CARGO_TARGET_DIR needs --force, since other
projects may build there).
Cargo names a crate's library after its package name alone, so two crates with one name would
replace each other's library in a shared folder (see docs/pitfalls.md). Each package name, and
each library name (foo-rs and foo_rs both build libfoo_rs), belongs to one crate folder
there (owners.json, written under owners.lock); another crate with the same package or library
name builds in its own target/ as before, and gets the name back once the first folder is gone.
A crate with a path dependency inside its own folder also builds in its own target/, since
cargo would share that dependency's build between crates laid out alike. Each crate's libraries
are copied to its own target/release, where every loader reads them, and only the kinds its
crate-type builds. Front doors (rust/app) keep their own target/, since every app's binary
would have the same name. rust-anything clean empties the shared folder under the owners lock
and keeps owners.json and owners.lock, so a build running at the time keeps its name.
What bridge decides
- Exports that cannot cross a bridge stay in the source language, with the reason, and the shadow
module re-exports the original. For TS:
functions that take or return functions, generators and iterators, RegExp,
instanceofchecks, generics (--as-json Tbridges one the app only fills with data), and values whose types (followed through imports, re-exports andextends) hold functions.--keep "name: reason"keeps more, e.g. code that depends onIntldata. - TS types map to Rust types, with type aliases resolved through imports and parameter types inferred from default values; structured values cross as a generated binary wire (JSON only as a fallback for shapes the wire does not model).
- JSON cannot express
undefined, NaN, Infinity, -0 or lone surrogates: structured values carry markers ({"$undefined": true},{"$num": "NaN"},{"$utf16": [...]}) that the generatedindex.cjstranslates, with helpers in the crate'sjs.rs.
record runs TS sources as they are: a Node resolve hook follows bundler-style imports
(./errors to ./errors.ts), --resolve-from supplies npm packages when the repo has none
installed, and TS that needs transforming (enums, parameter properties) is retried with
--experimental-transform-types.
What analyze looks at
Packages (
package.json) and source files; skipsnode_modules, build output, fixtures, playgrounds, tool configs. Vue/Svelte/Astro<script>blocks are parsed for imports.Units: a folder of source files, or a file at a package's source root.
Waves: a unit's imports come in earlier waves; import cycles are ported together.
Bridge: napi-rs when the unit or anything it imports needs Node; wasm-bindgen for portable code; keep in JS for UI and editor code.
Readiness (how safe) starts at 100 and subtracts, then clamps to 0–100:
Term Weight Each risk its severity weight (high 6, medium 3, low 1) × ln(1 + count), so one high risk costs 4.2Size lines / 40Fan-in 1.5per unit that imports it, at most 15Dependencies 12 per crate with no Rust fit, 4 per crate not in the table Tests +10 when a test file imports it directly; +4 when only its package has tests, counting a test in another package that imports this one by name Status is
readywhen readiness is 50 or more, the unit has no parse error and at most 25 places use high-severity risks (the logarithm above makes a hundred string slices cost little more than ten, so the count is checked on its own);cautionotherwise. Acautionunit is listed under start here only when fewer than three are ready, and then says so in its notes.Density: loops and string-offset operations per 100 lines, rounded to one decimal. It is reported, but the priority below uses loops only: a string-offset operation is a penalised risk and must not buy rank.
Priority is half readiness, half value, rounded to a whole number and clamped to 0–100, where value adds up to 100. It uses the readiness fraction before that is rounded for the report, so two units that both print 100 can still score differently:
Term Weight Compute loops per 100 lines × 4, at most 50Tests 30 when a test file imports it directly, 15 when only its package has tests Size lines / 4below 80, 20 from 80 up to (not including) 600, 10 at 600 and aboveStart here takes
readyunits with at least 20 lines and at least one bridgeable export, ordered by priority, then readiness (both highest first), wave (earliest first), density (highest first) and id, and keeps the first ten. When fewer than three qualify it picks again fromreadyandcautionunits. When that is still empty (no unit of 20 lines has a bridgeable export) it drops the size floor. So one unit crossing 20 lines can change the list.
Every risk below appears in plans as title xN with the lines that raised it; this table says how
bad it usually is and gives one example. The severities are the ones analyze scores with.
| Risk | Severity | Where it bites |
|---|---|---|
| String offsets and slicing | high | TS/JS slice, indexOf, matchAll; string indexing and slicing in Python, Ruby, PHP (substr, strpos), Java, Kotlin, C#, Go; C strlen, strcpy, sprintf: offsets counted in UTF-16 units, characters or bytes, not Rust's UTF-8 |
Regex features the regex crate lacks |
high | TS/JS, Python, Ruby, PHP, Java, Kotlin, C#, Go regexp, PowerShell -match/-replace: lookaround, backreferences, the y flag; in TS/JS, Python and Java also \d, \w, \s and \b (ASCII in JS, Unicode in the regex crate) |
| Regexes built at runtime | high | TS/JS, Python, Ruby, PHP, Java, C#, PowerShell: new RegExp(pattern), re.compile(s), a pattern that is not a literal |
| Dynamic code (eval, code built at runtime, computed import) | high | TS/JS eval, new Function, computed import(); Python exec, compile, __import__; Ruby eval, instance_exec; PHP eval, create_function; PowerShell Invoke-Expression, Add-Type |
| Dynamic typing | medium | TS/JS any, 'key' in value, == and !=; Python getattr, isinstance; Ruby method; PHP ==; Java instanceof and casts; Kotlin is/as; C# dynamic, is/as; Go interface{} and type switches; PowerShell $script:/$global: |
| Insertion-ordered maps and object keys | medium | TS/JS Map, Set, Object.keys, .sort() without a comparator (compares as UTF-16 strings); PHP arrays; Ruby hashes; PowerShell [ordered] dictionaries |
| Async and promises | medium | TS/JS Promise and async/await; Python async/await; C# async/await |
| Generators | medium | TS/JS function*; Python, Ruby and PHP yield; C# yield and LINQ queries |
| Class inheritance | medium | TS/JS, Python, Ruby, PHP, Java, Kotlin, C#, PowerShell classes: extends, base classes, mixins and traits |
| Reflection and prototypes | medium | TS/JS Proxy, Reflect, Symbol; Python globals/vars; Ruby send, is_a?; PHP variable variables; Java java.lang.reflect, getClass(); Kotlin ::class; C# System.Reflection; Go reflect; C function-like macros |
| Callback-shaped APIs | medium | TS/JS, Ruby, PHP, Java, Kotlin, C#, Go, PowerShell script blocks: function-typed parameters make a chatty bridge |
| Exceptions | low | all eleven: throw, raise, try, Go panic/recover/defer, C setjmp/longjmp/abort/exit/signal, PowerShell trap/Write-Error |
| Number semantics | low | TS/JS number, bitwise operators, Math.round, Math.sin/pow/exp/log and the other transcendental functions (last digit differs from libm), toFixed, toPrecision, toString(radix), parseInt/parseFloat (and Number.parseInt/Number.parseFloat); Python bitwise operators; PHP /; C# decimal |
| JSON round-trips | low | TS/JS JSON, Ruby, PHP, Go encoding/json, PowerShell ConvertTo-Json: key order, undefined, NaN |
| Integer width and overflow | medium | Python, Ruby and PHP ** and <<; Java, Kotlin, C# shifts, * and hash codes; Go and C shifts and conversions: wrap vs panic |
| Division and modulo | medium | Python // and % and Ruby integer / and % floor (div_euclid is not it for a negative divisor); Java, Kotlin, C#, Go, C integer / and % and PHP %, intdiv and fmod truncate like Rust, so a zero divisor and MIN / -1 are what is left; Python "..." % args is string formatting and not counted |
| Hash iteration order | high | Python set; Java and Kotlin HashMap/HashSet (also through import java.util.*), and Kotlin hashMapOf/hashSetOf; C# Dictionary/HashSet; Go map range (also over a variable declared as a map); PowerShell @{} hashtables |
| Pointers and manual memory | high | C pointers, malloc, memcpy; Go unsafe and pointer types; C# unsafe |
| Concurrency | medium | Go goroutines and sync, Java and Kotlin threads and synchronized, C# lock and System.Threading, Python, Ruby, PHP and C threads, PowerShell Start-ThreadJob |
| Null references | medium | Java, C#, PHP null; Kotlin nullable types; Go and Ruby nil; C NULL; PowerShell $null |
| Runtime changes to code | high | Ruby define_method and friends, Python Class.method = ..., PHP class_alias/runkit_*/uopz_* |
| Already compiled (numba, Cython, JAX) | medium | Python: decorated code that is not plain Python any more |
| numpy array parameters | high | Python: np.ndarray arguments and returns |
| Platform-specific C (asm, volatile, bitfields, packing) | high | C: asm, volatile, :3 bitfields, #pragma pack |
| Clock and random numbers | low | TS/JS Date.now/Math.random, Python time.time/random/os.urandom (also from time import time), Go time.Now/rand, Java System.currentTimeMillis, Java and Kotlin .shuffled()/.random()/Collections.shuffle, Ruby Time.now/.shuffle/.sample, PHP date/time/shuffle/array_rand/random_bytes, C# DateTime.Now, Swift Date()/.shuffled()/.randomElement(), PowerShell Get-Date/Get-Random/New-Guid: record --pin-clock covers TS/JS with the napi bridge and Python; elsewhere compare by hand |
| Implicit output and the pipeline | medium | PowerShell: Write-Output, echo and values left uncaptured go to the pipeline |
| Case-insensitive comparison | medium | PowerShell -eq, -like, -match, -contains and switch ignore case |
| Implicit type conversion | medium | PowerShell: casts such as [int]"abc", and / on integers giving a double |
| Intl and locale-aware strings | high | TS/JS Intl.*, localeCompare, toLocaleLowerCase, toLocaleString (and its Date and Time forms), normalize("NFC"): engine ICU data; ICU4X covers most, CJK word breaks differ |
| Date parsing | high | TS/JS Date.parse, new Date(string), new Date(y, m, d) and the local-time getters (getHours, getDay, getTimezoneOffset): V8's legacy formats and the machine's time zone; test with a date generator |
| Global and app state | medium | Java and Kotlin: a singleton's static accessor (LocaleManager.instance(), getInstance()), Java static fields that are not final: bridge keeps a function that reads them in the original |
| URL and encoding APIs | medium | TS/JS new URL, URLSearchParams, TextEncoder/TextDecoder, atob/btoa: the url crate follows the same standard |
Runtime traps (overflow, !, index out of range) |
medium | Swift: Int overflow, ! on nil, array index out of range, division by zero stop the program |
| Strings counted in grapheme clusters | medium | Swift: String.count, indices, prefix, reversed and == work on grapheme clusters and canonical equivalence |
| Double to text | low | Swift: \(x), String(x) and description of a Double: shortest digits, 1.0, 1e-05, inf |
| State outside the arguments (globals, environment) | medium | TS/JS module-level let assigned in a function and process.env; Python global, os.environ, os.getenv; Go, Java, Kotlin, Ruby, PHP, C#, PowerShell, Swift environment reads (os.Getenv, System.getenv, ENV, getenv, $env:, ProcessInfo): bridge keeps such an export in the original |
These are the same 36 titles analyze can emit, with the severities it scores them at;
src/risks.rs is the list, and tests/risks_doc.rs fails when this table and that list disagree.
What gate refuses to count
A port can pass diff without porting anything: answer the recorded cases from a table, run the
original for each answer, delete the tests that fail, or edit cases.jsonl until it agrees. gate
checks for each of these.
literals: string literals of 8 or more characters and numbers with 5 or more significant digits in the port's own files (not the bindings, not its#[cfg(test)]code) that equal a recorded argument or result, while the original's source never spells them out. One or two are named and pass; three or more fail, and so does any mention ofcases.jsonl,known-diffs.jsonlorrecorded-from.json. Powers of two and ten and the float limits are never counted. A constant the original really takes from a library stays with a// recorded-literal: <reason>comment on its line; a marker needs a reason, excuses at most two values (a table of results does not become a library constant by being marked), and every marker, like every// INFALLIBLE:, is counted in the gate output and the audit log.spawns: the port's own files (not the bindings, not its#[cfg(test)]code) do not start another program: nostd::process::CommandorCommand::new, no async process crate (tokio::process,async_process), no shell helper (duct,xshell,cmd_lib) and no libcsystem,forkorexec. A port that runsnodeorpython3on the original for each call passes every recorded case, sodiffcannot tell. Where the original starts a process itself (a function that runsgit), mark the line// SPAWNS: <why>; the mark counts only when the original's source starts processes too (child_process,subprocess,os/exec,ProcessBuilder, ...), so it cannot excuse a port of a pure function.runtimerefusesCommand::newandstd::process::Commandwhether marked or not, so the mark only matters for whatspawnsalone looks for. The check reads the port's Rust; a crate the port depends on can still start one, so read itsCargo.toml.tests: the crate's#[test]functions, assertions and#[ignore]s (insrc/andtests/) are saved to.rust-anything/tests.jsoneach timegatepasses. Fewer tests or assertions, or more ignored, fail the next run; when the change is intended, delete that file.recording:recordsaves the number of lines incases.jsonland their hash inrecorded-from.json, with how many inputs it generated and how many it could not record. A recorded line edited or removed fails; cases appended after them (fuzz --keep) are fine. A missing or unreadablerecorded-from.jsonfails too, so deleting it cannot switch the checks off; only a manifest that says"legacy_recording": trueskips it, and the verdict says so.diff,enable,report,goandmap --checkrun the same check, not onlygate.runtime: the port may not start a process (Command::new), load a library or embed the original at run time, include files from outside the crate or the recording files, or use abuild.rs: it would answer the recorded cases by running the original. The scan reads every.rsfile of the crate, hidden folders andlib.rsincluded, and thesrc/of each path dependency. A path dependency'sinclude_str!and#[path]are found from the file that names them, as rustc does, and may reach anywhere in that dependency's own crate, unless that crate holds the bridged crate or the original unit; it may never include the recording or a file in the original's language.accepted diffs:known-diffs.jsonlentries added since the last passing gate, or covering more than a tenth of the recorded cases, fail until you read them and pass--accept-known-diffs <N>.held-out:diffandgatereplay the recorded cases, so a port that memorised or approximated them passes. Afterbehaviorpasses,gateruns inputs the recording does not hold through the original and the port, with a seed taken from the clock on every run (printed, not saved;--held-out-seed Ndraws from a given one, to replay a failure):--held-out-cases Nfresh inputs per function (default 50, the generatorfuzzuses), and up to N per function made by changing one thing in a recorded call: one character of a string, the sign of a number, a boolean, two list items swapped, or one list element added or removed. Only arguments typed as strings, numbers, booleans and lists of those are changed; structured values, lists of them, byte buffers, encodedNaN/undefinedand strings typed as a union of literals ("fast" | "safe") stay as recorded, since changing their type or leaving the literals would be a different call. Fresh and perturbed inputs are also limited to calls the signature allows: an argument that is not a value of its parameter's declared TypeScript type (a non-array forentries: readonly Entry[], a list of things that are not entries) is left out, the verdict says how many, and a type the check cannot model accepts anything. The recorded cases that do that stay covered bydiff. A mismatch failsgateunder the same comparison rules asdiff(the saved float tolerance, key order andknown-diffs.jsonlapply), and the failing input with the shortest arguments is printed with what each side returned, the seed, how long the check took and the commands that replay the draw (gate --held-out-seed, andfuzz --seedfor the fresh half). A difference that aknown-diffs.jsonlentry explains (anint-beyond-i64entry for a Python function, say) does not fail the check, and the verdict says how many inputs it accepted. Nothing is added tocases.jsonl. If every generated input is already recorded, the check passes and says that nothing new was tried. If inputs were generated and none could be recorded (the original timed out on each, or its result could not be encoded), it fails. The port's run on them is stopped after twelve case timeouts (two minutes by default; a validRUST_ANYTHING_COMMAND_TIMEOUTreplaces that limit, as for every outside program), and a port that loops on an input fails the check instead of hanginggate.--held-out-cases 0turns it off, and the verdict says it is off in the check and in a note. It runs for TypeScript/JavaScript napi and Python PyO3 ports, the pathsfuzzis tested on end to end (tests/fuzz.rs,tests/held_out.rs); for every other language the verdict readsskipped: ...with the reason, and only the recorded cases were checked. It adds two driver runs to a gate (a few seconds for a small unit).
What loosens a verdict
Some flags make a green result weaker than an exact match. None is silent: the first line of
diff, gate, enable, report and the card (and comparison in --json and MCP results) is
comparison: exact or comparison loosened: with the float tolerance, ignored key order, the
number of known differences and the number of inputs record left out. A smaller recording and
enable --force are named in the recording check and the audit log instead.
Error messages are compared only for a unit recorded with record --messages (saved in
rust-anything.json and in recorded-from.json, which fails the recording if it is turned off
later by hand). Without it, when the recording holds errors, the next line of diff and gate
reads error messages not compared: N recorded errors checked by class only, and comparison
in --json carries messages and unchecked_messages. Go, C and Swift compare an error's text
always, so they print no such line. Under --messages the message is what the caller sees: for
Err("RangeError: text") the glue throws a RangeError whose message is text, and a Python
error is compared as its Type: message text.
| What | How | Why it needs asking |
|---|---|---|
| Floats match within a share | record --float-tolerance X or app record --float-tolerance X; above 1e-6 also --allow-large-tolerance |
A tolerance of 0.9 passes a port that is 50% off |
| Key order ignored | record --ignore-key-order |
Output that depends on order passes |
| Error messages not compared | the default; record --no-messages after --messages |
A port that throws the right class with the wrong message passes |
| Known differences | lines in known-diffs.jsonl; gate --accept-known-diffs N for new ones |
Every failing case could be listed as "known" |
Inputs record could not record |
record --allow-dropped N; gate --accept-dropped N |
A case whose result cannot be encoded (a byte-slicing trap) is not tested |
| A smaller recording | gate --accept-smaller-recording |
Re-recording fewer cases passes more easily |
Past enable's checks |
enable --force |
Printed and written to rust/audit.jsonl with each check it skipped |
| Few recorded cases | go --min-cases N (default 20 cases where the original did not throw) |
A thin recording proves little |
| No held-out inputs | gate --held-out-cases 0 |
A port that matches only the recorded cases passes |
| A larger port | a [[size]] decision in rust/obligations-decisions.toml with its ADR |
A port that re-implements what a crate provides, or handles cases one by one, passes size |
A larger port by decision
gate's size check fails a port longer than 3x the original's lines plus 50: past that, a port
usually re-implements what a crate provides. Some originals lean on a library no crate
reproduces: a Python unit that calls BeautifulSoup(html, "html.parser") has to rebuild
html.parser and bs4's tree builder to give the same tree on malformed HTML, and TASK.md allows
no new dependency. For such a unit a person can allow more, with a reason a reviewer reads. Write
an ADR in rust/DECISIONS.md that names the unit between backticks, then an entry that cites it
in rust/obligations-decisions.toml:
[[size]]
adr = "ADR-004"
date = "2026-12-02"
reason = "re-implements html.parser and the bs4 tree builder, which no crate reproduces"
unit = "src/scrape.py" # as the crate's rust-anything.json names it
max = 6 # times the original's lines, plus 50; more than 3
gate then passes size up to max, and says so: the detail ends with
allowed up to 6x by ADR-004: <reason>, and a note: line above the checks names the ADR and
the reason. A port over max times the original's lines plus 50 still fails. The file is read strictly, as for obligations waive: an ADR that is
missing or does not name the unit, a max of 3 or less, or an unknown key makes size fail, with
the fault, for a port over 3x. The last entry for a unit counts. No command writes it and the porting
agent must not: the skill and TASK.md leave it to the user.
Does the checking work?
Every claim above that diff or gate refuses something is a claim about code that can be
wrong in the quiet way: it keeps passing. rust-anything selftest tests the claims at the level
where the refusal happens. In a scratch folder under the system's temp directory (nothing of yours is read; it writes
only there and to the shared build cache, and the first build needs the same crates any bridged
port does), for each language whose toolchain is on
PATH (TS/JS needs node, Python needs python3; every other language is listed as not run
with the tool that is missing, or with "no built-in original yet"), it bridges and records a tiny
built-in original (shout, grade, half), plants one wrong port at a time, and asks diff and,
when diff passes, gate. A bug counts as caught only when the check meant to refuse it does:
a hard-coded table has to fail literals, not merely a build. It exits 1 when a planted bug gets
through, when the correct port is refused, or when a row ends in a way the table does not expect;
--strict also fails on a known gap, --only <id> runs one row, --json and the MCP tool
selftest return the same rows.
| Planted bug | Expected | Refused by (TS/JS and Python) |
|---|---|---|
| No-op port, always-throws port | caught | diff |
| The wrong error type | caught | diff (the recorded error's class is compared, DECISIONS L7) |
A hard-coded table of the recorded results, plain or with every line marked // recorded-literal: |
caught | gate: literals (a marker excuses at most two values) |
| A port that exits the process | caught | diff (the driver dies) |
A port that shells out to the original, with or without a // SPAWNS: mark (the original starts no process) |
caught | gate: runtime and spawns |
A port that includes cases.jsonl with include_str! |
caught | gate: literals and runtime |
recorded-from.json deleted, with the failing cases |
caught | gate: recording (and held-out) |
The failing cases deleted from cases.jsonl |
caught | gate: recording (and held-out) |
known-diffs.jsonl entries added for a wrong port's failures |
caught | gate: accepted diffs (and held-out in Python, where the fresh draw reaches the wrong branch too) |
The float tolerance raised after record |
caught | gate: recording |
| One correct port | passes | none of them |
| A port that prints extra output | known gap | nothing: a unit's diff compares printed text only as the stdout the port is handed when the original prints, not what it prints with println! |
| A port that differs only outside the recording | caught | gate: held-out (from a fixed seed in selftest), in TS/JS and in Python |
The failing cases and recorded-from.json deleted, the manifest marked "legacy_recording": true |
caught | gate: held-out finds the wrong port (the mark is the sanctioned way to use a recording made before fingerprints, and gate still says "legacy recording" in its notes) |
A known gap is listed, with its reason and the mitigation selftest checked, and does not fail
the run. When a gap closes or a catch is lost, the row ends as UNEXPECTED and
tests/selftest.rs, which runs this in CI on Linux and macOS, fails until the table is updated.
Measured on 2026-11-29, Linux x86_64, 4 cores of an Intel Xeon at 2.1 GHz, debug build, warm
build cache: TS/JS and Python together, 28 rows (19 caught, 7 known gaps, 2 correct ports passed),
2 minutes 20 seconds. The first run found three rows that were not caught: deleting
recorded-from.json, raising the tolerance and the shell-out port; each is closed by a gate
check now (recording, spawns, and runtime since). With the recording, error-class,
known-differences and runtime checks that came after, the same run on 2026-11-29 (macOS on an
Apple M4, 10 cores, debug build, warm build cache) has 34 rows: 26 caught, 6 known gaps, 2 correct
ports passed, in 1 minute 29 seconds. With the held-out check, on the same machine: 28 caught,
4 known gaps, 2 correct ports passed, in 1 minute 40 seconds. With the held-out check running
for Python PyO3 ports too, on 2026-12-01, Linux x86_64 (12 cores), debug build, warm build cache:
34 rows, 30 caught, 2 known gaps (a port that prints, in both languages), 2 correct ports passed,
in 5 minutes 8 seconds, most of it the 300 fresh inputs each held-out row now runs against both
languages.
Port rules
Corrections the user makes during a port ("dates print in local time", "an empty input prints
nothing") are kept in rust/RULES.md, committed with the port. rust-anything rules <repo>
lists them and rules <repo> --add "<rule>" appends one (an exact duplicate is skipped; a crate
folder stands for its repository). go puts them in TASK.md, and the MCP server's prompts and
instructions carry them, so every later unit and every agent keeps them.
What it can't catch
Passing means the Rust matches every case that was recorded, nothing more. What bites rewrites usually lives outside the recording, so know where the edges are:
- What a dependency calls.
spawnsreads the port's own Rust, andruntimeits path dependencies. A port that gets another crate to run the original, or loads it some way no pattern lists (a dynamic library, an embedded interpreter), is not seen; read the port's dependencies andsrc/before switching it on. - What a unit prints. A unit's
diffcompares what each function returns or throws and, in the languages listed under What a call is compared on, what it wrote to standard output. Standard error is not recorded, and a port that prints withprintln!instead of writing to itsstdoutis not seen when the original prints nothing (whole programs are:app recordcompares stdout, stderr and exit codes). - Inputs nobody recorded. The generated cases, the traps, the original's test suite
(
record --from-tests) and your own--inputsare the ceiling. Add real inputs (production samples, bug reports); the user input that breaks prod is rarely one a generator thinks of. Values inside a string argument (a date in JSON in base64url, as in a token) are varied only when a recorded case already holds such a string, and dates without a time zone (May 1, 21) only with--pin-clock, which fixes the time zone. - Arguments decoded inside the function. When a parameter goes into
JSON.parse,atob,Buffer.from(x, "base64" | "base64url" | "hex"),decodeURIComponentornew URLSearchParams, directly or through one local, generated strings can miss cases that depend on the decoded content. For example,new URLSearchParams(raw).get('a')accepts any string, but only a query with anaparameter exercises a lookup that finds a value.analyzenames the parameter and the call for each such function, andrecordlists them after its summary. Record real payloads with--inputs. TS/JS only; Python'sjson.loadsandbase64.b64decodeare not checked yet. - An original that moved on.
recordsaves a fingerprint of the unit's files (recorded-from.json); when the original changes later,diffwarns andgatefails until you record again, instead of passing against what the original used to do. - Regexes. The
regexcrate has no lookaround or backreferences, and even a pattern that compiles can treat\w,\b,\dand case-insensitive matching on non-ASCII text differently from JS, Python or Java. Swapping infancy-regexor rewriting the pattern can pass every recorded case and still differ on a Turkish dotlessıor a zero-width joiner.recordadds regex traps (those, the Kelvin sign, long s, Arabic-Indic digits, line separators, final sigma) to every function in a file that uses regexes, but fuzz your real patterns against real text too. - What changes between runs.
recordruns the original twice and sorts out what differed: changed values (times, ids) become wildcards; the same lines in another order (hash maps, concurrency) are compared in any order, so a port still has to produce exactly those lines; a different number of lines becomes..., which matches anything.recordlists each kind: look at every one, since a hash-order or concurrency difference is exactly what can change for real in a port. - Floats. Number-to-text formatting differs between languages (
1e21,-0, digit counts). The traps include those values, and they must match exactly;--float-toleranceforgives rounding only, never formatting. - Anything not in the output. Timing, memory and concurrency under load are not compared.
Side effects beyond stdout, stderr, exit codes, written files and HTTP responses are compared
only when you record them:
app record --effects http,smtpcatches outgoing HTTP calls and email, and--db-reset/--db-dumpthe database's state after each case (Side effects). HTTPS calls through the proxy show only the host, and anything the app reaches some other way (a message queue, signals) is still not compared. - Other platforms. A recording shows behavior on the machine that ran it. C whose results
depend on type sizes, endianness or the compiler can behave differently on the target;
analyzekeeps hardware-facing C in C for that reason.
What a real port takes
A small module is the loop above, once. A real application is not one command: it is many units
in an order, and most of the work is in behavior the original never wrote down. json-server
(report) took nine units, 514 recorded HTTP cases, two adapters, a
front door, two wiring steps and a hand-ported command line before lift gave one Rust binary.
What made it slow was not the Rust: it was tinyhttp re-running its routes after every next(),
V8's exact JSON error messages with UTF-16 positions, ICU collation in sort, and
/__proto__ reaching Object.prototype. Every one of those was found by a recorded case, not by
reading the code.
What helps:
- Expect milestones, not a switch. The front door starts at 100% fallback and every wired unit lowers it. A port that is half done still answers every case, through the original where Rust is missing, so it can ship at every step.
- Port the hot path first when speed is the goal (batches): most of the gain is often one loop.
- Give it real inputs. Generated cases find edge cases;
--inputswith real traffic or real files finds what users actually send. - Keep a map (
rust-anything map, below) so a long port can stop and resume, and so you can see what is left.
Keep the original's shape
A port keeps the original's units, names and public API: one crate per unit, the same exported
functions and classes, the same arguments and errors. The front door keeps the original's
commands and flags. That is what lets callers switch without changes, lets diff compare
function by function, and lets the original's maintainers read the Rust next to the code they
know. Change the design after the port matches, not during it.
Keep up with the original
The original keeps changing after a port starts. record saves a fingerprint of the unit's
files; when they change, diff reports a stale recording (and exits non-zero) and gate fails,
so an upstream change cannot pass silently.
rust-anything map shows the whole port at once: every unit of the original, the crate that
ports it, the functions in Rust and kept in the original, the cases and the last diff, the
whole app's glue (Rust only, or still handing cases to the original), the units not ported yet,
and every port whose original changed since it was recorded. map --write saves it as
rust/PORT_MAP.md; committed, it shows each upstream change as a diff. map --check exits 1
while any recording is stale, for CI: when an original changed since it was recorded, or when a
recording cannot be trusted (fingerprint missing, cases edited, removed or dropped).
After an upstream change: pull it, run map, and for each port marked changed run record
again, then diff. The new mismatches are exactly what changed upstream; port those.
For a whole CLI or server, app drift replays the original and the build against the recorded
cases and lists documented examples no case records; see
Keep up with the original for it and a GitHub Actions
workflow that runs it.