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.
Gate, switch, reports and shadow: the cheat guard and everything that says "done" (audit id A2)
Scope and coverage ledger
Read in full, every line (Read tool, chunks of at most 500 lines):
| File | Lines | Read |
|---|---|---|
src/gate.rs |
1938 | 1-1938 |
src/audit.rs |
568 | 1-568 |
src/enable.rs |
871 | 1-871 |
src/report.rs |
387 | 1-387 (the analyze Markdown plan, not the report command) |
src/card.rs |
780 | 1-779 |
src/port_map.rs |
593 | 1-593 |
src/rules.rs |
138 | 1-138 |
src/library.rs |
470 | 1-470 |
src/shadow.rs |
611 | 1-611 |
src/app_shadow.rs |
423 | 1-423 |
src/risks.rs |
596 | 1-596 |
tests/audit.rs |
267 | 1-267 |
tests/card.rs |
242 | 1-242 |
tests/switch.rs |
617 | 1-617 |
Read only in part (said plainly, so nobody assumes more):
tests/port_map.rs lines 1-110 and the test names of the rest; tests/report.rs, tests/rules.rs,
tests/library.rs, tests/end_state.rs only as a list of test names (grep), not line by line.
These are tests of display strings and fixtures; no finding below depends on their unread parts.
Read outside my file list because the gate path runs through them: src/recording.rs 1-500,
src/error_paths.rs 1-330, src/walk.rs 1-175, src/harness.rs 60-120, 940-1180, 1265-1530, 2755-2830
(the Node diff driver), src/main.rs 1500-1630 (enable, disable, report commands),
src/lang/syntax.rs code_lines, tests/loop.rs 2600-2778 (the cheat-guard test), and the docs
how-it-works.md, DECISIONS.md, STATUS.md (rows for gate, enable, report, shadow, map).
Experiments (all in /tmp/claude-0/.../scratchpad/A2/, nothing built in the repo): I compiled copies of
scan_rust, significant_digits, well_known and strip_code lifted verbatim from src/gate.rs with
rustc, and a 20-line program over the ignore crate at the version rust-anything uses (0.4.34) and
serde_json. Python and Node were used to check claims in risks.rs.
Summary
- The cheat guard (
literals,tests,recording) is a set of textual heuristics, and each has a cheap bypass that I reproduced: negative numbers, hex, split or concatenated strings, one big table literal,.ignored or hidden files,#[cfg(test)]placed first, a deletedrecorded-from.json. Nothing ingateruns a held-out input through original and port, which is the one check a lookup-table or shell-out port cannot pass. Gate does not look for process spawns,include_*!,build.rs, path dependencies or proc macros either. - The recording can be weakened without any check noticing:
rm recorded-from.jsonswitches off both the stale and the tamper check without a row in the output; a re-record with one case passes; a function with zero recorded cases passesgateand is switched on byenable;known-diffs.jsonlhas no cap and turns every failing case into a "match". - The escape hatches (
// recorded-literal:,// INFALLIBLE:, "delete tests.json") are unchecked, are not counted anywhere, and the failure messages tell the agent how to use them. enableprints "On: f runs in Rust" and the card prints "Switched on: on" without any check that the Rust module loads or that callers reach it; the block falls back silently by design.- Reports: the SVG headline "Same result as the original on all N recorded cases" counts cases accepted
through
known-diffs.jsonl, hides a float tolerance and key-order setting, and says nothing about gate, a stale or edited recording. Empty benches print "1.0x faster". - Shadow:
shadowStats.callsand "no mismatches" exclude every call where the original throws, so the error paths are never shadowed.app shadownever compares side effects. risks.rsadvisesdiv_euclid/rem_euclidfor Python floor division; that is wrong for negative divisors.
By severity: CRITICAL 0, HIGH 7, MEDIUM 8, LOW 4.
Findings
A2-01 [H1][H4][H6] [HIGH] [CONFIRMED] Deleting recorded-from.json switches off the stale and tamper checks, silently
- Where:
src/recording.rs:302-313(stale),:319-333(cases_tampered),src/gate.rs:923-938. - What happens: both functions start with
read_to_string(RECORDED_FROM).ok()?andserde_json::from_str(..).ok()?; a missing or unparsable file, or one withoutcases/cases_hash/fingerprintkeys, returnsNone, whichgatereads as "nothing wrong" and pushes norecordingrow at all. The doc says the check fails when "a recorded line is edited or removed" and the original "changed since record". - Failing scenario: a port fails 40 of 900 cases. The agent runs
rm recorded-from.json, deletes the 40 lines fromcases.jsonl, and runsgate:behavior 860/860, norecordingrow,Gate passed.The map column "Original" then reads "not recorded", but nothing fails. (The agent can equally write a newrecorded-from.json: FNV-1a over the first n lines, no secret.) - Evidence:
let saved: Value = serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?; - Fix: in
gate, whencases.jsonlexists andrecorded-from.jsonis missing or has nocases_hash, failrecordingwith "recording cannot be verified: runrecordagain". Stronger and still cheap: comparecases.jsonlwith the committed one (git show HEAD:<path>, or the merge base in CI) and fail when recorded lines of the committed file are missing. Test: delete the file, delete a case, assert gate fails.
A2-02 [H1][H4] [HIGH] [CONFIRMED] A recording may shrink, and a function with no recorded case passes gate and enable
- Where:
src/gate.rs:857-1043(no check of case count or coverage floor),src/gate.rs:951-996,src/main.rs:1545-1556. - What happens: nothing ratchets the number of cases, the cases per exported function, or the coverage
(
coverageis alwayspassed: true,src/gate.rs:940-949).diffiterates over cases, so an export with zero cases is never looked at;apionly lists exports missing from the Rust module that have cases.tests/card.rs/issue #887 showsrecord --count 0 --inputs one.jsonlgives a crate with one case. - Failing scenario 1: the agent re-records with
--count 0 --inputs one.jsonl.recorded-from.jsonandcases.jsonlare consistent, so there is no tamper signal; gate printsbehavior 1/1.enable(no flags) switches on every export. - Failing scenario 2: an export whose generated inputs all timed out (
RecordOutcome.timed_out) or whose input type the generator cannot build has 0 cases; its port body can beDefault::default()andportedpasses (it only looks forunimplemented!,todo!and a barepanic!);enableswitches it on. - Fix: persist
casesand per-function case counts and the saved coverage in.rust-anything/tests.jsonand fail when they drop (an explicitgate --accept-smaller-recordingleaves an audit line); failbehaviorwhen an export has no recorded case (theenable --partialpath already refuses such functions:select_matchingsays "no recorded cases, kept in the original"; make the full path consistent). Test: re-record with one case and assert gate fails; remove all cases of one export and assertenablerefuses.
A2-03 [H1][H4][H2] [HIGH] [CONFIRMED] known-diffs.jsonl can turn every failing case into a pass, and the card calls that "same result"
- Where:
src/recording.rs:408-475(known_diffs,apply_known),src/gate.rs:735-754,src/card.rs:424-431. - What happens: an entry needs only
fn,args,actual(copied fromdiff --json) and any non-blankreason.apply_knownremoves the matching mismatches and adds them topassed. There is no cap, no share limit, and gate does not fail when entries were added in the same change asport.rs; it only appends "N entries added since the last passing gate" to a passing line (behavior_detail).enableandreportrun the samediff, so both treat the cases as matched. - Failing scenario: the port returns
Nonefor everything;diff --json | jqproduces 900 entries with the reason "intended"; gate:pass behavior 900/900 recorded cases match (900 by known-diffs.jsonl). The card SVG prints "Same result as the original on all 900 recorded cases: 12x faster"; only the Markdown carries an "Intended differences" table. - Evidence:
let all = card.matched == card.cases && card.cases > 0;withmatched: diff.passed. - Fix:
gatefails when accepted cases exceed a small share (say 1% or 10 cases) unless the audit log shows a human--accept-known-diffs N; always print accepted cases in the card SVG headline ("899 match, 1 accepted difference"); require each entry to carry the stable group iddiffprints. Test: 100% of cases accepted must fail gate.
A2-04 [H1][H4] [HIGH] [CONFIRMED] Files can be hidden from literals, size and the test count
- Where:
src/gate.rs:94-103(GENERATED),:199-208(port_files),:299-301(stop_at_tests),:110-123(files_underviawalk::builder),src/walk.rs:128-146. - What happens, four independent ways:
port_fileswalks with theignorecrate, so asrc/.ignorecontainingtable.rs(always honoured, no git needed), a hidden foldersrc/.d/, a.gitignored file, or a subfolder holding arust-anything.jsonis skipped. I confirmed withignore0.4.34: withsrc/.ignore=table.rs, the walk returned onlyport.rsandnested/n.rs;table.rsand.hid/t.rswere gone. Cargo still compiles them (mod table;).- Any file named like a generated one (
lib.rs,js.rs,wire.rs,utf16.rs,pinned.rs,pyconv.rs,pynum.rs,rbconv.rs) at any depth is skipped by file name.src/lib.rsis the bindings file the agent can edit freely; nothing compares it with whatbridgegenerates. scan_rust(text, true)stops at the first#[cfg(test)]and ignores everything after it. A#[cfg(test)] fn helper() {}at the top of a file hides the rest of the file. Tested: a three-entry table after#[cfg(test)]\nfn helper(){}flagged 0 literals. The honest-sloppy form is a#[cfg(test)] use ...;near the top.files_underonly returns.rs; data files,build.rs(crate root, outsidesrc/) andtests/-only helpers are never read byliteralsorsize.
- Failing scenario:
echo table.rs > src/.ignore, put 900matcharms insrc/table.rs: size, literals, tests all pass;unsafestill scans (it usesread_dir, not the walker). - Fix: walk with
standard_filters(false)(no ignore files, hidden included) and exclude onlytarget/; identify generated files by content or by comparing withbridge's output (or a// @generated by rust-anythingheader plus a hash), not by name; stop only at a#[cfg(test)]that is followed bymodand treat the rest of the file as code otherwise (or parse withsynand dropcfg(test)items). Test: the four forms above each with a three-entry table must failliterals.
A2-05 [H1][H4] [HIGH] [CONFIRMED] literals is bypassed by re-spelling the recorded values
Where:
src/gate.rs:272-463(scan_rust),:505-550(Recorded),:558-664(literals_check).What happens: a string is flagged only if the whole literal equals a recorded string of 8+ characters; a number only if its unsuffixed decimal spelling parses to the same bits as a recorded number. Reproduced with the real
scan_rust(results = "flagged / fails at 3"):Spelling of a recorded value Flagged "hello world one"yes ["hello"," world one"].concat(),format!("hello {}","world two"),"a".to_owned()+"b",concat!(..)no one literal "in1\tout1\nin2\tout2..."parsed at run timeno (never equals one recorded value) "\u{68}ello world one",b"hello world one"yes (unescaped), so fine -12345.678when the recorded value is-12345.678no: the sign is not part of the scanned number, the bits differ 0xDEADBEEF,f64::from_bits(0x40C8...)no: hex/octal/binary go to code, notnumbers12344.678 + 1.0,12345.0 + 0.678no "12345.678".parse()no 4_294_967_299u64yes (underscores and suffix stripped), so fine any value below 8 characters / 5 significant digits never recorded in the set ( MIN_STRING,MIN_DIGITS): a table of short results ("ok", small ints, booleans, enum names) is invisibleany literal the original text contains anywhere (also in a comment, or as a substring of a longer number) exempt ( original.contains)So every negative recorded number is unguarded, and a table of short results needs no encoding at all.
size(3x original lines + 50) is the only remaining limit, and one long string literal is one line.Failing scenario: a unit with an
isValid-style function returning short strings; the port is amatchover the 200 recorded inputs (inputs are not looked at at all:argsare recorded values too, but amatcharm needs them as literals, so many are short ints). Passes literals, size permitting.Fix: this guard cannot be made complete by scanning; see "Verification improvements" 1 (held-out inputs). As cheap extras: count negative literals (treat a leading
-as part of the number), scan hex/binary/octal numbers, compare the set of values of arrays/matches, flag any string literal over ~200 characters, and flagmatchor array tables with more than N arms in a function whose original has none.
A2-06 [H4][H6] [HIGH] [CONFIRMED] Nothing stops the port from running or reading the original at run time
- Where:
src/gate.rs(no such check anywhere; the onlyCommand::newcalls are cargo);src/gate.rs:1130-1210(rust_checks),:1264-1306(unsafe_blocks). - What happens:
gateneither looks forstd::process,Command,libloading,include_str!,include_bytes!,include!,std::fs/read_diron paths outside the crate, nor for abuild.rs,[build-dependencies],path/gitdependencies or proc-macro crates.RECORDING_FILESmatches the three file names only inside string literals (src/gate.rs:588), soread_dir(".")filtered by.jsonl,concat!("cases", ".jsonl")orcp cases.jsonl src/d.bin; include_bytes!("d.bin")pass. A port that doesCommand::new("node") .arg(original_script)passes diff (the original is on the machine), clippy, tests, literals (source strings of the original are exempt viain_original), size andunsafe. - Related:
liftandmapuse the text testcontains("original::")(src/lift.rs:766,776,src/port_map.rs:293), so glue that spawns the original withoutcrate::original::is "Rust only" in the map (the lift part is for the lift auditor to confirm). - Fix: (a) static denylist over every
.rsfile in the crate includingbuild.rs, plusCargo.toml: process spawning, dynamic loading,include_*!pointing outsidesrc/,env!("CARGO_MANIFEST_DIR"),[build-dependencies], non-registry dependencies,proc-macro = true; allowed only with a// ALLOW-<kind>: <reason>that gate prints and the audit log counts. (b) dynamic: run the behaviordiffonce with the original unit folder unreadable (rename it for the run) and PATH-less for the port process; a shell-out or file read of the original then fails. Test: a port that shells out tonode original.jsmust fail gate.
A2-07 [H4] [HIGH] [CONFIRMED] The escape hatches are unchecked, uncounted, and advertised in the failure text
- Where:
src/gate.rs:62-65, 302-313, 591(recorded-literal),src/error_paths.rs:184-217, 278(INFALLIBLE),src/gate.rs:66-69, 756-806(tests.json). - What happens:
// recorded-literal:(any text, even empty, anywhere in a//comment on the line of the literal) removes that line's literals fromfound. The check output never says how many literals were exempted. A table with one marked arm per line passes withno recorded values written into the port. Thefixtext of the failing check and theliteralsdetail both name the marker.// INFALLIBLE:is accepted anywhere on the line (also inside a string literal:line.contains(INFALLIBLE)) or in the comment block above; no reason required; thepanicsfailure text names it. It also only looks atsrc/port.rsand attributes a panic to the nearest precedingfnname, so a panic in a helper called by an erroring export is not attributed to it at all.tests: the failure text says "delete.rust-anything/tests.json"; the next gate saves the weaker baseline, and nothing records that the baseline was reset (the file is not in the audit log;rust/audit.jsonlonly has the check names).
- Failing scenario: gate says
FAIL literals 5 recorded values ...; the agent appends// recorded-literal: library constantto each line; gate passes. Same for deletingtests.jsonafter removing tests. - Fix: the gate output prints "N literals exempted by
// recorded-literal:" (and the audit entry stores N and the count of INFALLIBLE markers and baseline resets); exemptions require a reason of at least a few words and the exempted value must occur in a dependency's source or docs (cheap approximation: fail when more than 2 lines carry the marker); the baseline file is committed and gate compares with the committed version (git show HEAD:...) so a deletion shows up in the diff. Test: 5 marked lines must produce a visible warning.
A2-08 [H2][H6] [MEDIUM] [CONFIRMED] enable says the Rust is on without checking that anything loads or is reached
- Where:
src/enable.rs:475-550(js_block,python_block),:154-193(declared/swap),src/main.rs:1566-1588,src/card.rs:135, 259-265. - What happens: (1) by design the block falls back to the original on any load error (
catch (e) { if MODE === 'new' throw };except ImportError: ... return), also whenp.getBuiltinModuleis missing on an older Node (TypeError inside thetry).enablenever loads the module, and prints "On: f runs in Rust". The card's "Switched on: on" isis_enabled= "the marker block exists in a file". (2) The Python block is inserted before the__main__guard or at the end, so references taken earlier at import time (HANDLERS = {"f": f},@app.routeregistrations,functools.partial(f), default arguments) keep the original function. (3) Exports thatdeclared()cannot rebind (aconstarrow) are listed inSwitched.skippedon the terminal only; REPORT.md and the card show "Switched on: on", "Fallback ... 0.0%" and a speedup from a bench that calls the Rust module directly. (4) A line-startfunction f(inside a template literal or docstring satisfiesdeclared(regex over raw text) for a name that is really aconst; the block then assigns to a constant at import (WEAK, not reproduced). - Failing scenario: the deployment ships
src/withoutrust/<crate>/index.cjs(or a.nodebuilt for another Node ABI): every call silently runs the original, audit saysswitched on, 900 cases match, the card says "Switched on: on, 12x faster". - Fix: after writing the block, probe it in a subprocess: import the original module and assert, for each
switched function, that it is the native function (JS:
u.f === native.f; Python:module.f is native.f), and print the result; storeskippedin the audit entry and the card; make the block log once to stderr when it falls back (the shadow module already does). Test: enable with a missingindex.cjsmust report "not loaded".
A2-09 [H2] [MEDIUM] [CONFIRMED] Report card claims more than it measured
- Where:
src/card.rs:86-157, 259-265, 394-500,src/harness.rs:971-1041. - What happens:
matchedincludes cases accepted throughknown-diffs.jsonl; the SVG headline says "Same result as the original on all N recorded cases" (A2-03).diffis called withfloat_tolerance: Noneandignore_key_order: false, whichsettle()replaces with the values saved inrust-anything.json(an editable file;tolerance::checkallows anything below 1;nearis|e-a| <= tol * max(|e|,|a|,1), absolute below 1). Neither card nor gate prints that a tolerance or key-order setting was in force.- Nothing says whether gate passed, whether the recording is stale, edited or tiny; REPORT.md/SVG can be produced for a port that fails gate.
verdict()returnsspeedup = 1.0for an empty row list andnothing_timed()requires a non-empty list, so a unit whose benched functions all produced no timings prints "Speedup ... 1.0x" and "1.0x faster" whileadvicesays "Nothing to compare".- The headline speedup is the geometric mean of per-function ratios, while the two big numbers on the card are
sums of per-call times across functions (
orig,rustfolds); with several functions the bars can read "1.1 ms vs 1.0 ms" next to "31x faster". The label "per call" hides that these are sums over functions. cases_per_functioncounts only"fn"cases (case["fn"].as_str()), butdiff.missingalso names missing classes (the Node driver pushesc.class), so a missing class' cases are not infallback_casesand the card prints a lower fallback share (0.0% when only a class is missing).machine()printsavailable_parallelism(cgroup/affinity aware) as "cores".
- Fix: add to REPORT.md and the SVG footer: gate result and date, "N accepted by known-diffs", "float tolerance X /
key order ignored", recording age/stale flag, number of cases and cases per function; compute the speedup
line from the same quantity the bars show (or show both); use
case["fn"].or(case["class"]); treat empty bench as "nothing to compare". Test: a card for a unit with oneknown-diffsentry must not say "Same result ... all".
A2-10 [H2] [MEDIUM] [CONFIRMED] The error cases check claims more than it checks
- Where:
src/error_paths.rs:112-171, 221-256,src/gate.rs:86-87,docs/how-it-works.mdrow "Gate". - What happens: the doc says "a recorded failing case for every error path of the original". The code finds
one line per export (the first
throw/raisein the function's own body, found by a brace counter that treats only"and`as quotes, so'}'or regex literals can end the body early) and requires **one** failing case per export. Exports that fail through a helper (assertValid(x)), Kotlinrequire/check/error, Rubyfail, Pythonassert, PowerShellWrite-Error -ErrorAction Stop, implicit runtime errors, and every C function (Lang::C => None) are "found nowhere", and the detail then reads "the original fails on purpose nowhere", a false sentence for those. - Fix: say "at least one failing case for each function that contains
throw/raise" in docs and detail; add the other spellings; when the check cannot analyse a language (C) printnot checked, not "nowhere". Test: Kotlinrequire(x > 0)must be listed.
A2-11 [H6][H1] [MEDIUM] [CONFIRMED] Shadow modes skip the error paths and the side effects, so "no mismatches" is narrower than it reads
- Where:
src/shadow.rs:218-249, 440-446, 477-480(TS/Pythoncall,check, class#call),src/app_shadow.rs:243-285. - What happens:
const expected = legacy(...args)runs outside any try; if the original throws the exception propagates, Rust is never run,shadowStats.callsis not incremented and nothing is compared (same for a rejected promise and for Python). Validation failures are the likeliest place for a port to differ, and they are exactly the calls that never reachcompare. Other gaps: if the Rust module does not load, the shadow warns once and thencallsstays 0 whilemismatchesstays 0; only the first 10 mismatches are reported andshadowStatsis not exposed unless the app reads it; a Rust abort, stack overflow or infinite loop in the second call still takes the process down (DECISIONS L9 says Rust errors never reach callers).app shadow: the build's effects are drained and discarded (build.drain_effects), the original's effects are not captured, so e-mails, webhooks and DB rows are never compared; an upstream error is answered 502 and counted inrequestsbut neithermatchednormismatches; headers present only in the build are not looked at (only the original's headers are iterated);--keepwrites each mismatching request includingAuthorizationand cookies toshadow/inputs.jsonl(onlyhostis removed) although the module comment says "Mismatches are logged as shapes, never values". - Fix: wrap the original in try/catch, run native, compare error vs error by type and message, count them in
shadowStats.errorsandcalls; exposeshadowStats.skipped/native_loaded; print a summary line at exit ("N calls, M compared, K original threw, mismatches X"); inapp shadowprintrequests = matched + mismatches + upstream_errors, compare the effect sinks of both sides, and stripauthorization,cookieandset-cookiebefore--keep. Test: a port that returns instead of throwing on bad input must show a mismatch in shadow.
A2-12 [H1] [MEDIUM] [CONFIRMED] The stale-recording check only fingerprints the unit's own files
- Where:
src/recording.rs:21-58(fingerprint),docs/how-it-works.md"Keep up with the original". - What happens: for a single-file unit only that file is hashed; for a folder only that folder. Repository files the
unit imports (which
gate's ownsizeand coverage include throughwith_local_imports) are not. The docs say "when they change,diffreports a stale recording ... so an upstream change cannot pass silently". - Failing scenario:
util.tsimports./helpers.ts; upstream changeshelpers.ts;mapsays "unchanged", gate has norecordingfailure. - Fix: hash the import closure (reuse
with_local_importsfor TS,called_implementationsfor C, the language plugins' import walkers elsewhere); until then, say "the unit's files" in the docs sentence about upstream changes. Test: change an imported helper, expect "changed since it was recorded".
A2-13 [H2] [MEDIUM] [CONFIRMED] Coverage excludes files that never ran and files Node transformed
- Where:
src/recording.rs:164-271(node_coverage:if !seen { continue; },if transformed { continue; }),src/gate.rs:940-949. - What happens: a file that was never loaded in any record run, or that Node transformed (enums, parameter
properties, retried with
--experimental-transform-types), is dropped from both numerator and denominator. "the recorded cases ran 100% of the original's N lines" can then be true while a whole file never ran. Lines count as reached when any character of the line ran, so a branch on the same line counts. The gate row is alwayspassed: true; other languages print no row, so the absence is not visible either. - Fix: list files excluded and why ("file X never loaded: 0 of N lines") and count never-loaded files as 0% reached; print "not measured for " explicitly in gate. Test: unit with two files, one never imported by the exports, expect coverage below 100%.
A2-14 [H2] [MEDIUM] [CONFIRMED] map counts a bridge stub as "has a Rust port", and shows a Last diff that may belong to another port
- Where:
src/port_map.rs:102-172, 233-266, 322-352, 403-420,src/recording.rs:385-392,src/audit.rs:250-254. - What happens: any crate folder with a manifest is a port, including a fresh
bridgewith every functionunimplemented!, zero cases and no gate (tests/port_map.rsasserts exactly this: one port,cases == 0). The headline reads "N of M units have a Rust port", and "Every unitanalyzefound has a port." appears when all are stubs.last_diffis the last line ofdiff-history.jsonl; it stores a hash ofport.rsbutlast_diffnever compares it with the current file, so a port edited after its last diff still shows "10/10". The same value goes into the audit entry ofenable --force, printed as "FORCED, last diff 10/10", although the forced switch was typically made precisely because the current port had not been diffed. Glue is "Rust only" if the file does not contain the textoriginal::. - Fix: count only ports with
portedpassing, cases > 0 and a recorded diff for the currentport.rshash;last_diffreturnsNone(printed "stale") when the hash differs; label stubs "stub".
A2-15 [H3] [MEDIUM] [CONFIRMED] Risk guidance recommends an API that is wrong for negative divisors
- Where:
src/risks.rs:232-235(DivisionSemantics), docs risk table row "Division and modulo". - What happens: "Python
//and%floor toward negative infinity; Rust/and%truncate: usediv_euclid/rem_euclidor explicit floor math." Euclidean division gives a non-negative remainder, which equals floor division only for positive divisors. Checked with Python:7 // -2 == -4,7 % -2 == -1; Euclidean7 div -2 == -3,7 rem -2 == 1;-7 // -2 == 3vs Euclidean4. An agent following the advice gets every negative-divisor case wrong (the recorded traps would catch it, but the advice lead there). - Fix: "floor division:
q = a / b; if (a % b != 0) && ((a < 0) != (b < 0)) { q - 1 }, remaindera - b*q" ornum_integer::Integer::div_floor/mod_floor; keeprem_euclidonly for a positive divisor. Test: a unit test inrisks.rsor a docs test that evaluates the recommended snippet against Python on a grid including negativeb. - Checked and fine in the same file: the
toFixed/Math.round/Dateclaims (verified with Node:new Date("2026-02-30")is 2 March 2026,(2.5).toFixed(0)is "3",Math.round(-2.5)is -2), the Swift/PowerShell notes.
A2-16 [H6][H1] [LOW] [CONFIRMED] The unsafe audit has holes
- Where:
src/gate.rs:1264-1306, 1315-1415. - What happens:
strip_codeworks line by line, so a string that closes on a later line leaves the rest of that line parsed as inside a new string: withlet s = r#"on one line and"#; unsafe { x() }on the next,unsafeis not found (reproduced with the real function, also for"abc..."; unsafe {}). It only scanssrc/:build.rs,tests/,benches/and every dependency (aunsafe-using crate added as a dependency, a path crate) are outside it;#![forbid(unsafe_code)]inport.rsis not checked to still exist.// SAFETY:is satisfied by any text in the comment block above. - Fix: parse with
syn(or runcargo geiger/cargo clippy -D unsafe_codeon the crate:-W clippy::undocumented_unsafe_blocksand-F unsafe_codefor everything exceptlib.rs), scanbuild.rstoo. Test: the two-line raw-string case.
A2-17 [H6] [LOW] [CONFIRMED] Deep recorded cases are skipped by gate and card (regression of a pitfalls entry)
- Where:
src/gate.rs:537(recorded_values),src/card.rs:163,src/error_paths.rs:176. - What happens: pitfalls says case lines are read with the recursion limit off. These three read them with
serde_json::from_str, which fails above 128 levels (checked: a 200-deep array returns an error).literalssilently ignores the line (continue), so recorded strings inside deep documents (Prettier doc trees) are invisible to the cheat guard;error casesdoes not see a deep failing case; the card's per-function count skips it. - Fix: use the harness's
parse_deep(orDeserializer::disable_recursion_limit) at those three places; test with a 200-deep line like the pitfalls entry says.
A2-18 [H4] [LOW] [CONFIRMED] The tests ratchet is textual
- Where:
src/gate.rs:682-713. - What happens: tests and assertions are counted by regex over source with comments and strings removed, not by
running them.
assert!(true)replaces a real assertion at equal count;#[cfg(any())]or#[cfg(FALSE)]on a test mod still counts; an empty#[test] fn t() {}counts;should_panicis counted but never compared. The first passing gate sets the baseline, so tests removed before it are never noticed. - Fix: count tests from
cargo test -- --list(names) and assertions only as a hint; fail when a name from the baseline disappears or whencargo testruns fewer tests than the baseline. Store test names in the baseline.
A2-19 [H2][H6] [LOW] [CONFIRMED] Smaller things that read as stronger than they are
sizereturns no row at all when the original files are not found (source == 0);stalereturns nothing when the unit is missing: absent rows look the same as passing ones in the audit entry (12/14 checks). Print "not checked: reason".lifted_checksruns fmt, clippy, test andportedonly; the audit entry "gate passed, 6/6 checks" does not say thatliterals,tests,recordingandbehaviordid not run (the check detail does, the audit does not).- The audit log is append-only by convention only; there is no hash chain, and
record()skips the entry silently whenunit_entrycannot load the manifest (switched/gatereturn before logging). lockfileandadvisoriesare alwayspassed: true, documented as warnings; fine, but the audit count of "checks passed" includes them.--float-toleranceis documented as "within that share";nearusesmax(|e|,|a|,1), so below 1 it is an absolute tolerance (0 vs 1e-10 matches at 1e-9).
Verification improvements for this area (ranked)
- Held-out validation in
gate(the one check that defeats lookup tables, split strings, include_bytes, build.rs and shell-outs together). At gate time runfuzzwith a fresh random seed (say 200 cases, 10-30 s budget) and fail on any mismatch; also derive "neighbour" cases by perturbing each recorded argument (one character, +-1, swap two fields) and compare original vs port. Cheap because both pieces exist (fuzz,diff). Test: three canned cheating ports (match table, shell-out,include_bytes!copy) must fail it. - Hermetic diff. Run the behavior
diffonce with the original unit folder renamed and the recording files outside the crate readable only by the harness, so a port that reads or executes the original fails. - Recording integrity from outside the working tree. Compare
cases.jsonlwith the committed version in gate andmap --check; fail whenrecorded-from.jsonis missing or has nocases_hash(A2-01); ratchet case count, per-function count and coverage (A2-02); require at least one case per export, and for a function with athrow, one failing case. - Known-diffs budget (A2-03): max 1% accepted unless a human accepts N via a flag that lands in the audit log; print accepted cases in every summary line and in the SVG.
- Walk everything. Replace the
ignore-based walker inport_fileswith a plain walk (hidden and ignored files included, minustarget/), includebuild.rsandtests/, drop the file-name exemption (A2-04), and add a denylist of process, dynamic-load,include_*!,env!("CARGO_MANIFEST_DIR"), build-script and non-registry dependency constructs (A2-06). - Mutation self-test of gate (cheap, mechanical). A
tests/gate_cheats.rsthat builds a stand-in crate and asserts gate fails for each of:.ignored table,#[cfg(test)]first, negative numbers, hex, split strings,recorded-from.jsonremoved, one-case re-record, all cases in known-diffs, shell-out,build.rstable,include_bytes!copy,unsafeafter a multi-line raw string, 5 marked literals. Today only the plain-spelling forms are covered (tests/loop.rs:2673), andSTATUS.mdrightly says "not yet run on a real port". - Make
enableprove itself (A2-08): load check in a subprocess, identity check per rebound name, skipped names stored in the audit entry and the card, a one-line stderr notice when the block falls back. - Reports carry their evidence (A2-09): gate result with date, accepted diffs, tolerance, recording state, cases; one definition of speedup.
- Shadow reports what it did not compare (A2-11): counters for original-threw, native-not-loaded, skipped, and
a summary at exit;
app shadowcompares effects and strips credentials in--keep. - Fix
div_euclidadvice (A2-15) and add a test that evaluates every code snippet inguidance()that claims an equivalence.
Things checked and found sound (so nobody re-checks them)
cases_hashcovers the firstnlines in order, with line ends; deleting, editing or reordering any recorded line is caught while the file andrecorded-from.jsonare consistent; appending is allowed (src/recording.rs:60-70, 319-333).apply_knownmatchesfn,argsand the port's exactactual: a different wrong result still fails, and an entry that no longer happens fails gate asknown diffs(src/recording.rs:447-475,src/gate.rs:998-1020).known_diffs_addedandbehavior_detaildo state accepted and newly added entries on the gate line (the issue is that they never fail; A2-03).enablewithout flags refuses when any case fails or any export is missing (src/main.rs:1545-1554);--partialand--onlywithout--forceselect only functions with at least one recorded case, all matching (select_matching); PowerShell partial enable is refused;--forceis written to the audit log and shown as FORCED bylogandmap(src/audit.rs:344-349,tests/audit.rs).disablerestores the file byte for byte, including the "newline added" case;assigned()word-boundary and multibyte handling (src/enable.rs:383-399, tests intests/switch.rs).- Audit entries hold no absolute path or user name; a torn last line is closed before the next entry and skipped
when reading (
src/audit.rs:130-153). record,diff,benchandfuzzset the unit's kill switch tooriginalfor the original's side (enable::original_only), so an enabled unit is still compared to the real original.- The
percenthelper never prints100%unless every line ran;fallback_percentnever rounds to none or all;times/nsround up into the next unit correctly (src/recording.rs:151-158,src/card.rs:200-257). scan_rusthandles nested block comments, raw strings with hashes,b/cprefixes,\u{..}/\x..escapes, numeric suffixes and underscores, and ranges (0..100000); the plain forms of hard-coding are caught (reproduced: three plain recorded strings or numbers fail).RECORDING_FILESmentions in a string literal failliterals(plaininclude_str!("../cases.jsonl")).unsafe_blocksrequires the// SAFETY:comment in the contiguous comment lines directly above, ignores comments and single-line strings, and walkssrc/withread_dir(so.ignoredoes not hide unsafe).- Date,
toFixed,Math.roundand PowerShell conversion claims inguidance()(Node and Python spot checks). risks.rsregex heuristics (uses_regex) are heuristics with tests; a regex literal at the start of a line or after=>/[is missed ((?:^|[=(,:!&|?{;]|return)without the multi-line flag), so a function with only such regexes does not get the regex traps (LOW, not reproduced end to end).rules.rs: appends only, deduplicates, no path or secret handling issues;library.rs: replay failure onErrand missing exports counts as failures, and the fallback is computed from the public API exports (a rate of exports, not of cases, asFallbackdocuments).