ruby-anything 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +12 -0
  2. package/.claude-plugin/plugin.json +7 -0
  3. package/.mcp.json +8 -0
  4. package/LICENSE +21 -0
  5. package/README.md +82 -2
  6. package/adapters/node/harness.mjs +324 -0
  7. package/adapters/node/package-lock.json +26 -0
  8. package/adapters/node/package.json +7 -0
  9. package/adapters/polyglot/harness.py +350 -0
  10. package/adapters/polyglot/lang_csharp.py +222 -0
  11. package/adapters/polyglot/lang_go.py +283 -0
  12. package/adapters/polyglot/lang_java.py +510 -0
  13. package/adapters/polyglot/lang_kotlin.py +133 -0
  14. package/adapters/polyglot/lang_php.py +156 -0
  15. package/adapters/polyglot/lang_ruby.py +148 -0
  16. package/adapters/polyglot/lang_rust.py +430 -0
  17. package/adapters/polyglot/lang_swift.py +337 -0
  18. package/adapters/python/harness.py +417 -0
  19. package/bin/ruby-anything.js +10 -0
  20. package/docs/assets/how-it-works-dark.svg +51 -0
  21. package/docs/assets/how-it-works-light.svg +51 -0
  22. package/harness/ruby_replay.rb +144 -0
  23. package/package.json +51 -4
  24. package/skills/ruby-anything/SKILL.md +130 -0
  25. package/skills/ruby-anything/frontend.md +64 -0
  26. package/skills/ruby-anything/languages/csharp.md +43 -0
  27. package/skills/ruby-anything/languages/go.md +36 -0
  28. package/skills/ruby-anything/languages/java.md +54 -0
  29. package/skills/ruby-anything/languages/javascript.md +50 -0
  30. package/skills/ruby-anything/languages/kotlin.md +27 -0
  31. package/skills/ruby-anything/languages/php.md +47 -0
  32. package/skills/ruby-anything/languages/python.md +49 -0
  33. package/skills/ruby-anything/languages/rust.md +31 -0
  34. package/skills/ruby-anything/languages/swift.md +27 -0
  35. package/skills/ruby-anything/whole-app.md +168 -0
  36. package/src/adapters.js +60 -0
  37. package/src/analyze.js +183 -0
  38. package/src/app.js +697 -0
  39. package/src/cli.js +75 -0
  40. package/src/detect.js +266 -0
  41. package/src/go.js +139 -0
  42. package/src/mcp.js +89 -0
  43. package/src/setup.js +106 -0
  44. package/src/units.js +444 -0
  45. package/src/util.js +312 -0
@@ -0,0 +1,144 @@
1
+ # ruby-anything replay harness: runs a Ruby port against recorded cases.
2
+ #
3
+ # Request on stdin: {"code_file", "receiver" ("Pricing" / "Pricing::Discount"), "method",
4
+ # "instance" (true = Receiver.new.method), "rails_root" (boot Rails first, optional),
5
+ # "command" ("replay" | "bench"), "cases" [{ref, args, kwargs}], "iterations"}
6
+ # Events on stdout: plan, case {ref, outcome, stdout, stderr, effects, duration_us}, done.
7
+ require "json"
8
+ require "stringio"
9
+ require "tmpdir"
10
+ require "digest"
11
+ require "set"
12
+
13
+ REAL_STDOUT = $stdout.dup
14
+ REAL_STDOUT.sync = true
15
+
16
+ def emit(event, **data)
17
+ REAL_STDOUT.write(JSON.generate(data.merge(event: event)) + "\n")
18
+ end
19
+
20
+ def encode(value)
21
+ case value
22
+ when nil, true, false, String, Integer then value
23
+ when Symbol then value.to_s
24
+ when Float
25
+ return { "$float" => "nan" } if value.nan?
26
+ return { "$float" => value.positive? ? "inf" : "-inf" } if value.infinite?
27
+ return { "$float" => "-0.0" } if value.zero? && (1.0 / value).negative?
28
+ return { "$float" => value.to_s } if value == value.floor && value.abs > 2**53
29
+
30
+ value
31
+ when Array then value.map { |v| encode(v) }
32
+ when Hash then value.to_h { |k, v| [ k.to_s, encode(v) ] }
33
+ when Set then { "$set" => value.map { |v| encode(v) }.sort_by { |v| JSON.generate(v) } }
34
+ else
35
+ if defined?(BigDecimal) && value.is_a?(BigDecimal) then value.to_f
36
+ elsif value.respond_to?(:as_json) then encode(value.as_json)
37
+ else { "$repr" => value.inspect[0, 200] }
38
+ end
39
+ end
40
+ end
41
+
42
+ def decode(value)
43
+ case value
44
+ when Array then value.map { |v| decode(v) }
45
+ when Hash
46
+ if value.key?("$float")
47
+ { "nan" => Float::NAN, "inf" => Float::INFINITY, "-inf" => -Float::INFINITY, "-0.0" => -0.0 }.fetch(value["$float"]) { Float(value["$float"]) }
48
+ elsif value.key?("$bytes") then value["$bytes"].unpack1("m0").b
49
+ elsif value.key?("$set") then Set.new(decode(value["$set"]))
50
+ elsif value.key?("$tuple") then decode(value["$tuple"])
51
+ else value.transform_values { |v| decode(v) }
52
+ end
53
+ else value
54
+ end
55
+ end
56
+
57
+ def snapshot(root)
58
+ Dir.glob("**/*", File::FNM_DOTMATCH, base: root).filter_map do |rel|
59
+ full = File.join(root, rel)
60
+ next unless File.file?(full)
61
+
62
+ data = File.binread(full)
63
+ { "path" => rel, "size" => data.bytesize, "sha256" => Digest::SHA256.hexdigest(data) }
64
+ end.sort_by { |e| e["path"] }
65
+ end
66
+
67
+ request = JSON.parse($stdin.read)
68
+ $stdout = StringIO.new
69
+ begin
70
+ if request["rails_root"]
71
+ ENV["RAILS_ENV"] ||= "test"
72
+ require File.join(request["rails_root"], "config", "environment")
73
+ end
74
+ load(request.fetch("code_file"))
75
+ rescue Exception => e # rubocop:disable Lint/RescueException
76
+ $stdout = STDOUT
77
+ emit("fatal", message: "loading #{request['code_file']} failed: #{e.class}: #{e.message}")
78
+ exit 2
79
+ ensure
80
+ $stdout = STDOUT
81
+ end
82
+
83
+ receiver = begin
84
+ Object.const_get(request.fetch("receiver"))
85
+ rescue NameError
86
+ emit("fatal", message: "#{request['receiver']} is not defined in #{request['code_file']}")
87
+ exit 2
88
+ end
89
+ target = request["instance"] ? receiver.new : receiver
90
+ method = request.fetch("method")
91
+ unless target.respond_to?(method)
92
+ emit("fatal", message: "#{request['receiver']}#{request['instance'] ? '#' : '.'}#{method} is not defined")
93
+ exit 2
94
+ end
95
+
96
+ call = lambda do |c|
97
+ args = decode(c.fetch("args", []))
98
+ kwargs = decode(c.fetch("kwargs", {})).transform_keys(&:to_sym)
99
+ kwargs.empty? ? target.public_send(method, *args) : target.public_send(method, *args, **kwargs)
100
+ end
101
+
102
+ emit("plan", total: request["cases"].size, runtime: "ruby #{RUBY_VERSION}")
103
+ case request.fetch("command", "replay")
104
+ when "replay"
105
+ request["cases"].each do |c|
106
+ out = StringIO.new
107
+ err = StringIO.new
108
+ Dir.mktmpdir("ra-case-") do |scratch|
109
+ Dir.chdir(scratch) do
110
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
111
+ $stdout, $stderr = out, err
112
+ outcome =
113
+ begin
114
+ { "kind" => "return", "value" => encode(call.call(c)) }
115
+ rescue StandardError, SystemStackError, NoMemoryError => e
116
+ line = e.backtrace&.find { |f| f.start_with?(request["code_file"]) }&.split(":")&.[](1).to_i
117
+ { "kind" => "raise", "type" => e.class.name, "message" => e.message, "raise_line" => line }
118
+ ensure
119
+ $stdout, $stderr = STDOUT, STDERR
120
+ end
121
+ took = (Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) - started) / 1000
122
+ emit("case", ref: c["ref"], outcome: outcome, stdout: out.string, stderr: err.string,
123
+ effects: snapshot(scratch), duration_us: took)
124
+ end
125
+ end
126
+ end
127
+ when "bench"
128
+ n = request.fetch("iterations", 30).to_i.clamp(1, 10_000)
129
+ request["cases"].each do |c|
130
+ $stdout = StringIO.new
131
+ samples = Array.new(n) do
132
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
133
+ begin
134
+ call.call(c)
135
+ rescue StandardError
136
+ nil
137
+ end
138
+ Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) - t0
139
+ end
140
+ $stdout = STDOUT
141
+ emit("case", ref: c["ref"], samples_ns: samples)
142
+ end
143
+ end
144
+ emit("done")
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "ruby-anything",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Migrate any app (TypeScript, JavaScript, Python, Go, Java/Spring, Kotlin, C#, PHP, Rust, Swift) to Ruby on Rails with Hotwire, Tailwind and daisyUI, one piece at a time, checked against the original's recorded behavior at every step.",
5
+ "keywords": [
6
+ "ruby",
7
+ "rails",
8
+ "hotwire",
9
+ "turbo",
10
+ "stimulus",
11
+ "tailwind",
12
+ "daisyui",
13
+ "migration",
14
+ "mcp",
15
+ "claude-code",
16
+ "codex"
17
+ ],
18
+ "license": "MIT",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/akkisavi/rust-anything.git",
22
+ "directory": "packages/ruby-anything"
23
+ },
24
+ "homepage": "https://github.com/akkisavi/rust-anything#readme",
25
+ "bugs": {
26
+ "url": "https://github.com/akkisavi/rust-anything/issues"
27
+ },
28
+ "bin": {
29
+ "ruby-anything": "bin/ruby-anything.js"
30
+ },
31
+ "files": [
32
+ "bin",
33
+ "src",
34
+ "harness",
35
+ "adapters",
36
+ "skills",
37
+ ".claude-plugin",
38
+ ".mcp.json",
39
+ "README.md",
40
+ "LICENSE",
41
+ "docs"
42
+ ],
43
+ "scripts": {
44
+ "prepack": "node scripts/sync-adapters.js",
45
+ "test": "node test/run.js"
46
+ },
47
+ "engines": {
48
+ "node": ">=18"
49
+ },
50
+ "dependencies": {
51
+ "typescript": "5.9.3"
52
+ }
53
+ }
@@ -0,0 +1,130 @@
1
+ ---
2
+ name: ruby-anything
3
+ description: Migrate an app or a function written in TypeScript/JavaScript, Python, Go, Java/Spring Boot, Kotlin, C#, PHP, Rust or Swift to Ruby on Rails 8 with Hotwire (Turbo + Stimulus), Tailwind CSS and daisyUI, with the ruby-anything CLI or MCP tools - plan, grill the user, record the original's behavior, put a Rails front door in front of it, port route by route and unit by unit, diff, gate, and lift to a pure Rails app. Use when asked to rewrite, port, convert or migrate code or an app to Ruby or Rails, or to plan such a migration.
4
+ ---
5
+
6
+ # Migration to Ruby on Rails with ruby-anything
7
+
8
+ ruby-anything gives you ground truth; you write the Ruby. The original's recorded behavior is the
9
+ spec, not its tests and not your reading of the code. Move one piece at a time, keep the app
10
+ running at every step, and call a piece done only when `gate` passes.
11
+
12
+ **Target stack** (unless the user's ADRs say otherwise): Rails 8 (7.2 works), Hotwire (Turbo
13
+ Drive, Frames, Streams + Stimulus) with importmap, Tailwind CSS v4 through `tailwindcss-rails` with
14
+ daisyUI 5, ActiveRecord, Minitest, Solid Queue/Cache/Cable, the Rails authentication generator.
15
+
16
+ **Whole app** (the usual request): read [whole-app.md](whole-app.md) first and follow it. It
17
+ grills the user on the decisions, records the whole app over HTTP, puts a Rails front door in
18
+ front of the original, moves routes one at a time, and lifts to a pure Rails app. For every page
19
+ you build, read [frontend.md](frontend.md): how React/Vue/Angular/templates map to ERB + Turbo +
20
+ Stimulus + daisyUI.
21
+
22
+ **Before porting any code, read the file for its language** in [languages/](languages/): how
23
+ its constructs map to Ruby and the traps that made recorded cases differ.
24
+ [python.md](languages/python.md), [javascript.md](languages/javascript.md) (TS and JS),
25
+ [go.md](languages/go.md), [java.md](languages/java.md) (Spring Boot), [kotlin.md](languages/kotlin.md),
26
+ [csharp.md](languages/csharp.md) (ASP.NET Core), [php.md](languages/php.md) (Laravel),
27
+ [rust.md](languages/rust.md), [swift.md](languages/swift.md).
28
+
29
+ Tools: the `ruby-anything` CLI, or the same steps as MCP tools (`ruby-anything mcp`): `go`,
30
+ `analyze`, `bridge`, `record`, `diff`, `gate`, `rules`, `app_record`, `app_replay`,
31
+ `app_front_door`, `app_wire`, `app_status`, `app_lift`, `doctor`. If the MCP tools are missing, use
32
+ the CLI. If `ruby-anything` is not installed, ask the user to run `npm i -g ruby-anything` and
33
+ `ruby-anything setup`, then restart the agent. When a step fails because a runtime is missing,
34
+ run `ruby-anything doctor`: it checks each one and prints the fix.
35
+
36
+ Recording runs the original's real code. Work on a copy, with a test database
37
+ (`--db-reset "<command>"`). Never point it at production data.
38
+
39
+ ## The one command: `go`
40
+
41
+ ```sh
42
+ ruby-anything go # 1st run: analyze -> rails/port/PLAN.md + TASK.md (grill the user)
43
+ ruby-anything go -- python3 app.py # once DECISIONS.md has ADRs: record the app, build the front door, replay
44
+ ruby-anything go # every later run: replay, fallback rate, next route -> TASK.md
45
+ ```
46
+
47
+ Each run moves to the next stage and writes `rails/port/TASK.md`. Do what it says, then run `go`
48
+ again. Report its stage and next step to the user at each checkpoint.
49
+
50
+ ## 1. Plan, then stop
51
+
52
+ ```sh
53
+ ruby-anything analyze <repo> # people: rails/port/PLAN.md
54
+ ruby-anything analyze <repo> --json # you: schema ruby-anything/analyze@1
55
+ ```
56
+
57
+ - Present the shape, the waves (1 models, 2 business logic, 3 routes/controllers, 4 views, 5 jobs
58
+ and mailers, 6 lift) and the `start_here` units.
59
+ - Call out dependencies with no Rails equivalent (`rails: null`). Do not hand-roll a missing gem
60
+ silently: research it (whole-app.md step 2) and flag it.
61
+ - Ask the decisions `analyze` lists (whole-app.md step 1). **Wait for the user's approval of the
62
+ plan and the decisions before writing Ruby.**
63
+
64
+ ## 2. Port one unit (a function)
65
+
66
+ Units are the original's functions: pricing rules, parsers, validators, formatters. Their Ruby
67
+ lives in `rails/app/services/<module>.rb` as module methods (or a class for stateless service
68
+ objects).
69
+
70
+ ```sh
71
+ ruby-anything bridge <repo> <unit-id> # Ruby skeleton + rails/port/TASK.md; never overwrites a method
72
+ ruby-anything record <repo> <unit-id> # the original's behavior on edge cases -> rails/port/cases/*.jsonl
73
+ ruby-anything record <repo> <unit-id> --inputs real.jsonl # {"fn": name, "args": [...]} per line
74
+ ```
75
+
76
+ **A port keeps behavior, bugs included.** Port a known bug as it is; fix it in its own change
77
+ after `gate` passes, with each case it changes in `rails/port/known-diffs.jsonl`
78
+ (`{"unit", "args", "actual", "reason"}`) and the user's yes.
79
+
80
+ Before writing code, run `ruby-anything rules <repo>` and follow every rule. When the user
81
+ corrects how the port behaves, add it right away: `ruby-anything rules <repo> --add "<rule>"`.
82
+
83
+ - Read each risk the plan lists for the unit, at its `file:line`.
84
+ - Errors: raise where the original raises. `diff` maps error families across languages
85
+ (ValueError / IllegalArgumentException / ArgumentException -> `ArgumentError`, KeyError /
86
+ NoSuchElementException -> `KeyError`, IndexError / IndexOutOfBounds -> `IndexError`,
87
+ ZeroDivisionError / ArithmeticException -> `ZeroDivisionError`, plain Error / RuntimeException ->
88
+ `RuntimeError`). Use the original's own class name (`class InvalidCoupon < StandardError`) when
89
+ the original defines one. Messages are compared only with `diff --messages`; keep them anyway.
90
+ - Numbers: keep ints ints and floats floats; `diff` tells `1` from `1.0`. Watch rounding,
91
+ integer division and modulo signs (the language file lists each trap).
92
+ - Ordered output: Ruby hashes keep insertion order like JS objects and Python dicts; sort where
93
+ the original sorts, never where it does not.
94
+ - Regex: Ruby's `\w`, `\d`, `\b` are ASCII-only unless you use `\p{}` classes; Python 3 and .NET
95
+ are Unicode by default. Record non-ASCII inputs when patterns touch user text.
96
+ - Use Ruby and ActiveSupport idioms (`sum`, `each_with_object`, `group_by`, `presence`,
97
+ `in_groups_of`) instead of transliterating loops, as long as `diff` stays N/N.
98
+ - Add a Minitest test in `rails/test/services/` for the cases you reason about.
99
+
100
+ ## 3. Prove it
101
+
102
+ ```sh
103
+ ruby-anything diff <repo> <unit-id> # must be N/N; groups mismatches and names where each first differs
104
+ ```
105
+
106
+ A mismatch is a behavior difference: fix the port, never the recording. When `diff` says the port
107
+ is **stalled** (three changes to the port in a row gained no matching case), stop editing: show the
108
+ user the remaining mismatches and ask. They may know the rule you are missing.
109
+
110
+ ## 4. Done means gate passes
111
+
112
+ ```sh
113
+ ruby-anything gate <repo> <unit-id> # one unit
114
+ ruby-anything gate <repo> --all # every bridged unit
115
+ ruby-anything gate <repo> --app # the whole app: units, bin/rails test, rubocop, brakeman, replay
116
+ ```
117
+
118
+ Unit gate: recorded, recording untouched (an edited `cases.jsonl` fails), recording fresh (the
119
+ original changed -> record again), Ruby syntax, method defined, no `NotImplementedError`/`TODO`
120
+ stubs, no debugger calls, results computed (recorded answers written into the code fail), the port
121
+ at most 3x the original's lines plus 50, every `raise`/`throw` in the original reached by a
122
+ recorded case (add one with `record --inputs` when gate names it), tests and assertions never fewer
123
+ than at the last passing gate, rubocop clean, every recorded case matching. Each failed check
124
+ carries a `fix`: run that first.
125
+
126
+ Then report to the user, and **wait for their go-ahead before the next unit or route**:
127
+
128
+ - what changed (files, functions, routes, views),
129
+ - gate output, diff counts, replay result and fallback rate,
130
+ - behavior differences or risks left, and what is left in the plan.
@@ -0,0 +1,64 @@
1
+ # Frontend: any UI to ERB + Turbo + Stimulus + Tailwind + daisyUI
2
+
3
+ The server renders HTML; Turbo makes it feel like a SPA; Stimulus adds the small behaviors; daisyUI
4
+ gives the components. No React, no JSON-for-the-UI layer, no client router. Replay compares the
5
+ pages by visible text (ADR), so keep every piece of content and every flow; the markup is yours.
6
+
7
+ ## Setup (front-door does most of it)
8
+
9
+ - `app/assets/tailwind/application.css`:
10
+ ```css
11
+ @import "tailwindcss";
12
+ @plugin "./daisyui.mjs" { themes: light --default, dark --prefersdark; }
13
+ ```
14
+ `daisyui.mjs` and `daisyui-theme.mjs` sit next to it (downloaded from the daisyUI releases;
15
+ Tailwind's standalone CLI loads them without Node). Run `bin/dev` (or `bin/rails tailwindcss:watch`)
16
+ while editing views.
17
+ - Theme: `<html data-theme="light">` in the layout; a theme switcher is a Stimulus controller that
18
+ sets `document.documentElement.dataset.theme` and stores it in a cookie.
19
+ - Layout: daisyUI `navbar` (or `drawer` for side navigation) with the original's links, `main`
20
+ with `container mx-auto p-4`, flash messages as `alert alert-success` / `alert-error`.
21
+
22
+ ## Mapping
23
+
24
+ | Original | Rails |
25
+ |---|---|
26
+ | Page / route component (React, Vue, Angular, Svelte, Next.js page) | Controller action + `app/views/<resource>/<action>.html.erb` |
27
+ | Reusable component (`<ProductCard>`) | Partial `_product_card.html.erb` (or a ViewComponent once repeated with logic) |
28
+ | Props | Partial locals: `render "product_card", product: p` |
29
+ | Client router links (`<Link>`, `router.push`) | `link_to` / `button_to`; Turbo Drive does the SPA navigation |
30
+ | `useState` / `ref` for UI-only state (open, tab, toggle) | Stimulus controller with `static values` and `targets` |
31
+ | Fetch-then-render (`useEffect(fetch)`, SWR, React Query) | Render on the server; lazy parts in `<turbo-frame src=... loading="lazy">` |
32
+ | Form with client-side submit + JSON API | `form_with model:`; errors re-render with `status: :unprocessable_entity` |
33
+ | Optimistic update / live list | Turbo Stream response (`turbo_stream.append/replace/remove`) |
34
+ | WebSocket / polling updates | `turbo_stream_from @room` + `broadcasts_to` on the model (Action Cable) |
35
+ | Modal | daisyUI `modal` (`<dialog>`) opened by a Stimulus controller, content in a `turbo-frame id="modal"` |
36
+ | Infinite scroll / "load more" | Turbo Frame with `loading="lazy"` for the next page |
37
+ | Debounced search-as-you-type | Stimulus controller that submits the form after 300 ms; results in a Turbo Frame |
38
+ | Client-side validation (zod, yup) | ActiveModel validations, HTML5 `required`/`pattern`; daisyUI `validator` class |
39
+ | CSS modules / styled-components / Bootstrap classes | Tailwind utilities + daisyUI components |
40
+ | Global store (Redux, Pinia, Context) | The server is the store; session for per-user state; Stimulus outlets for cross-controller UI |
41
+ | i18n strings | `config/locales/*.yml` + `t(".key")` |
42
+ | Server templates (Jinja, Thymeleaf, Blade, EJS, Razor, Go templates) | ERB: `{{ x }}` -> `<%= x %>`, `{% for %}` -> `<% each do %>`, blocks/sections -> `content_for` / `yield`, includes -> partials |
43
+
44
+ ## daisyUI components to reach for
45
+
46
+ `btn` (`btn-primary`, `btn-ghost`, `btn-sm`), `card` (`card-body`, `card-title`, `card-actions`),
47
+ `navbar`, `menu`, `drawer`, `table` (`table-zebra`), `badge`, `alert`, `modal`, `tabs`, `dropdown`,
48
+ `input`/`select`/`textarea` with `fieldset` + `label` (daisyUI 5), `join` for grouped buttons and
49
+ pagination, `stat` for dashboards, `steps` for wizards, `toast` for flash, `skeleton` and
50
+ `loading` for lazy frames.
51
+
52
+ ## Rules
53
+
54
+ - Same URLs, same page titles (`content_for :title`), same headings, labels, button text, table
55
+ columns and empty states as the original: replay checks the text.
56
+ - Forms post to the same paths with the same field names unless an ADR says otherwise; keep
57
+ `name` attributes so recorded POST cases still work.
58
+ - Server-render everything the original showed on first load; only things that were lazy in
59
+ the original become lazy frames.
60
+ - Accessibility: real `<button>`/`<a>`, `<label for>`, `aria-live` on Turbo Stream targets,
61
+ focus moved into modals. daisyUI components are accessible when you use the right element.
62
+ - No inline `<script>`. Behavior goes in `app/javascript/controllers/*_controller.js`
63
+ (`bin/rails generate stimulus name`), pinned by importmap.
64
+ - System tests (`bin/rails generate system_test`) for each flow that has JavaScript behavior.
@@ -0,0 +1,43 @@
1
+ # C# / ASP.NET Core to Ruby
2
+
3
+ Recorder: the polyglot C# adapter (`dotnet` + a generated driver). Static methods are recordable.
4
+ ASP.NET Core minimal API (`app.MapGet`) and attribute-routed controllers are found by `analyze`.
5
+
6
+ ## ASP.NET to Rails
7
+
8
+ | ASP.NET Core | Rails |
9
+ |---|---|
10
+ | `app.MapGet("/x/{id}", ...)` / `[HttpGet("{id}")]` | route + controller action |
11
+ | `Results.Ok(x)` / `return Ok(x)` | `render json: x` |
12
+ | `Results.NotFound()` / `NotFound()` | `head :not_found` (match the recorded body) |
13
+ | `CreatedAtAction(...)` | `render json: x, status: :created, location: ...` |
14
+ | Razor pages / views (`.cshtml`) | ERB views (frontend.md) |
15
+ | Entity Framework `DbContext`, LINQ | ActiveRecord; `Where/Select/OrderBy/Include` -> `where/select/order/includes` |
16
+ | Data annotations (`[Required]`, `[StringLength]`) | `validates` |
17
+ | Identity | Rails authentication generator (password hashes differ: plan a re-hash) |
18
+ | `IOptions<T>` / `appsettings.json` | `config/*.yml` + credentials |
19
+ | `BackgroundService` / Hangfire | Active Job + Solid Queue |
20
+ | System.Text.Json camelCase output | keep camelCase keys |
21
+
22
+ ## Constructs
23
+
24
+ - **Errors**: `ArgumentException`/`ArgumentNullException`/`ArgumentOutOfRangeException` ->
25
+ `ArgumentError`; `InvalidOperationException` -> `RuntimeError`; `KeyNotFoundException` ->
26
+ `KeyError`; `FormatException` (`int.Parse`) -> `ArgumentError`.
27
+ - **Nullable** `int?` -> `nil`; `??` -> `.nil? ? d : x`; `?.` -> `&.`.
28
+ - **LINQ** on collections -> Enumerable (`Aggregate` -> `reduce`, `GroupBy` -> `group_by`,
29
+ `ToDictionary` -> `to_h`/`index_by`, `First()` raises when empty -> `fetch(0)` / raise).
30
+ - **Records / properties** -> `Data.define` / `attr_reader`.
31
+ - **`decimal`** -> `BigDecimal`, never Float.
32
+
33
+ ## Traps
34
+
35
+ - **Rounding**: `Math.Round(2.5) == 2` (banker's rounding by default!) -> `round(half: :even)`;
36
+ `MidpointRounding.AwayFromZero` -> `round`. `ToString("F2")` and string interpolation formats use
37
+ the current culture: the decimal separator can be `,`.
38
+ - Integer overflow wraps unless `checked`; `/` truncates toward zero; `%` takes the dividend's sign.
39
+ - `string.Length` counts UTF-16 units. `string.Split(' ')` keeps empty entries (`split(" ", -1)`
40
+ with a regex in Ruby).
41
+ - `Dictionary<K,V>` enumeration order is insertion order in practice but not guaranteed: sort when a
42
+ recorded case shows an order.
43
+ - `DateTime` without a kind is local time; serialize the way the recording shows.
@@ -0,0 +1,36 @@
1
+ # Go to Ruby
2
+
3
+ Recorder: the polyglot Go adapter (a generated driver per function, `go build`). Frameworks:
4
+ net/http, Gin, Echo, Fiber and chi routes are found by `analyze`.
5
+
6
+ ## Constructs
7
+
8
+ - **Errors as values**: `return 0, fmt.Errorf("bad input %q", s)` -> `raise ArgumentError, ...`
9
+ (the recorder reports a returned non-nil error as a raise). Sentinel errors (`var ErrNotFound =
10
+ errors.New(...)`) -> `class NotFound < StandardError`. `panic` -> `raise` (RuntimeError).
11
+ - **Multiple returns** -> an array or a small `Data.define`, unless the second value is the error.
12
+ - **Zero values**: an unset `int` is `0`, `string` is `""`, a nil slice marshals to JSON `null` while
13
+ an empty slice marshals to `[]`. Match the recorded JSON exactly.
14
+ - **Structs** -> `Data.define` / `Struct`; JSON tags (`json:"user_id,omitempty"`) decide the keys
15
+ and whether zero values are dropped: port `omitempty` with `compact`/explicit checks.
16
+ - **Maps**: iteration order is random in Go; the recorder shows a sorted or noisy order. Sort
17
+ before output wherever the original's output came from a map.
18
+ - **Goroutines/channels** -> sequential code, or Active Job when they were background work.
19
+ - **Handlers**: `w.WriteHeader(201); json.NewEncoder(w).Encode(x)` -> `render json: x, status:
20
+ :created`. Gin `c.JSON(200, gin.H{...})` -> `render json: {...}`. `http.Error(w, msg, 400)` writes
21
+ `msg + "\n"` as text/plain: `render plain: "#{msg}\n", status: :bad_request`.
22
+ - **database/sql, sqlx, GORM** -> ActiveRecord on the same tables.
23
+
24
+ ## Traps
25
+
26
+ - **Integer types**: `int32`/`int64`/`uint8` overflow and wrap; Ruby never does. Port the wrap only
27
+ where a recorded case reaches it. Integer division truncates toward zero (`-7 / 2 == -3`): Ruby
28
+ floors; use `.fdiv(b).truncate`. `%` takes the dividend's sign: `remainder`.
29
+ - **Rounding**: `math.Round(-2.5) == -3` (half away from zero) like Ruby's `round`.
30
+ `math.RoundToEven` -> `round(half: :even)`. `fmt.Sprintf("%.2f")` -> `format("%.2f")`.
31
+ - **Strings are bytes**: `len(s)` counts bytes, `s[i]` is a byte, `for i, r := range s` walks runes.
32
+ Ruby `length` counts characters: use `bytesize` / `byteslice` where the original uses bytes.
33
+ - **`strings.Title`, `strings.ToUpper`** are Unicode-aware like Ruby's `upcase`; `strings.Fields`
34
+ -> `split` (no argument).
35
+ - **Floats in JSON**: Go writes `1` for a float64 holding 1.0; recordings show it as an int.
36
+ - **time.Time** marshals as RFC 3339 with nanoseconds: `iso8601(9)` and trim trailing zeros like Go.
@@ -0,0 +1,54 @@
1
+ # Java / Spring Boot to Ruby
2
+
3
+ Recorder: the polyglot Java adapter (javac + a generated driver). `public static` methods and
4
+ public methods of stateless classes (no instance fields, no constructor arguments, typical
5
+ `@Service`/`@Component` helpers) are recordable; Spring annotations are stripped for the
6
+ recording, and dependency jars in `target/dependency` (`mvn dependency:copy-dependencies`) go on
7
+ the classpath. Classes with injected dependencies are checked through app record/replay.
8
+
9
+ ## Spring to Rails
10
+
11
+ | Spring | Rails |
12
+ |---|---|
13
+ | `@RestController` + `@GetMapping("/x/{id}")` | `get "x/:id"` + controller action, `render json:` |
14
+ | `@Controller` + Thymeleaf template | controller action + ERB view (frontend.md) |
15
+ | `@PathVariable`, `@RequestParam`, `@RequestBody` | `params[:id]`, `params[:q]`, `params.expect(...)` / `params.require().permit()` |
16
+ | `ResponseEntity.status(201).body(x)` | `render json: x, status: :created` |
17
+ | `@ResponseStatus(NOT_FOUND)` exception / `@ControllerAdvice` | `rescue_from` in `ApplicationController` with the same body and status |
18
+ | `@Service` | service object in `app/services` |
19
+ | `@Entity` + `JpaRepository` | ActiveRecord model; derived queries (`findByEmail`) -> `find_by(email:)`; `@Query` -> scopes / `where` |
20
+ | `@Transactional` | `ActiveRecord::Base.transaction do ... end` |
21
+ | Bean Validation (`@NotBlank`, `@Size`, `@Email`) | `validates :x, presence:, length:, format:` |
22
+ | Spring Security | Rails authentication generator + `before_action`; keep bcrypt hashes |
23
+ | `application.properties` / `@Value` | `config/*.yml`, credentials, `ENV.fetch` |
24
+ | `@Scheduled` | Solid Queue recurring jobs (`config/recurring.yml`) |
25
+ | Jackson field names (camelCase) | keep camelCase keys in `render json:` (`as_json` with a key transform or explicit hashes) |
26
+
27
+ ## Constructs
28
+
29
+ - **Errors**: `IllegalArgumentException` -> `ArgumentError`; `IllegalStateException` ->
30
+ `RuntimeError`; `NoSuchElementException` (`Optional.get`, `orElseThrow`) -> `KeyError` or the app's
31
+ own error; `NullPointerException` -> `NoMethodError` (port it only when a recorded case shows it).
32
+ - **Optional** -> `nil` handling; `orElse(d)` -> `|| d` (or `.nil? ? d : x` when false is a value).
33
+ - **Streams**: `stream().filter().map().collect(toList())` -> `select.map`; `Collectors.groupingBy`
34
+ -> `group_by`; `joining(", ")` -> `join(", ")`; `sorted(comparing(X::y))` -> `sort_by(&:y)`.
35
+ - **Records / POJOs** -> `Data.define` / `Struct` / plain classes with `attr_reader`.
36
+ - **Overloads** -> optional or keyword arguments; check every overload's recorded cases.
37
+
38
+ ## Traps
39
+
40
+ - **Integer overflow**: `int` wraps at 2^31 (`Integer.MAX_VALUE + 1` is negative); `long` at 2^63.
41
+ Ruby integers never overflow. Port the wrap (`((x + 2**31) % 2**32) - 2**31`) only where a
42
+ recorded case reaches it.
43
+ - **Integer division** truncates toward zero (`-7 / 2 == -3`); Ruby floors (`-4`). Use
44
+ `(a.fdiv(b)).truncate` or `a.quo(b).truncate`. `%` takes the dividend's sign: use `remainder`.
45
+ - **Rounding**: `Math.round(-2.5) == -2` (half up toward +infinity); `BigDecimal` with
46
+ `RoundingMode.HALF_EVEN` -> `round(half: :even)`; `HALF_UP` -> `round(half: :up)`.
47
+ - **BigDecimal money** -> Ruby `BigDecimal` (require "bigdecimal"); never Float for money.
48
+ - **Strings**: `length()` counts UTF-16 units like JS. `String.format("%.2f")` -> `format("%.2f")`.
49
+ `equals` vs `==`: Ruby `==` compares values.
50
+ - **Regex**: Java `\w` is ASCII unless `UNICODE_CHARACTER_CLASS`: same as Ruby. `matches()` anchors
51
+ the whole string (`\A...\z`); `find()` does not.
52
+ - **HashMap** iteration order is unspecified; `LinkedHashMap` keeps insertion order like Ruby hashes;
53
+ `TreeMap` is sorted (`sort.to_h`). Sort before output where the original used `HashMap` and a
54
+ recorded case shows an order.
@@ -0,0 +1,50 @@
1
+ # TypeScript / JavaScript to Ruby
2
+
3
+ Recorder: the Node adapter (modules are imported; TypeScript is transpiled first). Frameworks:
4
+ Express, Fastify, Koa, NestJS routes are found by `analyze`; React/Vue/Angular/Svelte/Next.js pages
5
+ become ERB views (read frontend.md).
6
+
7
+ ## Constructs
8
+
9
+ - **Errors**: `throw new Error(m)` -> `raise m` (RuntimeError); `TypeError` -> `TypeError`;
10
+ `RangeError` -> `RangeError` (or ArgumentError); custom `class X extends Error` ->
11
+ `class X < StandardError`. A rejected promise is a raise.
12
+ - **null / undefined** -> `nil`. An object key holding `undefined` disappears from `JSON.stringify`;
13
+ `nil` values stay as `null` in Rails' `render json:`. Use `compact` where the original relied on
14
+ undefined keys vanishing.
15
+ - **Numbers**: one `number` type. Integral results come back as ints in recordings; fractional ones
16
+ as floats. `Number.isInteger(5.0)` is true. Return `Integer` where the recording shows ints.
17
+ - **Truthiness**: `0`, `""`, `NaN`, `null`, `undefined` are false in JS; only `nil`/`false` in Ruby.
18
+ `x || default` -> `x.presence || default` for strings, explicit zero checks for numbers. `??` ->
19
+ `x.nil? ? default : x`.
20
+ - **Arrays**: `map/filter/reduce/find/some/every/includes` -> `map/select/reduce/find/any?/all?/include?`.
21
+ `arr.sort()` without a comparator sorts **as strings** (`[10, 9, 1].sort() == [1, 10, 9]`): port
22
+ that as `sort_by(&:to_s)`. `sort((a, b) => a - b)` -> `sort`.
23
+ - **Objects** keep insertion order, except integer-like keys, which JS puts first in ascending
24
+ order. Spread `{...a, ...b}` -> `a.merge(b)`. Optional chaining `a?.b` -> `a&.dig(:b)` / `&.`.
25
+ - **Strings**: `length` and indexes count UTF-16 code units: an emoji is 2. Ruby counts code points.
26
+ Where emoji or astral characters reach a length, slice or index, recorded cases will show it; use
27
+ `s.encode("UTF-16LE").bytesize / 2` for length parity. `substring` swaps reversed arguments;
28
+ `slice` takes negatives. `toUpperCase` is locale-free like `upcase`.
29
+ - **Express**: `req.params` / `req.query` / `req.body` -> `params`; `res.status(201).json(x)` ->
30
+ `render json: x, status: :created`; `res.redirect(path)` -> `redirect_to path` (302 in both);
31
+ middleware -> `before_action` / Rack middleware; `express.static` -> `public/`.
32
+ - **Async**: `await` chains become plain sequential calls; `Promise.all` over I/O -> sequential, or
33
+ threads only when an ADR says latency matters.
34
+ - **Mongoose / Prisma / Sequelize / TypeORM** -> ActiveRecord models; Mongo documents need a
35
+ schema decision (ADR) or the mongoid gem.
36
+
37
+ ## Traps
38
+
39
+ - **Rounding**: `Math.round(-2.5) == -2` (half toward +infinity); Ruby `-2.5.round == -3`. Use
40
+ `(x + 0.5).floor`. `toFixed(2)` rounds the binary value: `(1.005).toFixed(2) == "1.00"`; Ruby
41
+ `format("%.2f", 1.005) == "1.00"` too, but `1.005.round(2) == 1.01`: use `format`.
42
+ - **Integer division**: `7 / 2 == 3.5`; `Math.floor(7 / 2)` floors, `Math.trunc` truncates
43
+ (negative numbers differ). `%` takes the dividend's sign (`-7 % 2 == -1`); Ruby takes the
44
+ divisor's (`1`): use `remainder`.
45
+ - **Regex**: no `u` flag means `\w` is ASCII (same as Ruby). `/g` with `.test()` keeps `lastIndex`
46
+ state between calls: port the bug only if recorded.
47
+ - **Dates**: `new Date(y, m, d)` months start at 0; `Date.parse` of a date-only string is UTC.
48
+ - **parseInt("12px") == 12**; Ruby `Integer("12px")` raises: use `"12px".to_i` (but `to_i` returns 0
49
+ where `parseInt` returns `NaN`).
50
+ - **`==` coercion** (`"1" == 1`): port the coercion explicitly where a recorded case depends on it.
@@ -0,0 +1,27 @@
1
+ # Kotlin to Ruby
2
+
3
+ Recorder: the polyglot Kotlin adapter (kotlinc + the Java driver). Top-level functions are
4
+ recordable. Ktor and Spring (Kotlin) routes are found by `analyze`; read java.md for Spring.
5
+
6
+ ## Constructs
7
+
8
+ - **Null safety**: `String?` -> may be `nil`; `?.` -> `&.`; `?:` -> `||` (when false is not a value)
9
+ or `.nil? ? d : x`; `!!` -> raise `NoMethodError`-like errors only where a recorded case shows it.
10
+ - **Errors**: `require(cond) { msg }` -> `raise ArgumentError, msg unless cond`; `check()` ->
11
+ `RuntimeError` (IllegalStateException); `error(msg)` -> `raise msg`.
12
+ - **Data classes** -> `Data.define` (value equality, `with` for `copy`).
13
+ - **Sealed classes / `when`** -> a `case ... in` pattern match or `case` on class.
14
+ - **Collections**: `map/filter/fold/groupBy/associateBy/sumOf/joinToString` ->
15
+ `map/select/reduce/group_by/index_by/sum/join`. `listOf` is immutable: `freeze` if mutation would
16
+ be a bug.
17
+ - **Ktor**: `get("/x/{id}") { call.respond(HttpStatusCode.OK, x) }` -> route + `render json:`.
18
+
19
+ ## Traps
20
+
21
+ - Same numeric traps as Java: `Int` overflow wraps, `/` truncates toward zero, `%` takes the
22
+ dividend's sign (`remainder`), `roundToInt()` rounds half up toward +infinity (`2.5 -> 3`,
23
+ `-2.5 -> -2`).
24
+ - `String.length` counts UTF-16 units; `substring` throws `StringIndexOutOfBoundsException`
25
+ (-> `IndexError`) where Ruby returns `nil`.
26
+ - `toInt()` on a string raises `NumberFormatException` (-> `ArgumentError`, like `Integer(s)`);
27
+ `toIntOrNull()` -> `Integer(s, exception: false)`.