Skip to content

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.

38.8 KB
Raw Blame

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 deleted recorded-from.json. Nothing in gate runs 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.json switches 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 passes gate and is switched on by enable; known-diffs.jsonl has 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.
  • enable prints "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.calls and "no mismatches" exclude every call where the original throws, so the error paths are never shadowed. app shadow never compares side effects.
  • risks.rs advises div_euclid/rem_euclid for 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()? and serde_json::from_str(..).ok()?; a missing or unparsable file, or one without cases/cases_hash/fingerprint keys, returns None, which gate reads as "nothing wrong" and pushes no recording row 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 from cases.jsonl, and runs gate: behavior 860/860, no recording row, Gate passed. The map column "Original" then reads "not recorded", but nothing fails. (The agent can equally write a new recorded-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, when cases.jsonl exists and recorded-from.json is missing or has no cases_hash, fail recording with "recording cannot be verified: run record again". Stronger and still cheap: compare cases.jsonl with 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 (coverage is always passed: true, src/gate.rs:940-949). diff iterates over cases, so an export with zero cases is never looked at; api only lists exports missing from the Rust module that have cases. tests/card.rs/issue #887 shows record --count 0 --inputs one.jsonl gives a crate with one case.
  • Failing scenario 1: the agent re-records with --count 0 --inputs one.jsonl. recorded-from.json and cases.jsonl are consistent, so there is no tamper signal; gate prints behavior 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 be Default::default() and ported passes (it only looks for unimplemented!, todo! and a bare panic!); enable switches it on.
  • Fix: persist cases and per-function case counts and the saved coverage in .rust-anything/tests.json and fail when they drop (an explicit gate --accept-smaller-recording leaves an audit line); fail behavior when an export has no recorded case (the enable --partial path already refuses such functions: select_matching says "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 assert enable refuses.

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 from diff --json) and any non-blank reason. apply_known removes the matching mismatches and adds them to passed. There is no cap, no share limit, and gate does not fail when entries were added in the same change as port.rs; it only appends "N entries added since the last passing gate" to a passing line (behavior_detail). enable and report run the same diff, so both treat the cases as matched.
  • Failing scenario: the port returns None for everything; diff --json | jq produces 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; with matched: diff.passed.
  • Fix: gate fails 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 id diff prints. 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_under via walk::builder), src/walk.rs:128-146.
  • What happens, four independent ways:
    1. port_files walks with the ignore crate, so a src/.ignore containing table.rs (always honoured, no git needed), a hidden folder src/.d/, a .gitignored file, or a subfolder holding a rust-anything.json is skipped. I confirmed with ignore 0.4.34: with src/.ignore = table.rs, the walk returned only port.rs and nested/n.rs; table.rs and .hid/t.rs were gone. Cargo still compiles them (mod table;).
    2. 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.rs is the bindings file the agent can edit freely; nothing compares it with what bridge generates.
    3. 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.
    4. files_under only returns .rs; data files, build.rs (crate root, outside src/) and tests/-only helpers are never read by literals or size.
  • Failing scenario: echo table.rs > src/.ignore, put 900 match arms in src/table.rs: size, literals, tests all pass; unsafe still scans (it uses read_dir, not the walker).
  • Fix: walk with standard_filters(false) (no ignore files, hidden included) and exclude only target/; identify generated files by content or by comparing with bridge's output (or a // @generated by rust-anything header plus a hash), not by name; stop only at a #[cfg(test)] that is followed by mod and treat the rest of the file as code otherwise (or parse with syn and drop cfg(test) items). Test: the four forms above each with a three-entry table must fail literals.

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 time no (never equals one recorded value)
    "\u{68}ello world one", b"hello world one" yes (unescaped), so fine
    -12345.678 when the recorded value is -12345.678 no: the sign is not part of the scanned number, the bits differ
    0xDEADBEEF, f64::from_bits(0x40C8...) no: hex/octal/binary go to code, not numbers
    12344.678 + 1.0, 12345.0 + 0.678 no
    "12345.678".parse() no
    4_294_967_299u64 yes (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 invisible
    any 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 a match over the 200 recorded inputs (inputs are not looked at at all: args are recorded values too, but a match arm 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 flag match or 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 only Command::new calls are cargo); src/gate.rs:1130-1210 (rust_checks), :1264-1306 (unsafe_blocks).
  • What happens: gate neither looks for std::process, Command, libloading, include_str!, include_bytes!, include!, std::fs/read_dir on paths outside the crate, nor for a build.rs, [build-dependencies], path/git dependencies or proc-macro crates. RECORDING_FILES matches the three file names only inside string literals (src/gate.rs:588), so read_dir(".") filtered by .jsonl, concat!("cases", ".jsonl") or cp cases.jsonl src/d.bin; include_bytes!("d.bin") pass. A port that does Command::new("node") .arg(original_script) passes diff (the original is on the machine), clippy, tests, literals (source strings of the original are exempt via in_original), size and unsafe.
  • Related: lift and map use the text test contains("original::") (src/lift.rs:766,776, src/port_map.rs:293), so glue that spawns the original without crate::original:: is "Rust only" in the map (the lift part is for the lift auditor to confirm).
  • Fix: (a) static denylist over every .rs file in the crate including build.rs, plus Cargo.toml: process spawning, dynamic loading, include_*! pointing outside src/, 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 behavior diff once 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 to node original.js must 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 from found. The check output never says how many literals were exempted. A table with one marked arm per line passes with no recorded values written into the port. The fix text of the failing check and the literals detail 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; the panics failure text names it. It also only looks at src/port.rs and attributes a panic to the nearest preceding fn name, 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.jsonl only has the check names).
  • Failing scenario: gate says FAIL literals 5 recorded values ...; the agent appends // recorded-literal: library constant to each line; gate passes. Same for deleting tests.json after 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 when p.getBuiltinModule is missing on an older Node (TypeError inside the try). enable never loads the module, and prints "On: f runs in Rust". The card's "Switched on: on" is is_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.route registrations, functools.partial(f), default arguments) keep the original function. (3) Exports that declared() cannot rebind (a const arrow) are listed in Switched.skipped on 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-start function f( inside a template literal or docstring satisfies declared (regex over raw text) for a name that is really a const; the block then assigns to a constant at import (WEAK, not reproduced).
  • Failing scenario: the deployment ships src/ without rust/<crate>/index.cjs (or a .node built for another Node ABI): every call silently runs the original, audit says switched 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; store skipped in 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 missing index.cjs must 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:
    1. matched includes cases accepted through known-diffs.jsonl; the SVG headline says "Same result as the original on all N recorded cases" (A2-03).
    2. diff is called with float_tolerance: None and ignore_key_order: false, which settle() replaces with the values saved in rust-anything.json (an editable file; tolerance::check allows anything below 1; near is |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.
    3. 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.
    4. verdict() returns speedup = 1.0 for an empty row list and nothing_timed() requires a non-empty list, so a unit whose benched functions all produced no timings prints "Speedup ... 1.0x" and "1.0x faster" while advice says "Nothing to compare".
    5. 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, rust folds); 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.
    6. cases_per_function counts only "fn" cases (case["fn"].as_str()), but diff.missing also names missing classes (the Node driver pushes c.class), so a missing class' cases are not in fallback_cases and the card prints a lower fallback share (0.0% when only a class is missing).
    7. machine() prints available_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 one known-diffs entry 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.md row "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/raise in 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)), Kotlin require/check/error, Ruby fail, Python assert, PowerShell Write-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) print not checked, not "nowhere". Test: Kotlin require(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/Python call, 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.calls is 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 reach compare. Other gaps: if the Rust module does not load, the shadow warns once and then calls stays 0 while mismatches stays 0; only the first 10 mismatches are reported and shadowStats is 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 in requests but neither matched nor mismatches; headers present only in the build are not looked at (only the original's headers are iterated); --keep writes each mismatching request including Authorization and cookies to shadow/inputs.jsonl (only host is 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.errors and calls; expose shadowStats.skipped/native_loaded; print a summary line at exit ("N calls, M compared, K original threw, mismatches X"); in app shadow print requests = matched + mismatches + upstream_errors, compare the effect sinks of both sides, and strip authorization, cookie and set-cookie before --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 own size and coverage include through with_local_imports) are not. The docs say "when they change, diff reports a stale recording ... so an upstream change cannot pass silently".
  • Failing scenario: util.ts imports ./helpers.ts; upstream changes helpers.ts; map says "unchanged", gate has no recording failure.
  • Fix: hash the import closure (reuse with_local_imports for TS, called_implementations for 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 always passed: 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 bridge with every function unimplemented!, zero cases and no gate (tests/port_map.rs asserts exactly this: one port, cases == 0). The headline reads "N of M units have a Rust port", and "Every unit analyze found has a port." appears when all are stubs. last_diff is the last line of diff-history.jsonl; it stores a hash of port.rs but last_diff never 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 of enable --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 text original::.
  • Fix: count only ports with ported passing, cases > 0 and a recorded diff for the current port.rs hash; last_diff returns None (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: use div_euclid/rem_euclid or 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; Euclidean 7 div -2 == -3, 7 rem -2 == 1; -7 // -2 == 3 vs Euclidean 4. 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 }, remainder a - b*q" or num_integer::Integer::div_floor/mod_floor; keep rem_euclid only for a positive divisor. Test: a unit test in risks.rs or a docs test that evaluates the recommended snippet against Python on a grid including negative b.
  • Checked and fine in the same file: the toFixed/Math.round/Date claims (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_code works line by line, so a string that closes on a later line leaves the rest of that line parsed as inside a new string: with let s = r#" on one line and "#; unsafe { x() } on the next, unsafe is not found (reproduced with the real function, also for "abc ... "; unsafe {}). It only scans src/: build.rs, tests/, benches/ and every dependency (a unsafe-using crate added as a dependency, a path crate) are outside it; #![forbid(unsafe_code)] in port.rs is not checked to still exist. // SAFETY: is satisfied by any text in the comment block above.
  • Fix: parse with syn (or run cargo geiger/cargo clippy -D unsafe_code on the crate: -W clippy::undocumented_unsafe_blocks and -F unsafe_code for everything except lib.rs), scan build.rs too. 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). literals silently ignores the line (continue), so recorded strings inside deep documents (Prettier doc trees) are invisible to the cheat guard; error cases does not see a deep failing case; the card's per-function count skips it.
  • Fix: use the harness's parse_deep (or Deserializer::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_panic is 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 when cargo test runs 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

  • size returns no row at all when the original files are not found (source == 0); stale returns 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_checks runs fmt, clippy, test and ported only; the audit entry "gate passed, 6/6 checks" does not say that literals, tests, recording and behavior did 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 when unit_entry cannot load the manifest (switched/gate return before logging).
  • lockfile and advisories are always passed: true, documented as warnings; fine, but the audit count of "checks passed" includes them.
  • --float-tolerance is documented as "within that share"; near uses max(|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)

  1. 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 run fuzz with 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.
  2. Hermetic diff. Run the behavior diff once 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.
  3. Recording integrity from outside the working tree. Compare cases.jsonl with the committed version in gate and map --check; fail when recorded-from.json is missing or has no cases_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 a throw, one failing case.
  4. 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.
  5. Walk everything. Replace the ignore-based walker in port_files with a plain walk (hidden and ignored files included, minus target/), include build.rs and tests/, 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).
  6. Mutation self-test of gate (cheap, mechanical). A tests/gate_cheats.rs that builds a stand-in crate and asserts gate fails for each of: .ignored table, #[cfg(test)] first, negative numbers, hex, split strings, recorded-from.json removed, one-case re-record, all cases in known-diffs, shell-out, build.rs table, include_bytes! copy, unsafe after a multi-line raw string, 5 marked literals. Today only the plain-spelling forms are covered (tests/loop.rs:2673), and STATUS.md rightly says "not yet run on a real port".
  7. Make enable prove 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.
  8. Reports carry their evidence (A2-09): gate result with date, accepted diffs, tolerance, recording state, cases; one definition of speedup.
  9. Shadow reports what it did not compare (A2-11): counters for original-threw, native-not-loaded, skipped, and a summary at exit; app shadow compares effects and strips credentials in --keep.
  10. Fix div_euclid advice (A2-15) and add a test that evaluates every code snippet in guidance() that claims an equivalence.

Things checked and found sound (so nobody re-checks them)

  • cases_hash covers the first n lines in order, with line ends; deleting, editing or reordering any recorded line is caught while the file and recorded-from.json are consistent; appending is allowed (src/recording.rs:60-70, 319-333).
  • apply_known matches fn, args and the port's exact actual: a different wrong result still fails, and an entry that no longer happens fails gate as known diffs (src/recording.rs:447-475, src/gate.rs:998-1020).
  • known_diffs_added and behavior_detail do state accepted and newly added entries on the gate line (the issue is that they never fail; A2-03).
  • enable without flags refuses when any case fails or any export is missing (src/main.rs:1545-1554); --partial and --only without --force select only functions with at least one recorded case, all matching (select_matching); PowerShell partial enable is refused; --force is written to the audit log and shown as FORCED by log and map (src/audit.rs:344-349, tests/audit.rs).
  • disable restores the file byte for byte, including the "newline added" case; assigned() word-boundary and multibyte handling (src/enable.rs:383-399, tests in tests/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, bench and fuzz set the unit's kill switch to original for the original's side (enable::original_only), so an enabled unit is still compared to the real original.
  • The percent helper never prints 100% unless every line ran; fallback_percent never rounds to none or all; times/ns round up into the next unit correctly (src/recording.rs:151-158, src/card.rs:200-257).
  • scan_rust handles nested block comments, raw strings with hashes, b/c prefixes, \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_FILES mentions in a string literal fail literals (plain include_str!("../cases.jsonl")).
  • unsafe_blocks requires the // SAFETY: comment in the contiguous comment lines directly above, ignores comments and single-line strings, and walks src/ with read_dir (so .ignore does not hide unsafe).
  • Date, toFixed, Math.round and PowerShell conversion claims in guidance() (Node and Python spot checks).
  • risks.rs regex 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 on Err and missing exports counts as failures, and the fallback is computed from the public API exports (a rate of exports, not of cases, as Fallback documents).