Skip to content

Contributing to trails ​

The Rails-port methodology for building features that match Rails. The rules and conventions you must follow — commits, PR sizing, the module-mixin pattern, worktrees — live in CLAUDE.md. Project overview, package list, and the declare / associations / enums / schema reference live in README.md.

Working principles ​

  • Implementation-first. The goal is to implement Rails features, not to flip skipped tests. Build the feature, then unskip the tests that prove it. Read the Rails source first to understand the expected behavior.
  • Read existing code before writing new code. Trace how the codebase already handles the concern. Use the real persistence API (isNewRecord(), isPersisted(), readAttribute(), writeAttribute()) — not ad-hoc state. Handle composite primary keys (primaryKey can be string | string[]). Delegate to existing infrastructure; don't reimplement it.
  • Ship behavior and signatures. Never commit a method that matches a Rails API surface but returns null/undefined or only mutates in-memory state when Rails hits the DB — a missing method is better than a misleading one. The converse is equally true: correct behavior under a name, signature, or structure Rails doesn't have is also a defect, because the next agent to port a caller won't find it. parity:api coverage is a floor, not a goal; see CLAUDE.md "Fidelity is the job" for the standard.
  • Use the package ecosystem like Rails does. In activerecord, build queries with @blazetrails/arel (Table, SelectManager, Nodes, Attribute) — never raw SQL strings. Use @blazetrails/activemodel for validations/callbacks and @blazetrails/activesupport for inflection.

Porting a Minitest assertion ​

A Minitest built-in assertion (vendor/minitest/v6.0.0/lib/minitest/assertions.rb) ports as a Vitest expect, never as a helper. The built-in matcher is the default. A matcher from @blazetrails/vitest-matchers (loaded in every vitest project through @blazetrails/vitest-matchers/setup) is used only where the built-in gives the wrong result for that test, and test code never calls a ruby-compat function to assert. In Minitest exp is the first argument; in expect the actual value goes in expect(...), so the order flips. A msg argument becomes expect(x, msg). The refute_* / assert_not_* forms (refute_equal, refute_nil, assert_not_empty, …) are the same row with .not. scripts/test-compare/assertion-kinds.ts credits the built-in and the Ruby matcher of a row with the same kind.

Minitest (assertions.rb)Built-inRuby matcherUse the Ruby matcher only when
assert x / refute x (:171, :650)toBeTruthy() / toBeFalsy()toBeRubyTruthy() / toBeRubyFalsy()the value can be 0, "" or NaN
assert_predicate o, :foo? (:394)expect(o.isFoo()).toBeTruthy()expect(o.foo()).toBeRubyTruthy()foo? returns a value rather than a boolean
assert_equal exp, act (:220)expect(act).toEqual(exp)expect(act).toEqualRuby(exp)the value defines Ruby == (records, Duration, BigDecimal)
assert_nil x (:305)toBeNull()
assert_same exp, act (:463)expect(act).toBe(exp)
assert_in_delta exp, act, d (:241)expect(act).toBeCloseTo(exp, digits)expect(act).toBeWithinDelta(exp, d)toBeCloseTo's digit precision does not express the delta
assert_empty o (:188)expect(o).toHaveLength(0)expect(o).toBeEmpty()the receiver has no length (Map, Set, a Hash, an empty?)
assert_includes c, o (:260)toContainEqual(o) (Array), toContain(o) (String), toHaveProperty([o]) (Hash key)
assert_instance_of cls, o (:271)expect(o).toBeInstanceOf(cls)expect(o).toBeExactInstanceOf(cls)the subclass distinction matters
assert_kind_of cls, o (:282)expect(o).toBeInstanceOf(cls)
assert_respond_to o, :m (:453)expect(typeof o.m).toBe("function")expect(o).toRespondTo("m")the name is answered by respond_to_missing?
assert_match m, s (:293)expect(s).toMatch(m)
assert_operator a, :<, b (:315)toBeLessThan / toBeGreaterThan / …OrEqual
flunk msg (:624)expect.unreachable(msg)
skip msg (:825)ctx.skip(), or it.skip under a PERMANENT-SKIP: line

A built-in can also wrongly pass: toBeFalsy passes on 0, which Ruby treats as truthy, so a test going green is not the only signal. Check the type of the value under test before choosing the built-in.

A Rails test that asserts on a Minitest failure message or diff output loses that assertion permanently. Record it with a row in scripts/test-compare/assertion-receipts/<package>.ts.

Rails-private helpers and @internal JSDoc ​

Rails-private helpers must carry @internal JSDoc. The website's TypeDoc build runs with excludeInternal: true, and the blazetrails/rails-private-jsdoc ESLint rule (autofixable via pnpm lint --fix) enforces it. The rule consults eslint/rails-private-methods.json, regenerated by pnpm parity:api. Active across all Rails-mirroring packages (arel, activesupport, activemodel, activerecord, actionpack, actionview).

After a rebase: lint the auto-merged files ​

The pre-commit hook runs lint-staged, which lints only what is staged for that commit. A git rebase replays commits without running pre-commit, so files git auto-merged never get linted locally — and a defect can exist in the merged result while existing in neither parent branch. Two sibling PRs each deleting a different caller of the same import orphans that import; the first signal is the Lint CI job (this bit #5356).

The post-rewrite and post-merge husky hooks now lint the files each replayed commit touches (scripts/lint-rewritten-files.sh — for each <old> <new> pair git reports, it lints git diff <new>^!). That is deliberately narrower than <old>..<new>, which is a tree diff across the base move and would also name every file the new upstream changed and your commit never did. They report and never block — a rebase is not a commit you can amend in flight — so read the output: a failure prints a red banner. A plain git commit --amend is skipped, since pre-commit already linted its staged files.

Manual fallback, for when the hook did not run (a rebase driven by a tool that skips hooks, --no-verify, a hooks-less clone) — this one lints the whole ORIG_HEAD..HEAD span, upstream-only files included, so it is noisier than the hook:

bash
# 1. lint what the rebase moved
# The empty check is load-bearing: a bare `eslint` with no paths lints the whole
# repo (the >2min run this replaces). Don't reach for `xargs -r` — that flag is
# GNU-only and BSD/macOS xargs rejects it.
moved=$(git diff --name-only ORIG_HEAD..HEAD -- '*.ts' '*.tsx' '*.jsx' '*.js' '*.mjs' '*.cjs')
if [ -n "$moved" ]; then echo "$moved" | xargs pnpm exec eslint; fi

# 2. re-read each file you believe you changed, against the new base
git diff origin/main -- <file>

Step 2 matters as much as step 1: lint catches orphaned imports, but a duplicated guard — the same fix landed twice at slightly different offsets and merged cleanly, the second copy unreachable — needs a human reading the diff.

Measuring progress ​

Primary signals: pnpm run parity:api (use --package &lt;name> for one package) and pnpm run parity:test.

Before pushing, also run pnpm parity:api:calls — the call-mismatch ratchet is a separate CI step (.github/workflows/ci.yml, jobs "API comparison (calls)" + "Call-mismatches ratchet") that pnpm parity:api does not run. Because that step runs only in CI, a PR that passes every local check can still fail the rails-comparison job (this happened in #5027). pnpm parity:api:calls runs the lint locally, and since RFC 0083 a plain gating run regenerates output/call-mismatches.json itself before linting (lint-call-mismatches.ts:68-78, via run.sh so the extraction manifests compare.ts reads are refreshed first) — so the bare command is enough. It opts out of that regeneration under --no-regen, API_COMPARE_SKIP_REGEN=1, or any CI value, and only then does it gate whatever artifact is on disk. Reach for API_COMPARE_FORCE=1 pnpm parity:api --calls beforehand when you need to bypass a warm cache (it under-reports vs CI): compare.ts computes the call sets, and writes call-mismatches.json, only under --calls, so a plain pnpm parity:api refreshes nothing this gate reads. (RFC 0084 folded the narrow RFC 0044 ratchet into this one and deleted its separate artifact, baseline and CI step.) The pre-PR checklist in CLAUDE.md is the authoritative workflow; this section explains the machinery behind it.

The baseline is only-shrink: it fails not just on a new mismatch but on a converged one. Fixing a real divergence makes the corresponding baseline entry stale and turns the gate red — e.g. #5027 added the String arm to visit_Arel_Nodes_Over, which started genuinely calling quote_column_name and made the baselined "omits quote_column_name" entry stale. The fix is to delete the now-stale entry from the call-mismatches-exclude/ baseline, NOT to --write/reseed. Reseeding (pnpm parity:api:calls:reseed / lint-call-mismatches.ts --write) rewrites the whole call-mismatches-exclude/ tree, so it buries the one entry you meant to retire in a diff nobody can review; the hand deletion is the whole change. (The cross-package reordering that used to make this worse is fixed — #5183 pinned emission to the code-unit compareKeys order, so a reseed now leaves untouched packages byte-identical.)

Deleting the row also drops that source's unreviewed count below its committed high-water mark, which the gate reports as a STALE high-water mark. The remedy is the narrow one — pnpm parity:api:calls:tighten [&lt;shard>...], where a shard is the mark's &lt;package>/&lt;tsFile .ts→.json> path. It lowers only the named shards (all stale ones when none are named) and writes nothing else, so the "delete the row by hand, never reseed" rule and the gate's own advice agree. A mark is a measurement that only shrinks, so tightening one file is always safe on its own; parity:api:calls:reseed stays for a genuine reseed.

Any PR that converges a visitor or method body toward Rails can trip this, so run the ratchet locally whenever you change a ported method body.

The same gate carries a second only-shrink counter (RFC 0083): the number of baseline entries whose reason is still the verbatim seed string, held against the high-water mark committed in scripts/api-compare/call-mismatches-unreviewed.json. Replacing a seeded placeholder with a real one-line reason lowers the count — that is how review progress registers even when no entry converges. --write lowers the mark and never raises it, and it holds out rows the reseed itself seeded — so reseeding after adding a mismatch turns the gate red until those rows are given real reasons.

The gate arm itself compares only the aggregate count against the mark; it keeps no record of which keys were seeded when the mark was set. So a hand-edited baseline that adds one seeded row while reviewing one old row leaves the count unchanged and passes. The guarantee is therefore that unreviewed debt never grows — not that every individual new entry is forced to carry a real reason (writing one is still the rule, enforced by whoever reviews the baseline diff). pnpm parity:api:calls:unreviewed prints the count and the mark.

Row count is the debt metric; the unreviewed count is not ​

Decision (RFC 0084): the debt this campaign burns down is the baseline's row count. The unreviewed-reason count is a review-hygiene signal, not a debt metric, and is not tracked as one.

The evidence is the two series side by side. Rows went 6,845 (2026-07-17) → 2,218 (2026-08-03) → 2,195 today, because rows converge by deletion — the port starts making the call Rails makes and the row goes stale. Over the same window the unreviewed count barely moved: 2,028 of 2,218 rows (91%) still carried the verbatim RFC 0047 seed weeks after seeding, and it is 2,005 of 2,195 now. Per-row reason wordsmithing is not happening at any rate that matters, and reviewer cycles spent demanding it buy no convergence — the row they would have justified is one a later PR deletes outright.

So, concretely:

  • Do not block a PR on seeded reasons in rows it did not add. Inherited seed strings are not that PR's debt.
  • Do write a real reason for a row you add. That rule stands (CLAUDE.md's pre-PR checklist) — it is what makes the baseline diff reviewable — and @missingRailsCall at the call site remains the alternative. Rows an author chooses to justify keep their reviewed reason; nothing about the reviewed path is withdrawn.
  • Report progress in rows retired, not reasons written.

Nothing mechanical is loosened. The only-shrink row ratchet, the per-file unreviewed high-water marks, the stale-tag arm, the reseed-drift arm and the sharding are all untouched — every one of them has a paid-for incident behind it (#4020, #5869), and the unreviewed marks in particular still stop the count from growing. What changes is what we ask reviewers to spend cycles on.

Decision (this story): the call-mismatch lint is deliberately kept out of pnpm parity:api and documented here instead. Folding it in would make the common narrow run pay for the call-artifact regeneration on every invocation, and the two ratchets gate different artifacts against different baselines; a combined api:gates wrapper was considered and declined as premature — the doc pointer above is the intended fix.

The call-ARGUMENT ratchet (pnpm parity:api:calls:args) ​

RFC 0095 adds a second, independent gate over the same --calls extraction: parity:api:calls compares the SET OF CALL NAMES a body makes, so a port can call where where Rails calls where, hand it a completely different argument list, and stay green. pnpm parity:api:calls:args (lint-call-args.ts, CI step "Call-argument ratchet") ratchets output/call-arg-mismatches.json against the same scripts/api-compare/call-mismatches-exclude/ shards the call-set gate uses — one shard file per source file, holding both dimensions. Its rows carry kind: "args" and are keyed package + tsFile + rubyName + call + rubyArgs; a row with kind absent or "calls" belongs to the call-set gate. Each gate filters the shard to its own kind, which is what keeps RFC 0084's row-count debt metric exactly the call-set rows. (A second parallel tree was the original design and was reversed: sharding both dimensions the same way meant every burndown PR touching one file's arguments and its call set edited two files in two directories, and every rebase ate two conflict surfaces.)

It carries the identical contract to the calls ratchet above and for the same reasons: only-shrink (delete the converged row by hand — do NOT --write/reseed, which rewrites the whole tree), a stale-row arm, a partial-scope rejection, and self-regeneration of the artifact before gating. It does not carry the second, unreviewed-reason counter described above: lint-call-args.ts has no --set-reason and no high-water-mark tree, and its only debt metric is the row count.

Two things are specific to it:

  • It gates shape rows only — argument count, order, literal values, kwarg keys. naming rows, where the two lists differ only in how a ref: identifier is spelled, are the local/parameter-identifier dimension surfacing through the argument comparison. They are never baselined. In every package of the AR require-closure (resolved from ar-closure.ts) and in any other package listed in NAMING_ENROLLED_PACKAGES (only-grow, RFC 0153) the same gate requires each one to be renamed away or, when the naming taxonomy files it permanent, receipted with @missingRailsName &lt;ruby_identifier> — PERMANENT|CONVERGEABLE &lt;story-id> on the enclosing declaration; a receipt on a convergeable pair, or one matching no row, is red. Everywhere else — the actionpack family, rack, trailties — they remain report-only: pnpm parity:api:calls:args:report reports them.
  • A reordering is shape, not naming. The same identifiers in a different order is an argument-ORDER defect (inject_join(list, collector, join_str) ported as injectJoin(nodes, connector, collector)), and it is gated.

The args rows are seeded on main by their own PR. Until then no args row is baselined while the artifact flags hundreds, and that combination is reported and exits 0; the arm closes itself the moment the first row lands, and it cannot swallow a converged dimension (nothing baselined AND nothing flagged is a real green).

What 100% test compare means ​

"100% on parity:test" is name parity and assertion parity, with skipped = 0 — all three, per package. A package whose names all match but whose assertion counters are non-zero is not done: the matched tests assert something other than what Rails asserts. The assertion counters are measured for every compared package — RFC 0105 widened them from activerecord alone to the in-scope closure, and RFC 0126 dropped the scoping set entirely — so the number means the same thing everywhere. Before that, a 100% claim outside the measured set was strictly the weaker claim, because nothing about its assertions was measured at all.

Two things that look like a pass and are not:

  • A pending / it.skip stub. It counts as matched-and-skipped and subtracts from the implemented total (compare.ts:1196, matched - matchedSkipped), so a file full of stubs cannot reach 100%. Stubs are scaffolding for a port, never its end state.
  • A whole-file unported-files row written because "users won't use this." The only admissible reason for a new row is that the trails surface does not exist and is not intended to. The test is about the surface, not about demand for it.

The two worked examples:

  • Admissible — migration/compatibility_test.rb: Migration[7.0] version compatibility is a Rails surface trails deliberately does not ship (PR #5070, closed unmerged). No surface, no denominator.
  • Not admissible — the fixtures.rb / fixture_set / test_fixtures.rb rows (scripts/parity/unported-files/unscoped.ts:77-99, 172 AR tests), whose reason is that "Trails users won't ship YAML fixtures". The surface exists: packages/activerecord/lib/fixtures.ts ships, and CLAUDE.md names fixtures({ … }) the canonical test surface. The row went stale and the tests stayed out of the denominator anyway. That is the failure mode this section exists to prevent — the registry grew from 18 entries in May 2026 to ~200 in August (the tasks repo's archive/trails-docs/infrastructure/parity-convergence-forecast.md, Part 1).

When a specific Rails case is genuinely unportable — it exercises a Ruby-only mechanism inside an otherwise ported file — exclude that case with a case-level tests: entry and a reason, never a whole-file row. A whole-file row takes every future test in that file out of the denominator too.

For an activesupport file, whether it is in the AR closure at all is a separate question from whether it is ported: pnpm parity:test:closure [&lt;test file>] prints in/out — the command ships with RFC 0105's derive-ar-closure-test-manifest story. Out-of-closure is not a licence to add an unported-files row — it changes which denominator the file belongs to, not whether the surface exists.

Assertion-mismatch ratchet ​

pnpm parity:test measures three assertion-level divergences inside name-matched tests — the pair asserts a different number of things (totalAssertionMismatch), the same number but different kinds (totalKindMismatch), or the same kinds with different literal expected values (totalValueMismatch). Without a gate, a newly ported test can assert less than its Rails counterpart and still count as matched, so those totals are pinned by an only-shrink ratchet (RFC 0025):

sh
pnpm parity:test:assertions          # gate

Nothing is committed (RFC 0127). Main's CI uploads convention-comparison.json as the artifact parity-outputs-&lt;sha>, and the gate compares each package's three counters against that artifact for its base — the merge commit's first parent under CI, origin/main locally (scripts/parity/main-artifact.ts). When main has no artifact for that commit the gate recomputes it on a detached worktree of the base. A counter above its base count, or a package the base never measured, fails the gate; shrinkage needs no write, so there is no reseed, no freeze and no mark to conflict on. CI runs the gate in the rails-comparison job ("Assertion-mismatch ratchet"). The arm is aggregate — the guarantee is "assertion-level debt never grows", not that every remaining mismatch has been reviewed. Converging one test while porting another that asserts less is a neutral trade the gate lets through; the reviewer of the diff enforces the stronger rule.

The stale-artifact trap: the counts are read from scripts/test-compare/output/convention-comparison.json — no second extractor. Gating a file written before a sibling PR's tests landed reports movement that never happened, so a plain local run regenerates the artifact itself (pnpm parity:test --json) before gating. --no-regen (what CI uses, since it writes the artifact in the preceding step) gates whatever is on disk. Locally the base is your origin/main ref, so git fetch first or the gate compares against an old base. A partial-scope run is caught separately: if a package in the base is missing from the artifact — a --package filter, an unfetched vendor source — the lint fails rather than reading it as converged.

Once the counters are pinned their burn rate is measurable, which is what the ActiveRecord release estimate needs to price promoting this from a ratchet to a hard release gate (the path gates.ts already took: advisory → ratchet → zero).

"Misplaced" means tests exist but are in the wrong file per Rails layout — they need to be moved, not rewritten. The per-file "Extra" column counts TS tests in the convention file that matched no Rails test — a large value flags a file that has ballooned with bespoke/non-Rails tests (a fidelity smell). Use parity:test --sort-extra (sort the table by Extra descending) and --min-extra=N (hide files under N extra) to triage the worst offenders. --extra lists each file's extra tests under its row, as describe > path > name.

The exact Ruby→TypeScript naming rules parity:api matches on — predicate/bang/ setter forms, token renames, file-path aliases, and the skip list with reasons — are catalogued in docs/ruby-ts-conventions.md. That file is generated from explainConventions() in scripts/parity/conventions.ts (regenerate with pnpm parity:api:conventions); CI runs tsx scripts/parity/conventions-doc.ts --check and fails if it drifts, so it is always current — never hand-edit it, change the rule in conventions.ts instead.

Body pins (source-hash pinning) ​

scripts/api-compare/body-pins/&lt;package>.json records, per name-matched pair, the normalized digest of the vendored Rails body the TS method was ported against. pnpm parity:api:pins (CI: Body-pins gate) then reports DRIFT when a bump to vendor/rails changes a pinned body, and STALE when a pinned method is removed or renamed.

Floor policy: the --pin-all floor is taken. The policy was organic until first release, but a vendor bump against an empty manifest reports no drift at all, so the whole-surface floor was seeded against rails v8.0.2 before the first bump (RFC 0159-versioned-vendor-layout): every matched pair is pinned at the digest of the tree every existing port was written against, and each pin records the upstream ref it was taken at. A floor pin carries no reason — it is only a "this is the tree we ported against" claim, weaker than a verified port. ref is the tag at the pin's last write: a bump that leaves a body's digest unchanged does not rewrite its pin, so ref can trail the vendored tag without meaning anything is stale. On top of the floor, convergence and port stories re-pin the pairs they verify; that pin is a real "a human verified this TS port matches this exact vendored Rails body" claim, recorded via --pin:

sh
API_COMPARE_FORCE=1 pnpm parity:api   # refresh output/body-hashes.json
pnpm tsx scripts/api-compare/body-pins.ts --pin activerecord/lib/active_record/relation.rb

Run that as the last step of any convergence/port story, once the port is verified faithful against vendor/rails, and set the entry's reason to the story id or PR that verified it. Re-pinning preserves an existing reason. When a Rails bump reports drift, re-verify the port against the new upstream body before re-pinning — never re-pin to silence the gate.

Re-pinning is a step of every vendor bump. After the bump, the gate's DRIFT list is the worklist: re-verify each drifted port against the new upstream body, then re-pin its file. pnpm parity:api:pins:all re-runs --pin-all, which pins newly matched pairs and re-pins every drifted one at once — use it only once the drift worklist is burnt down, never to silence the gate. Pins keep their reason across a re-pin.

A drift worklist too large for the bump PR goes in the bump ledger (RFC 0191 § 3): scripts/parity/bump-ledger/&lt;source>.json, one row per drifted or removed pair, seeded in the PR that moves the source's ref. The body-pins gate reports a ledgered pair and passes it; pnpm parity:api:pins:ledger (CI: Bump-ledger gate) reds a row that no longer names a live DRIFT or STALE pin, a row added without a ref move, a bump PR's ledger that differs from the recomputed seed, and a body-pins/&lt;package>.json edit forked before a ref move. --pin &lt;ruby-file> and --prune delete the rows they clear; the ledger only shrinks.

When the gate fails:

  • DRIFT — the vendored body changed. Re-verify the port, then re-pin that file with --pin. During a bump, a DRIFT pair the bump PR did not converge is a ledger row, not a red: the gate reports it as ledger and passes. The burn-down story that re-verifies it runs --pin &lt;ruby-file>, which clears the pin's DRIFT and deletes the row in the same write. Never re-pin to silence the gate, ledgered or not: a --pin is the claim that the port was read against the new body.
  • STALE — the pinned method was removed or renamed upstream (or the TS side no longer name-matches). Once you have confirmed the pair is genuinely gone, pnpm tsx scripts/api-compare/body-pins.ts --prune drops every unresolved pin so the removal doesn't require hand-editing the ~10k-entry floor manifest. --prune never touches a drifted pin.
  • PARTIAL scope — the artifact was built with a --package filter; rebuild with API_COMPARE_FORCE=1 pnpm parity:api before pinning or gating.

Secondary signal: pnpm test:types — Vitest typecheck suites in packages/*/dx-tests/ that pin the public type contract and encode DX gaps as assertions. When a gap closes, the assertion flips. A dedicated DX Type Tests CI job runs on every push, as does a Virtualized DX Type Tests job covering packages/activerecord/virtualized-dx-tests/ (compiled by trails-tsc).

The canonical manual-declare reference is packages/activerecord/dx-tests/declare-patterns.test-d.ts; the zero-declare virtualized reference is packages/activerecord/virtualized-dx-tests/virtualized-patterns.test-d.ts. Prefer the virtualized form for new model code (see README).