0058. Porting the TS AI reference to Rust, and how parity is kept
Source:
docs/decisions/0058-ts-reference-port-and-parity.md. Generated at build time; edit the source file.
Date: 2026-11-21 Status: Accepted (R3 Task 5). Renumbered by R3 Task 26 (it was the R3 placeholder record). Builds on 0030, ADR 0057 and ADR-AI-8.
Context
Section titled “Context”R3 ports TS M3 (.worktrees/m3/packages/ai) to the Rust ai crate. The TS code and its tests are the behavioural spec. Most of it ports one to one. A few things cannot, mostly because the regex crate has no lookarounds. In exchange it guarantees linear-time matching, with no catastrophic backtracking. The validator enforces facts by reference (ADR-AI-8). A port that drifts from TS, or that a hostile string can stall, would leak made-up chess facts or hang a job.
Decision
Section titled “Decision”Intentional deviations
Section titled “Intentional deviations”These are the plan’s eight deviations. Every other behaviour must match TS.
parse_coaching_inputreports the first serde deserialisation error, then every refinement error. Zod reported all issues at once. Paths stay dotted (weaknesses.0.rank).- Regex lookarounds are emulated by
validator::bounded(bounded_matchesand its generalscan). A failed boundary check retries from the rejected start plus one char. JS\dbecomes[0-9], and JS\bbecomes(?-u:\b).Token.indexis a byte offset into the canonical text, not a UTF-16 index. - The number and date path index is a
BTreeMap, solist_number_pathsreturns paths sorted, not in insertion order. - The model never writes free-text facts. The old extractors (
extract_moves/numbers/dates) mine evidence strings. They also run as defence in depth on token-stripped text after the leak check. - Item citations: in reports, every position token (
move/best/pv) must reference one of the item’scitations(uncited_reference). In chat, position tokens are themselves the citations. - Item text is capped at
ITEM_TEXT_MAX_CHARS = 2000client-side (schema_mismatch/too_big). - Owner input: the chat is no longer cache-only for the engine.
get_evalstays cache-only. The newanalyse_positionruns an interactive engine check under its own protocol, and its results are stored apart fromposition_evals. Free users may chat (3 messages a week). - On the Postgres queue, AI unavailability re-queues through
JobError::Release { delay }from the schedule. The retry count lives on the run or note row. There are no BullMQ-r<n>job ids.
Regex translation table (deviation 2)
Section titled “Regex translation table (deviation 2)”| JS | Rust | Why |
|---|---|---|
(?<!C)X (a char-class lookbehind) |
X, plus before_ok(prev char) in scan |
No lookbehind. A rejected start retries at start + 1, and the scan skips every position whose before-check fails, so a run of rejections costs one pass. |
X(?!C) at the end, with a fixed match end |
X, plus after_ok(next char) (ISO dates, double, half) |
No backtracking choice can change the end, so a post-check is exact. after_ok is valid only for fixed-end patterns. On a variable-length pattern it rejects a match that JS would shorten by backtracking: JS [a-c]+(?!\d) matches “ab” in “abc1”, but the post-check rejects “abc”. Such patterns must use the next row. |
X(?!C) at the end, where X has optional or alternative parts |
(?P<m>X)(?:[^C]|$). The logical match is m, and the next search resumes at the end of m. |
Leftmost-first semantics then pick the same shorter match that JS backtracking finds (0-0-0x gives O-O-0x, and e7-e8=Qx gives e7e8). |
An inner lookahead (\d{1,3}(?:,\d{3})+(?!\d), (?![\d:]), and the year tail YEAR(?![A-Za-z0-9])) |
Folded into a consumed alternative ((?:\.(f)|[^0-9]|$)), or a small manual matcher that tries the JS backtracking order (mdy_day, year_after) |
Same result, and still linear. |
(?=PH) |
…\x{1}, consumed, with only m replaced |
Same. |
\d (no u flag) |
[0-9] |
Rust \d is Unicode. The class is ASCII in both, but hardening H1 folds every \p{Nd} digit to ASCII first. So extract_numbers("٣ games") is [] in TS and [3] in Rust, deliberately. |
\s |
[\t\n\x0B\x0C\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF] (JS_SPACE) |
Rust \s adds U+0085 and lacks U+FEFF. trim and split(/\s+/) use the same set. |
\b |
(?-u:\b) |
JS \b is ASCII even with the i flag. |
The i flag |
(?i:…) scoped to ASCII words, never around [A-Za-z] classes |
Unicode folding adds only U+212A (Kelvin) and U+017F (long s) to ASCII letters, and NFKC has already mapped both away. |
\p{Nd} (u flag) |
\p{Nd} |
Same class. Unicode versions may differ slightly. |
s.normalize("NFKC") |
unicode_normalization::nfkc, followed by H2 and H3 |
Same algorithm, possibly another Unicode version. |
UTF-16 indexes (slice(i - 16, i), PH.repeat(m.length), sort by index) |
window_before counts UTF-16 units, mask writes one placeholder per unit, and Utf16Cursor sorts hits by UTF-16 offset |
Window sizes and ordering stay observable and identical. Other offsets are byte offsets. |
Every lookaround in the validator uses one of these forms. A new pattern must use one of them too, and must say which one in a comment.
Bounded and linear
Section titled “Bounded and linear”Each regex call is linear in the span it searches, but a sum of linear calls is not automatically linear: the total is what matters. The rules that keep the total linear in the input:
scanrestarts after a match at its end. After a rejection it skips every start whose before-check fails, so a run of rejected starts costs one pass.- Per-candidate checks run only on bounded windows (the 12-, 16- and 20-unit look-behind windows) or on slices that do not overlap across candidates (the text after a number, a word run or “half”, up to the next token).
- Nothing rescans a growing prefix. The TS bare-square rule tests
^[gap]*$onslice(lastEnd, c.at), which rescans one long gap for every rejected square after it: quadratic. The first version of this port inherited that.scan_movesnow walks the text once, keeps the last non-gap position, and accepts the gap iff that position is beforelast_end. The result is the same, in linear time.
The union (below) runs every extractor on both normalisations. That at most doubles the cost, and each path keeps these rules.
Deterministic tests enforce the rules:
extract::tests::scanned_bytes_are_linear_on_hostile_shapes(a unit test; binding). Acfg(test)counter,bounded::count_scanned, records the bytes each regex search inscanreads (from the search start to the match end, or to the text end), the bytes skipped after a rejection, and the per-candidate checks inscan_moves(the gap walk, the 16-unit window and the gap before the next candidate).scanbacksbounded_matchesand every extractor pass. The test runs all four public functions, so both paths, on 31 hostile shapes at n = 32 Ki. It asserts at most 120·n bytes; the worst measured is 67·n, on the gap shape. A quadratic rescan, such as the pre-fix gap check, reads about n²/20 bytes there, which is about 1600·n.bounded_matches_is_linear_in_rejectionscounts the boundary-predicate calls: at most n + 2 on 200k rejected starts.extractors_are_linear_on_large_hostile_text(timing, N against 4N) is kept as a cross-check. It is#[cfg_attr(debug_assertions, ignore)], so it runs only in release builds. Before the fix, the gap shape took 0.48 s at N and 7.6 s at 4N.
Deliberate hardening beyond TS (fix round 1, binding ruling)
Section titled “Deliberate hardening beyond TS (fix round 1, binding ruling)”A missed claim is a leak, so extraction is a superset of TS by construction (union). This is fix round 2’s binding ruling.
Each extractor runs one pipeline function twice:
- once with
NormMode::TsExact, which is TS’s steps only, with TS’s invisible, dash and thousands sets and TS’s long-algebraic class; - once with
NormMode::Hardened, which adds H1–H6 below.
The result is the TS-path list unchanged, then each hardened result the TS path did not also find. The difference is a multiset difference by value, in hardened order (extract::union_by, linear). normalize_text is the hardened normalisation, and normalize_ts is TS’s.
Fix round 1 applied hardening alone, and that was a regression. Folding a non-ASCII neighbour to ASCII (H1, H3, H4) glues it onto a move or date before the boundary checks run. Nf3é becomes Nf3e, e2-e4а becomes e2-e4a, and 14 Octé becomes 14 Octe. TS finds all three; hardening alone found none. The union restores them.
Each item below is a recorded deviation. Each has a test in tests/extract_gaps.rs, in mod hardening; mod union tests the merge.
- H1. Decimal digits. Every
\p{Nd}digit is folded to ASCII after NFKC (٣becomes3,१२becomes12). The value comes fromND_ZEROS, a static table of the code points that start each run of ten (76 runs, generated from Node 22.22, ICU 77.1, Unicode 16.0).ND_ZEROSalso defines\p{Nd}for thousands grouping. - H2. Invisibles.
strip_invisiblesremoves the whole\p{Default_Ignorable_Code_Point}set as well as TS’s list. That adds, for example, U+180F, U+206A–206F, U+FFF0–FFF8, U+1BCA0–1BCA3, U+1D173–1D17A and all of U+E0000–E0FFF. - H3. Combining marks. After NFKC, the text goes through NFKD, every
\p{Mn}is dropped, and the text is recomposed with NFC. SoN\u{301}f3reads asNf3, andéreads ase. - H4. Homoglyphs. Cyrillic, Greek and Armenian lookalikes of chess letters (files, pieces,
O,x) and digits are folded to ASCII. Examples are Cyrillic а е о р с х К В Н О Р Т and З→3, Greek Α Β Ε Κ Ν Ο Ρ Τ Χ ο ν, and a few Latin ones (ɡ ɑ ı). They live in one table,normalize::HOMOGLYPHS, a superset of TSleaks.ts’sCONFUSABLESthat the leak detector (T6) reuses. - H5. Dashes. The dash set adds U+02D7, U+2E3A, U+2E3B, U+058A and U+30FC to TS’s
DASH, which already holds U+2796. It is one table,normalize::DASH_RANGES, used byis_dash, by the castling and minus rules, and (throughdash_class()) by the long-algebraic separator class. On the TS-exact path the long-algebraic class stays TS’s:-, U+2010–U+2015, U+2212 andx. - H6. Thousands separators. U+2006, U+2008 and U+200A group thousands, as U+00A0, U+202F, U+2009 and U+2007 already did.
The pipeline is:
- strip invisibles;
- group thousands;
- NFKC;
- strip invisibles;
- H3;
- H1 and H4, char by char;
- TS’s castling dashes, minus before a digit, figurines and
0-0castling.
In the differential corpus, the inputs whose hardened normalisation differs from TS are listed in HARDENED. For every row, each Rust list (numbers, SAN, UCI, dates) must start with TS’s list unchanged. That makes it a superset of TS’s, in TS’s order, and normalize_ts must equal TS’s normalizeText. A HARDENED row may add results but never lose one, and must still differ somewhere, so the list cannot go stale. Every other row must equal TS exactly. The corpus has 175 inputs, including every regression example above.
Leak detector and tokens (Task 6)
Section titled “Leak detector and tokens (Task 6)”- Tokens.
canonical_for_tokensuses TS’s exact invisible set, not the hardened one, sostrippedkeeps every char TS keeps and the leak detector can still see a boundary there. Token and token-error indexes are byte offsets in the canonical text; stray-brace errors are byte offsets instripped(TS reports those instrippedtoo).{{eng:<32 hex>:tried|<1-3>[:<n>]}}and{{offtopic}}are R3 additions. - Leak union.
find_leaksruns two paths and returns the TS path’s leaks unchanged, then the hardened path’s extras, deduplicated by(kind, text).find_leaks_with(s, NormMode::TsExact)is TS’sfindLeaksexactly: TS’s invisibles,CONFUSABLESon[Α-ωЀ-ӿ],DASHand detectors. The hardened path adds H2 (invisibles), H3 (marks), H4 (all ofHOMOGLYPHS) and H5 (dashes). H1 is not needed:\p{N}+already flags every non-ASCII digit. - Origin-aware boundaries. The hardened text lowercases every ASCII letter and writes every folded char (a homoglyph, or a char whose decomposition without marks is ASCII) as ASCII uppercase. The detector bodies match case-insensitively, while the boundary classes (
[a-z],[a-z0-9], checked bybefore_okand in the folded lookahead as(?-i:[^a-z])) stay case-sensitive. A folded neighbour therefore never counts as a letter. That closes the homoglyph-plus-accent gap the T5 review found:fιveé(TS: ι is not folded; plain folding:fivee) is flagged. Hardened leak text is reported lowercased. - The date alternation. Only alternatives
aandccarry(?<![a-z]), soscangets no global before-check, and the check rejects anaorccandidate whose previous char is[a-z]. Retrying at start + 1 is exact, because no other alternative can match at a start whereaorcwas chosen. - Corpus. The same tool records TS’s
canonicalForTokens,parseTokensandfindLeaks(on the stripped and the raw text) intotests/leaks.rs: 150 inputs, including all 56 escapes. For every row, the TS path and the tokens equal TS exactly (indexes compared in UTF-16), andfind_leaksstarts with TS’s list. Rows in that file’sHARDENEDmust add leaks; all other rows must equal TS exactly. - Cost. Every detector and token pass runs through
bounded::scan, socount_scannedsees it.leaks::tests::scanned_bytes_are_linear_on_hostile_shapesasserts at most 80·n on 23 shapes at n = 32 Ki. - Accepted false positives.
HOMOGLYPHSfoldsбto 6 andЗto 3, so Cyrillic prose can be flagged (базаgives the digit6). Coaching text is English, and a false positive only costs a repair. the\bin the date alternation (Task 7 fix).(?-u:\b)treats the hardened text’s uppercase fold marker as a word char, sojaո theéwas missed. TS’s(?:[0-9]|the\b)is now two alternatives:a(MONTH\.?\s+[0-9]) andt(MONTH\.?\s+the, followed by the folded lookahead(?:(?-i:[^a-z0-9_])|$)outside the group). The char after the greedy\s+decides between them, so leftmost-first gives TS’s match, and the reported text excludes the consumed char.tsharesa’s lookbehind.
Evidence index, resolver and segments (Task 7)
Section titled “Evidence index, resolver and segments (Task 7)”- Walk.
build_evidencewalksCoachingInput::to_json(), the wire JSON TS walks.serde_jsonmaps are sorted, so object keys are visited in key order instead of insertion order. That only reordersEvidence::numbers(a set; never rely on its order) and would change which of two writes to one path wins, which never happens on the fixtures. - JS number semantics.
cleanisformat!("{n:.11e}")parsed back (toPrecision(12)).js_roundisfloor(x), plus 1 whenx - floor(x) >= 0.5. That is exact JSMath.round, where(x + 0.5).floor()is wrong for 0.49999999999999994 and for odd integers at or above 2^52.Math.sign(0)is 0, sof64::signumis not used.-0prints as0. Number sets use SameValueZero. TS’sroundaddsEPSILON·sign(v)first, soformatNumber(-1.25, "dec1")is"-1.3"in TS (recorded with Node). The R3 plan’s"-1.2"is wrong, and the port follows TS. - pv.
pv_to_sanandfen_afterusePosition::push_uci, narrowed to chess.jsmove({from, to, promotion}): a promotion letter on a plain move is ignored, and king-takes-rook castling (e1h1) is illegal. The plan’sPosition::play_uci(&mut self) -> Result<PlayedMove, IllegalMove>already exists aspush_uci(R2), because R1’splay_uci(&self) -> Result<Position, _>keeps its callers.board.rsis unchanged, andchess-core/tests/board_uci.rspins the contract onpush_uci. {{eng:}}.triedgives the tried moves joined by spaces.<line>gives the evaluation from White’s point of view:signed1pawns,mate in n(White mates),mated in n(White is mated) orcheckmate(mate 0).<line>:<n>gives the n-th SAN.{{offtopic}}never resolves inresolve_token.- Segments.
render_segmentschecks that each token sits at its byte index in the canonical text, in order and without overlap. Otherwise, or if any token does not resolve, it returnsNone. Empty text runs are left out. It reports its single pass tocount_scanned. - Differential golden.
backend/tools/gen-evidence-golden.mjsruns m3’sevidence.tswith chess.js (it reads the version fromnode_modules/chess.js/package.json) and writesbackend/fixtures/ai/evidence/ts-evidence.json. That file holds the full index of all three fixtures, plus TS’sformatNumberof every number path in all 7 formats and a 287-row value grid. The format strings are the primary check and must match exactly. The values themselves are a secondary check, within 1 ulp. Numbers are written as JSString(n), sostr::parsereads them exactly. serde_json/float_roundtrip(coordinator-approved, fix round 1). Without this feature,serde_jsonreads some decimals one ulp off:0.9134999999999999reads as0.9135, sopct1renders91.4%where TS renders91.3%. The typedCoachingInputwould then not be the input JS sees. The workspace enables the feature. It adds no crate and leavesCargo.lockunchanged.paths.rs::json_numbers_parse_exactly_so_formats_match_jspins three such values.- Unprintable numbers.
format_numberreturnsNonefor non-finite values and for printed magnitudes of 1e21 or more (forpct0/pct1, after the ×100). At that point JS switches toInfinityor exponent form, and Rust never does. The token then does not resolve. from_fenis stricter than chess.js.Position::from_fenrejects FENs that cozy-chess finds structurally invalid but chess.js 1.4.0 loads (ADR 0037), such as a castling right without its rook. For such a FEN,pv_to_sangives[]andfen_aftergivesNonewhere TS converts the line. Fewer allowed moves is the safe direction: the validator only rejects more. The fixtures never hit this case.
Parity checklist rule
Section titled “Parity checklist rule”The plan’s parity checklist (TS test file → Rust test file → task) is binding:
TS test file (.worktrees/m3/packages/ai/test/) |
Rust test file (backend/crates/ai/tests/) |
Task |
|---|---|---|
input/schema.test.ts |
input_schema.rs (+ input_shape.rs) |
T2 (T1) |
output/output.test.ts |
output.rs |
T3 |
validator/extract.test.ts (except the pvToSan block) |
extract.rs |
T5 |
validator/extract-gaps.test.ts |
extract_gaps.rs |
T5 |
validator/tokens.test.ts |
tokens.rs |
T6 |
validator/leaks.test.ts (all 56 escapes) |
leaks.rs |
T6 |
validator/evidence.test.ts |
evidence.rs |
T7 |
validator/paths.test.ts |
paths.rs |
T7 |
extract.test.ts pvToSan block |
pv.rs |
T7 |
cost.test.ts |
cost.rs |
T9 |
client/fix-round-1.test.ts (parse reasons, taxonomy, custom ids, UnknownModel) |
parse_output.rs, client_errors.rs, custom_id.rs, cost.rs |
T9 |
client/anthropic.test.ts, fix-round-1.test.ts (adapter and batch parts) |
http_client.rs |
T11 |
client/fake-breaker.test.ts, fix-round-1.test.ts (breaker and fake parts) |
breaker.rs, fake_client.rs |
T12 |
The rules for every Rust file:
- it keeps the TS test titles in snake_case (a
describebecomes a module); - it asserts the same strings and values;
- a TS test with no Rust equivalent is listed in the plan with its reason (none are planned).
Where a port depends on engine semantics, a recorded differential corpus pins it. The validator’s corpus has 175 inputs. They cover:
- backtracking;
- inner lookaheads;
- the members of JS
\s(U+0085, U+1680,\t,\v, U+2029); - astral characters split by the 12-, 16- and 20-unit windows;
Oct 14th, 2026;- the hardening inputs.
backend/tools/gen-validator-corpus.mjs generates it. The tool runs m3’s normalize.ts and extract.ts under Node type stripping and rewrites the BEGIN GENERATED block of tests/extract_gaps.rs. That block records the Node, ICU and Unicode versions and the m3 commit (last run: Node 22.22.0, ICU 77.1, Unicode 16.0, m3 4ff8220). The output is deterministic, so re-running the tool on the same versions leaves the file unchanged. The block is checked by ts_parity::rust_matches_the_recorded_ts_output_on_the_edge_corpus. To add a case, edit the tool’s inputs and re-run it. Never hand-edit the block.
Consequences
Section titled “Consequences”- Superset by construction. The extractors return exactly what TS returns (the TS-exact path), plus whatever extra the hardened path finds (H1–H6). They can never lose a TS result, and every corpus row checks this. The hardened
normalize_textalone is not a superset; only the union is. - Cost. Linear time is a property of the rules above, not a guarantee of the
regexcrate alone. The deterministic byte-count test enforces it on both paths, and the union costs at most 2×. Every new check must keep to bounded windows or non-overlapping slices, and must callcount_scanned. - Lookaround forms. The forms above are the only sanctioned ones. Tasks 6–8 (tokens, leaks, claims) reuse
bounded::scanand the same constants. The leak detector should reuseHOMOGLYPHSandDASH_RANGES, not copy TS’s smaller tables. - Task 6 (the leak detector) must apply the same union if it reuses
HOMOGLYPHS(or any other H-item). It must detect on the TS-exact canonical text and on the hardened one, and flag a leak found by either. Folding alone can glue a neighbour onto a leak and hide it (Nf3é).NormMode,normalize_withandstrip_invisibles_withexist for this. - Unicode-version drift between ICU and
unicode-normalizationorregexis accepted. Such characters are rare in model text, and the leak detector catches the cases that matter.