ruby-anything 0.0.0-stage → 0.2.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.
- package/.claude-plugin/marketplace.json +12 -0
- package/.claude-plugin/plugin.json +7 -0
- package/.mcp.json +8 -0
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/action.yml +56 -0
- package/adapters/node/harness.mjs +348 -0
- package/adapters/node/package-lock.json +26 -0
- package/adapters/node/package.json +7 -0
- package/adapters/polyglot/harness.py +350 -0
- package/adapters/polyglot/lang_csharp.py +222 -0
- package/adapters/polyglot/lang_go.py +283 -0
- package/adapters/polyglot/lang_java.py +510 -0
- package/adapters/polyglot/lang_kotlin.py +133 -0
- package/adapters/polyglot/lang_php.py +156 -0
- package/adapters/polyglot/lang_ruby.py +148 -0
- package/adapters/polyglot/lang_rust.py +430 -0
- package/adapters/polyglot/lang_swift.py +337 -0
- package/adapters/python/harness.py +459 -0
- package/bin/ruby-anything.js +10 -0
- package/docs/assets/how-it-works-dark.svg +51 -0
- package/docs/assets/how-it-works-light.svg +51 -0
- package/harness/ruby_replay.rb +155 -0
- package/package.json +52 -4
- package/skills/ruby-anything/SKILL.md +146 -0
- package/skills/ruby-anything/frontend.md +64 -0
- package/skills/ruby-anything/languages/csharp.md +43 -0
- package/skills/ruby-anything/languages/go.md +36 -0
- package/skills/ruby-anything/languages/java.md +54 -0
- package/skills/ruby-anything/languages/javascript.md +50 -0
- package/skills/ruby-anything/languages/kotlin.md +27 -0
- package/skills/ruby-anything/languages/php.md +47 -0
- package/skills/ruby-anything/languages/python.md +49 -0
- package/skills/ruby-anything/languages/rust.md +31 -0
- package/skills/ruby-anything/languages/swift.md +27 -0
- package/skills/ruby-anything/whole-app.md +204 -0
- package/src/adapters.js +63 -0
- package/src/analyze.js +183 -0
- package/src/app.js +774 -0
- package/src/cli.js +80 -0
- package/src/cli_app.js +251 -0
- package/src/detect.js +266 -0
- package/src/drift.js +124 -0
- package/src/effects.js +145 -0
- package/src/fromtests.js +105 -0
- package/src/go.js +165 -0
- package/src/mcp.js +89 -0
- package/src/setup.js +106 -0
- package/src/units.js +452 -0
- package/src/util.js +312 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# PHP / Laravel to Ruby
|
|
2
|
+
|
|
3
|
+
Recorder: the polyglot PHP adapter (functions and static methods are called through a generated
|
|
4
|
+
driver). Laravel routes (`Route::get`) are found by `analyze`.
|
|
5
|
+
|
|
6
|
+
## Laravel to Rails (they are close cousins)
|
|
7
|
+
|
|
8
|
+
| Laravel | Rails |
|
|
9
|
+
|---|---|
|
|
10
|
+
| `routes/web.php`, `routes/api.php` | `config/routes.rb` (keep the `/api` prefix) |
|
|
11
|
+
| Controller + `Request $request` | controller action + `params` |
|
|
12
|
+
| `return response()->json($x, 201)` | `render json: x, status: :created` |
|
|
13
|
+
| `abort(404)` / `firstOrFail()` | `head :not_found` / `find_by!` + `rescue_from` with the recorded body |
|
|
14
|
+
| Blade (`@extends`, `@section`, `@foreach`, `{{ }}`) | ERB layouts (`yield`/`content_for`), `each`, `<%= %>` (frontend.md) |
|
|
15
|
+
| Eloquent model, relations, scopes, casts | ActiveRecord model, associations, scopes, `attribute`/serializers |
|
|
16
|
+
| Migrations | Rails migrations, but keep the existing tables first (ADR) |
|
|
17
|
+
| Form Requests / `$request->validate([...])` | model validations or a form object |
|
|
18
|
+
| Middleware | `before_action` / Rack middleware |
|
|
19
|
+
| Queues / Jobs | Active Job + Solid Queue |
|
|
20
|
+
| Mailables | Action Mailer |
|
|
21
|
+
| `config()` / `.env` | `config/*.yml`, credentials, `ENV` |
|
|
22
|
+
| Sanctum / Breeze auth | Rails authentication generator; bcrypt hashes carry over (`$2y$` -> `$2a$`) |
|
|
23
|
+
|
|
24
|
+
## Constructs
|
|
25
|
+
|
|
26
|
+
- **Errors**: `InvalidArgumentException` -> `ArgumentError`; `DivisionByZeroError` ->
|
|
27
|
+
`ZeroDivisionError`; `RuntimeException` -> `RuntimeError`; the app's own exceptions keep their
|
|
28
|
+
names.
|
|
29
|
+
- **Arrays are ordered maps**: a PHP array with keys `0..n-1` is a JSON list; with gaps
|
|
30
|
+
(after `unset` or `array_filter`) it becomes a JSON object. Use `array_values` semantics
|
|
31
|
+
(`values`) where the recording shows a list.
|
|
32
|
+
- **null** -> `nil`; `isset($a['k'])` -> `a.key?("k") && !a["k"].nil?`; `empty($x)` is true for
|
|
33
|
+
`0`, `"0"`, `""`, `[]`, `null`.
|
|
34
|
+
- **Strings**: `strlen` counts bytes (`bytesize`); `mb_strlen` counts characters (`length`).
|
|
35
|
+
`.` concatenation -> interpolation.
|
|
36
|
+
|
|
37
|
+
## Traps
|
|
38
|
+
|
|
39
|
+
- **Loose comparison** (`==`, `in_array` without strict): `"1" == 1`, `"abc" == 0` (PHP 7). Port the
|
|
40
|
+
coercion explicitly where a recorded case depends on it.
|
|
41
|
+
- **Rounding**: `round(2.5) == 3` and `round(-2.5) == -3` (half away from zero) like Ruby's `round`.
|
|
42
|
+
`intdiv` truncates toward zero; `%` takes the dividend's sign (`remainder`); `/` returns an int when
|
|
43
|
+
exact (`4 / 2 === 2`) and a float otherwise.
|
|
44
|
+
- **Int overflow** turns into float silently.
|
|
45
|
+
- `json_encode` escapes `/` as `\/` and unicode as `\uXXXX` by default: the body text differs but the
|
|
46
|
+
parsed JSON is equal (replay compares parsed JSON).
|
|
47
|
+
- `sort`, `usort` are not stable before PHP 8.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Python to Ruby
|
|
2
|
+
|
|
3
|
+
Recorder: the Python adapter (functions are imported and called; top-level code runs).
|
|
4
|
+
Frameworks: Flask, FastAPI and Django routes are found by `analyze`.
|
|
5
|
+
|
|
6
|
+
## Constructs
|
|
7
|
+
|
|
8
|
+
- **Errors**: `raise ValueError(...)` -> `raise ArgumentError, "..."`; `KeyError` -> `KeyError`;
|
|
9
|
+
`IndexError` -> `IndexError`; `TypeError` -> `TypeError`; the app's own exception classes ->
|
|
10
|
+
`class Name < StandardError` with the same name.
|
|
11
|
+
- **None** -> `nil`; `Optional[T]` parameters default to `nil`. `x or default` behaves the same
|
|
12
|
+
only when `x` is never `0`, `""`, `[]` or `{}`: Python treats those as false, Ruby does not. Use
|
|
13
|
+
`x.presence || default` or explicit checks.
|
|
14
|
+
- **Truthiness**: `if items:` -> `if items.any?` (or `unless items.empty?`); `if s:` ->
|
|
15
|
+
`unless s.empty?`; `if n:` -> `unless n.zero?`.
|
|
16
|
+
- **Comprehensions** -> `map` / `select` / `filter_map` / `each_with_object`; `dict(zip(a, b))` ->
|
|
17
|
+
`a.zip(b).to_h`; `enumerate` -> `each_with_index`; `sorted(x, key=f)` -> `sort_by` (stable in
|
|
18
|
+
both); `sum` -> `sum`.
|
|
19
|
+
- **Strings**: `len`, slicing and indexes count code points like Ruby `String#length`/`[]`; `s[a:b]`
|
|
20
|
+
-> `s[a...b]`; `s[-1]` works the same; f-strings -> interpolation; `str.split()` with no argument
|
|
21
|
+
-> `split` (both collapse whitespace) but `split(" ")` differs: Python keeps empty strings, Ruby's
|
|
22
|
+
`split(" ")` is awk-style; use `split(/ /, -1)`.
|
|
23
|
+
- **Dicts** keep insertion order like Ruby hashes. String keys stay strings (`"name"`), not symbols,
|
|
24
|
+
when they reach JSON.
|
|
25
|
+
- **Classes**: dataclasses -> `Struct` / `Data.define` or plain classes; `@property` -> reader
|
|
26
|
+
methods; `__eq__`/`__hash__` -> `==`/`eql?`/`hash`.
|
|
27
|
+
- **Django/Flask**: views -> controller actions; `request.args` -> `params`; `jsonify(x)` ->
|
|
28
|
+
`render json: x`; `abort(404)` -> `head :not_found` (or the original's error body); Django ORM ->
|
|
29
|
+
ActiveRecord (`filter` -> `where`, `exclude` -> `where.not`, `get` -> `find_by!`,
|
|
30
|
+
`select_related` -> `includes`).
|
|
31
|
+
|
|
32
|
+
## Traps
|
|
33
|
+
|
|
34
|
+
- **Rounding**: `round(2.5) == 2` (half to even). Ruby `2.5.round == 3`. Use `round(half: :even)`.
|
|
35
|
+
`round(x, 2)` also rounds half to even on the binary value: `round(2.675, 2) == 2.67`.
|
|
36
|
+
- **Division**: `/` always returns a float (`7 / 2 == 3.5`, `4 / 2 == 2.0`); Ruby `7 / 2 == 3`.
|
|
37
|
+
Use `fdiv` or `/ 2.0`. `//` floors: `-7 // 2 == -4` like Ruby's `-7 / 2`.
|
|
38
|
+
- **Modulo** takes the divisor's sign in both languages (`-7 % 2 == 1`): same.
|
|
39
|
+
- **Ints vs floats**: `diff` tells `2` from `2.0`; a function that returns `x / 2` returns floats
|
|
40
|
+
even for even `x`.
|
|
41
|
+
- **Big ints** never overflow in either language: same.
|
|
42
|
+
- **`str.isalpha`/`isdigit`** are Unicode-aware; Ruby `/[[:alpha:]]/` is too, `/[a-z]/` is not.
|
|
43
|
+
- **Regex**: Python `\w`, `\d` match Unicode letters and digits; Ruby's are ASCII-only. Use
|
|
44
|
+
`\p{Word}` / `\p{Nd}` or `[[:alnum:]_]` when the original sees non-ASCII text. `re.match` anchors at
|
|
45
|
+
the start only (`\A` in Ruby); `re.fullmatch` -> `\A...\z`.
|
|
46
|
+
- **Sorting mixed types** raises `TypeError` in Python; Ruby raises `ArgumentError`.
|
|
47
|
+
- **Default mutable arguments** (`def f(x=[])`) share state across calls; port the bug only if a
|
|
48
|
+
recorded case shows it.
|
|
49
|
+
- **Clock and random**: pin them (pass the time in), or ask the user about wildcards.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Rust to Ruby
|
|
2
|
+
|
|
3
|
+
Recorder: the polyglot Rust adapter (rustc + a generated driver). Public functions are recordable.
|
|
4
|
+
Axum and Actix routes are found by `analyze`.
|
|
5
|
+
|
|
6
|
+
## Constructs
|
|
7
|
+
|
|
8
|
+
- **`Result<T, E>`**: `Err(e)` is a raise. Map the error enum's variants to Ruby error classes
|
|
9
|
+
(`class ParseError < StandardError`) or `ArgumentError` for invalid input. `panic!`/`unwrap` on
|
|
10
|
+
`None` -> raise only where a recorded case shows it.
|
|
11
|
+
- **`Option<T>`** -> `nil`; `unwrap_or(d)` -> `|| d` (or explicit nil check when false is a value);
|
|
12
|
+
`map`/`and_then` -> `&.then`.
|
|
13
|
+
- **Structs + impl** -> `Data.define` or classes; traits -> modules (duck typing); enums with data
|
|
14
|
+
-> `Data.define` per variant + `case ... in`.
|
|
15
|
+
- **Iterators**: `iter().filter().map().collect::<Vec<_>>()` -> `select.map`; `fold` -> `reduce`;
|
|
16
|
+
`zip`, `enumerate` -> `zip`, `each_with_index`; `chunks(n)` -> `each_slice(n)`.
|
|
17
|
+
- **Axum/Actix**: `Json(x)` with `(StatusCode::CREATED, Json(x))` -> `render json: x, status:
|
|
18
|
+
:created`; extractors (`Path`, `Query`, `Json`) -> `params`.
|
|
19
|
+
- **serde**: `#[serde(rename_all = "camelCase")]`, `skip_serializing_if` decide the JSON keys.
|
|
20
|
+
|
|
21
|
+
## Traps
|
|
22
|
+
|
|
23
|
+
- **Integer types** wrap in release builds (`wrapping_*` explicitly), panic in debug: the
|
|
24
|
+
recording shows which. Ruby never overflows. `/` truncates toward zero (Ruby floors);
|
|
25
|
+
`%` takes the dividend's sign (`remainder`); `rem_euclid` -> `%` for positive divisors.
|
|
26
|
+
- **Rounding**: `f64::round` rounds half away from zero like Ruby; `round_ties_even` ->
|
|
27
|
+
`round(half: :even)`. `format!("{:.2}", x)` rounds half to even on the binary value.
|
|
28
|
+
- **Strings**: `len()` counts bytes (`bytesize`); `chars().count()` counts code points (`length`).
|
|
29
|
+
Slicing by byte offsets panics on a char boundary.
|
|
30
|
+
- **HashMap** iteration order is random: sort where the output came from one; `BTreeMap` is sorted.
|
|
31
|
+
- **Float formatting**: `1.0_f64.to_string() == "1"`; Ruby `1.0.to_s == "1.0"`.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Swift to Ruby
|
|
2
|
+
|
|
3
|
+
Recorder: the polyglot Swift adapter (swiftc + a generated driver). Free functions and static
|
|
4
|
+
methods are recordable. Vapor routes are checked through app record/replay.
|
|
5
|
+
|
|
6
|
+
## Constructs
|
|
7
|
+
|
|
8
|
+
- **`throws`**: `throw ValidationError.empty` -> `raise ValidationError, "empty"` with a matching
|
|
9
|
+
Ruby class per error enum, or `ArgumentError` for plain invalid input.
|
|
10
|
+
- **Optionals**: `String?` -> `nil`; `if let`/`guard let` -> `return ... if x.nil?`; `??` ->
|
|
11
|
+
`.nil? ? d : x`; force unwrap `!` -> raise only where a recorded case shows it.
|
|
12
|
+
- **Structs/enums**: value types -> `Data.define`; enums with associated values -> `Data.define`
|
|
13
|
+
per case + `case ... in`; `Codable` keys decide JSON names (`CodingKeys`).
|
|
14
|
+
- **Collections**: `map/filter/reduce/compactMap/first(where:)/sorted(by:)` ->
|
|
15
|
+
`map/select/reduce/filter_map/find/sort_by`.
|
|
16
|
+
- **Vapor**: `app.get("x", ":id") { req in ... }` -> route + action; `req.parameters.get("id")` ->
|
|
17
|
+
`params[:id]`; `Abort(.notFound)` -> `head :not_found` with the recorded body.
|
|
18
|
+
|
|
19
|
+
## Traps
|
|
20
|
+
|
|
21
|
+
- **Integer overflow traps** (crashes) instead of wrapping; `&+` wraps. `/` truncates toward zero
|
|
22
|
+
(Ruby floors); `%` takes the dividend's sign (`remainder`).
|
|
23
|
+
- **Rounding**: `rounded()` is half away from zero (Ruby `round`); `.toNearestOrEven` ->
|
|
24
|
+
`round(half: :even)`. `String(format: "%.2f")` -> `format("%.2f")`.
|
|
25
|
+
- **Strings**: `count` counts grapheme clusters (an emoji with a skin tone is 1); Ruby `length`
|
|
26
|
+
counts code points: use `s.grapheme_clusters.length`. Indexing uses `String.Index`, not ints.
|
|
27
|
+
- **Dictionary** order is random: sort where the output came from one.
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# Whole app to a pure Rails app
|
|
2
|
+
|
|
3
|
+
The goal: a standalone Rails 8 app (Hotwire, Tailwind, daisyUI) that does what the original does,
|
|
4
|
+
with the original kept only as reference. The app stays runnable at every step: a Rails **front
|
|
5
|
+
door** owns the entry point early and proxies whatever is not ported yet to the original, routes
|
|
6
|
+
move to Rails one at a time, and the **lift** at the end removes the proxy. The user makes the
|
|
7
|
+
decisions; you find the facts.
|
|
8
|
+
|
|
9
|
+
Everything for the port lives in `<repo>/rails/`: the Rails app itself, and `rails/port/` with
|
|
10
|
+
`PLAN.md`, `plan.json`, `MAP.md`, `DECISIONS.md`, `GLOSSARY.md`, `HANDOFF.md`, `RULES.md`,
|
|
11
|
+
`research/`, `cases/` (unit recordings), `app-cases/` (HTTP recordings) and `TASK.md`.
|
|
12
|
+
|
|
13
|
+
## The map
|
|
14
|
+
|
|
15
|
+
A whole-app port outlasts one session, so `rails/port/MAP.md` carries it between sessions: the
|
|
16
|
+
goal, an index of the ADRs, every route and unit of the plan with its state (`open`,
|
|
17
|
+
`claimed by <session> <date>`, `done`), open questions, and what is out of scope. It points to
|
|
18
|
+
the other files and never copies them.
|
|
19
|
+
|
|
20
|
+
A session **claims** one route or unit before it starts, ports it, and marks it `done` with its
|
|
21
|
+
gate and replay results. A new session starts by reading `MAP.md`, then `HANDOFF.md`.
|
|
22
|
+
`ruby-anything app status <repo> --write` generates `rails/port/PORT_MAP.md` from what is measured
|
|
23
|
+
(fallback rate, wired routes, unit gates); check `MAP.md` against it at every checkpoint.
|
|
24
|
+
|
|
25
|
+
## 1. Grill the user
|
|
26
|
+
|
|
27
|
+
Interview the user until every decision the port depends on is settled. Map them as a **design
|
|
28
|
+
tree**: each decision branches into the ones that hang off it. Ask in **rounds**: a round is every
|
|
29
|
+
decision whose prerequisites are settled. Number each question, give your recommended answer,
|
|
30
|
+
and word it so "yes" accepts it:
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
❓ **Q1** - **<title>**: <question, with the choices>
|
|
34
|
+
|
|
35
|
+
➡️ <recommended answer>
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Facts are yours, never the user's: run `analyze`, read the code, run the app, send subagents.
|
|
39
|
+
`analyze` lists the seed decisions with recommendations; grow the tree from the answers:
|
|
40
|
+
|
|
41
|
+
- **Shape and scope**: which entry points, every feature or drop dead ones, admin areas, APIs used
|
|
42
|
+
by mobile clients.
|
|
43
|
+
- **Frontend**: rebuild every page as ERB + Turbo + Stimulus + daisyUI (default); which daisyUI
|
|
44
|
+
theme(s); keep the same information architecture and flows; what may change visually.
|
|
45
|
+
- **Equivalence bar**: JSON exact (default); HTML by visible text (default `--mode text`: every line
|
|
46
|
+
of the original's text must appear in the Rails page; markup and added chrome are free), status
|
|
47
|
+
and redirects only (`--mode status`), or exact text (`--mode exact`).
|
|
48
|
+
- **Data**: the same database and tables first (models with `self.table_name`, `self.primary_key`,
|
|
49
|
+
`attribute` types matching the existing columns) or a new schema with a data migration.
|
|
50
|
+
Never let Rails migrations alter the original's tables before the cut-over.
|
|
51
|
+
- **Auth and sessions**: password hash format (bcrypt carries over; others need a re-hash on
|
|
52
|
+
login), session cookies and API tokens that must keep working.
|
|
53
|
+
- **Compatibility**: URLs, JSON field names (camelCase stays camelCase), status codes, env vars,
|
|
54
|
+
file uploads, webhooks and emails that must stay the same.
|
|
55
|
+
- **Dependencies**: a gem for every library the plan lists with `rails: null`.
|
|
56
|
+
- **Background work and realtime**: Active Job on Solid Queue; Action Cable / Turbo Streams for
|
|
57
|
+
sockets.
|
|
58
|
+
- **Checkpoints**: when you stop for the go-ahead (default: after the front door, after each wave).
|
|
59
|
+
- **Cutover**: deploy target (Kamal, Render, Heroku, a VPS), and the switch plan.
|
|
60
|
+
|
|
61
|
+
Write every decision to `rails/port/DECISIONS.md` as a short ADR, numbered in order and never
|
|
62
|
+
renumbered (`go` waits until there is one):
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
## ADR-003: HTML pages compared by visible text
|
|
66
|
+
Status: accepted (2026-11-28)
|
|
67
|
+
Context: the views are rebuilt with daisyUI; markup cannot match.
|
|
68
|
+
Decision: app replay --mode text; JSON stays exact.
|
|
69
|
+
Consequences: copy changes need a new ADR and a re-record.
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Start `rails/port/GLOSSARY.md`: each domain term, its meaning, and its Ruby name (model, service,
|
|
73
|
+
route, Stimulus controller).
|
|
74
|
+
|
|
75
|
+
## 2. Research, in the background
|
|
76
|
+
|
|
77
|
+
For each dependency with no Rails equivalent and each `high` risk, send a background subagent to
|
|
78
|
+
research it against **primary sources** only (the library's own docs and code, the gem's
|
|
79
|
+
repository and docs, the Rails guides). Each writes `rails/port/research/<topic>.md`, citing the
|
|
80
|
+
source of every claim and listing the semantic traps. Read it before porting any unit it covers.
|
|
81
|
+
|
|
82
|
+
## 3. Record the whole app
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
ruby-anything app record <repo> --http --inputs rails/port/app-cases/inputs.jsonl \
|
|
86
|
+
--db-reset "<command that resets the test database>" -- <command that starts the original>
|
|
87
|
+
ruby-anything app replay <repo> --original # the original must pass its own recording 100%
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The start command reads `PORT` or uses `{port}` (`--port` if it is fixed). GET routes without
|
|
91
|
+
parameters are discovered from the code; everything else comes from `inputs.jsonl`
|
|
92
|
+
(`{"name", "method", "path", "headers", "body"}` per line). Collect: the app's tests, docs and curl
|
|
93
|
+
examples, each page and form, logged-in and logged-out requests (put the session cookie or bearer
|
|
94
|
+
token in `headers`), and the error paths (bad input, missing records, forbidden, validation
|
|
95
|
+
failures). Every GET runs twice: values that change between runs become `[..]` wildcards. Ask the
|
|
96
|
+
user about each one: is the order part of the contract?
|
|
97
|
+
|
|
98
|
+
**Side effects.** If the app calls other APIs, sends email or writes a database, record those too,
|
|
99
|
+
or a port that forgets to charge the card or send the receipt would pass:
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
ruby-anything app record <repo> --http --inputs ... \
|
|
103
|
+
--effect-env PAYMENT_API_URL=http,SMTP_HOST=smtp_host,SMTP_PORT=smtp_port \
|
|
104
|
+
--db-dump "sqlite3 db.sqlite3 .dump" --db-reset "<reset command>" -- <start command>
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`--effect-env NAME=KIND` points the app's own setting at a local stand-in: `http` (a URL that
|
|
108
|
+
records every call and answers 200 `{}`, or what `rails/port/app-cases/effect-replies.json`
|
|
109
|
+
says: `[{"method", "path", "status", "body"}]`), `smtp` (an `smtp://host:port` URL), `smtp_host`
|
|
110
|
+
and `smtp_port`. Find the variable names in the app's config; ask the user when it hardcodes a
|
|
111
|
+
URL. `--db-dump` runs after every non-GET request and its rows are part of the case. Replay sets
|
|
112
|
+
the same variables for the Rails app, so Rails must read them too: the payment client's base URL
|
|
113
|
+
from the same env var, Action Mailer's `smtp_settings` from `SMTP_HOST`/`SMTP_PORT` (with
|
|
114
|
+
`delivery_method :smtp` in development), and the same database the dump reads.
|
|
115
|
+
|
|
116
|
+
**CLI apps.** For a command-line tool there is no server: list invocations in
|
|
117
|
+
`rails/port/app-cases/cli.jsonl` (`{"name", "args": [...], "stdin", "env"}`: every command and
|
|
118
|
+
flag, `--help`, bad input, each error exit code) and record with
|
|
119
|
+
`ruby-anything app record <repo> --cli --inputs rails/port/app-cases/cli.jsonl -- python tool.py`
|
|
120
|
+
(or `ruby-anything go --cli -- python tool.py`). Each invocation runs twice in a throwaway copy of
|
|
121
|
+
the repo; exit code, stdout, stderr and the files it writes are the case. The front door is
|
|
122
|
+
`rails/bin/<name>`: a command wired with `app wire <repo> <unit> --command <name>` (`*` for the
|
|
123
|
+
default) runs `Cli::<Unit>.call(argv)` from `rails/app/cli/<unit>.rb` inside the Rails app and
|
|
124
|
+
returns the exit code; every other invocation execs the original.
|
|
125
|
+
|
|
126
|
+
## 4. Build the front door
|
|
127
|
+
|
|
128
|
+
```sh
|
|
129
|
+
ruby-anything app front-door <repo> # rails new rails --css=tailwind --javascript=importmap + daisyUI + proxy
|
|
130
|
+
ruby-anything app replay <repo> # through Rails: must match 100% before any route moves
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
It creates the Rails app in `rails/`, adds daisyUI to `app/assets/tailwind/application.css`, and
|
|
134
|
+
installs `lib/ruby_anything/front_door.rb`: a Rack middleware that proxies every request not listed
|
|
135
|
+
in `config/ruby_anything.yml` to the original (`RUBY_ANYTHING_ORIGINAL_URL`). Replay starts both
|
|
136
|
+
apps for you. The **fallback rate** is the share of recorded cases the original still answers; it
|
|
137
|
+
only goes down.
|
|
138
|
+
|
|
139
|
+
Set up the layout once: `app/views/layouts/application.html.erb` with a daisyUI `navbar`, the
|
|
140
|
+
original's navigation, flash messages as `alert`s, and `<html data-theme="...">` from the ADR.
|
|
141
|
+
|
|
142
|
+
## 5. Port route by route
|
|
143
|
+
|
|
144
|
+
Follow the waves, lowest first: a route's models and services are Ruby before its controller.
|
|
145
|
+
For each route (`go` names the next one):
|
|
146
|
+
|
|
147
|
+
1. Claim it in `MAP.md`; run `ruby-anything rules <repo>`.
|
|
148
|
+
2. Port the units it calls with SKILL.md steps 2-4 (`bridge`, `record`, write, `diff`, `gate`).
|
|
149
|
+
3. Model: an ActiveRecord model on the same table (wave 1). Validations from the original's
|
|
150
|
+
checks; associations from its joins; scopes from its repeated queries.
|
|
151
|
+
4. Controller action + route in `config/routes.rb` with the **same path, params, status codes,
|
|
152
|
+
redirects and JSON shape** (`render json:` with the original's keys; `head :no_content`
|
|
153
|
+
where it returns 204).
|
|
154
|
+
5. View (HTML routes): ERB + Turbo + Stimulus + daisyUI per [frontend.md](frontend.md).
|
|
155
|
+
6. `ruby-anything app wire <repo> <unit-name> --route "GET /products/:id"` (one per method and
|
|
156
|
+
path; `ANY /admin/*` for a prefix). Kill switch: `RUBY_ANYTHING_UNIT_<NAME>=original`.
|
|
157
|
+
7. `ruby-anything app replay <repo>`: 100% again and a lower fallback rate. When red, fix one case
|
|
158
|
+
at a time: `ruby-anything app replay <repo> --case <name>`: read its difference, form one
|
|
159
|
+
hypothesis, change the Rails code, rerun until green, then the full replay.
|
|
160
|
+
8. Add a Minitest controller or system test, mark the route `done` in `MAP.md`.
|
|
161
|
+
|
|
162
|
+
Units in one wave do not depend on each other, so a wave can go **in parallel**: give each unit
|
|
163
|
+
to its own subagent with the unit id, its claim, and the files to read (`DECISIONS.md`,
|
|
164
|
+
`GLOSSARY.md`, the unit's research). You wire routes one at a time and replay after each. Turn
|
|
165
|
+
every mistake a subagent made into a rule (`rules --add`), an ADR, or a test.
|
|
166
|
+
|
|
167
|
+
Translate faithfully first, then make it idiomatic Rails once `replay` passes, and replay again.
|
|
168
|
+
|
|
169
|
+
Stop at the checkpoints from `DECISIONS.md`: report routes and units done, gate and replay
|
|
170
|
+
results, the fallback rate and what is left. Write `rails/port/HANDOFF.md` for a fresh session
|
|
171
|
+
(where the port stands, what is in progress or broken, links to MAP.md, the ADRs that matter now
|
|
172
|
+
and the last replay report). Point to files; copy nothing.
|
|
173
|
+
|
|
174
|
+
## 6. Lift to a pure Rails app
|
|
175
|
+
|
|
176
|
+
When the fallback rate is 0 and every unit passes `gate`:
|
|
177
|
+
|
|
178
|
+
```sh
|
|
179
|
+
ruby-anything gate <repo> --app # units, bin/rails test, rubocop, brakeman, replay
|
|
180
|
+
ruby-anything app lift <repo> # refuses until nothing falls back; replays Rails alone; removes the proxy
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## 7. Prove it, then cut over
|
|
184
|
+
|
|
185
|
+
Run `ruby-anything app replay <repo>` and `bin/rails test` in CI, plus `ruby-anything drift <repo>`
|
|
186
|
+
while the original is still developed. In GitHub Actions, the bundled action runs the gate on
|
|
187
|
+
every pull request:
|
|
188
|
+
|
|
189
|
+
```yaml
|
|
190
|
+
- uses: <owner>/<repo>/packages/ruby-anything@master # or the published copy
|
|
191
|
+
with:
|
|
192
|
+
app: "true"
|
|
193
|
+
``` A mismatch is a bug in the
|
|
194
|
+
port, never in the cases: change a case only with the user's approval, recorded in an ADR.
|
|
195
|
+
|
|
196
|
+
After the lift the Rails app no longer has to mirror the original's structure. Offer a reshape
|
|
197
|
+
pass (RESTful resources, concerns, form objects, Turbo Streams where the original polled, view
|
|
198
|
+
components for repeated daisyUI markup), one change at a time with replay passing after each.
|
|
199
|
+
|
|
200
|
+
Report: replay results, gate results, known behavior differences. The user decides the
|
|
201
|
+
cut-over. Do every step you can; for the ones only the user can do (DNS, secrets, production
|
|
202
|
+
deploy, retiring the original), write `rails/port/cutover.sh`: an interactive script that walks
|
|
203
|
+
them through one step at a time, checks what it can (the health route `/up` answers), and offers
|
|
204
|
+
the way back at each step. Leave the original in place until they say otherwise.
|
package/src/adapters.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
// Runs PortPilot's language adapters (the recorders) on the original code.
|
|
3
|
+
// Recording EXECUTES the original: work on a copy, with a test database.
|
|
4
|
+
const fs = require('node:fs')
|
|
5
|
+
const path = require('node:path')
|
|
6
|
+
const { PKG, python, which, runHarness, canon } = require('./util')
|
|
7
|
+
|
|
8
|
+
const POLYGLOT = { go: 'go', java: 'javac', kotlin: 'kotlinc', csharp: 'dotnet', php: 'php', rust: 'rustc', swift: 'swiftc', ruby: 'ruby' }
|
|
9
|
+
|
|
10
|
+
function adaptersDir() {
|
|
11
|
+
// Inside the PortPilot repo the live adapters win over a copy left by `npm pack`.
|
|
12
|
+
const dev = path.resolve(PKG, '..', '..', 'adapters')
|
|
13
|
+
if (fs.existsSync(path.join(dev, 'polyglot', 'harness.py'))) return dev
|
|
14
|
+
const bundled = path.join(PKG, 'adapters')
|
|
15
|
+
if (fs.existsSync(path.join(bundled, 'polyglot'))) return bundled
|
|
16
|
+
throw new Error('language adapters missing: reinstall ruby-anything')
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// argv + env for a language's harness, or throws with what to install.
|
|
20
|
+
function harnessFor(lang) {
|
|
21
|
+
const dir = adaptersDir()
|
|
22
|
+
const py = python()
|
|
23
|
+
if (lang === 'python') {
|
|
24
|
+
if (!py) throw new Error('python 3 is required to record Python code')
|
|
25
|
+
return { argv: [py, '-X', 'utf8', '-I', '-B', path.join(dir, 'python', 'harness.py')], env: {} }
|
|
26
|
+
}
|
|
27
|
+
if (lang === 'javascript' || lang === 'typescript') {
|
|
28
|
+
return { argv: [process.execPath, '--enable-source-maps', path.join(dir, 'node', 'harness.mjs')], env: {} }
|
|
29
|
+
}
|
|
30
|
+
if (POLYGLOT[lang]) {
|
|
31
|
+
if (!py) throw new Error(`python 3 is required to drive the ${lang} recorder`)
|
|
32
|
+
if (!which(POLYGLOT[lang])) throw new Error(`${POLYGLOT[lang]} is not installed (needed to record ${lang}); run ruby-anything doctor`)
|
|
33
|
+
return { argv: [py, '-X', 'utf8', '-B', path.join(dir, 'polyglot', 'harness.py')], env: { PORTPILOT_LANGUAGE: lang } }
|
|
34
|
+
}
|
|
35
|
+
throw new Error(`no recorder for ${lang}`)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function supported(lang) {
|
|
39
|
+
return lang === 'python' || lang === 'javascript' || lang === 'typescript' || !!POLYGLOT[lang]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function analyzeUnits(root, lang) {
|
|
43
|
+
const h = harnessFor(lang)
|
|
44
|
+
const { events } = await runHarness(h.argv, { command: 'analyze' }, { env: { ...h.env, PORTPILOT_SRC: root }, cwd: root })
|
|
45
|
+
return {
|
|
46
|
+
files: events.filter((e) => e.event === 'file'),
|
|
47
|
+
units: events.filter((e) => e.event === 'unit'),
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function record(root, lang, { moduleFile, fn, cases = [], count = 40, seed = 1, mode = 'edge', pinClock = false, onEvent }) {
|
|
52
|
+
const h = harnessFor(lang)
|
|
53
|
+
const req = { command: 'record', module_file: moduleFile, function: fn, cases: '__CASES__', generate: count ? { count, seed, mode } : null, pin_clock: !!pinClock }
|
|
54
|
+
// cases keep their int/float kinds ({ $n } values) on the way in
|
|
55
|
+
const raw = JSON.stringify(req).replace('"__CASES__"', canon(cases))
|
|
56
|
+
const { events } = await runHarness(h.argv, raw, { env: { ...h.env, PORTPILOT_SRC: root }, cwd: root, onEvent })
|
|
57
|
+
return {
|
|
58
|
+
runtime: events.find((e) => e.event === 'plan')?.runtime,
|
|
59
|
+
cases: events.filter((e) => e.event === 'case'),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
module.exports = { adaptersDir, harnessFor, supported, analyzeUnits, record }
|
package/src/analyze.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
const fs = require('node:fs')
|
|
3
|
+
const path = require('node:path')
|
|
4
|
+
const { detect } = require('./detect')
|
|
5
|
+
const adapters = require('./adapters')
|
|
6
|
+
const { layout, writeFile, writeJSON, parseArgs, plain, bold, dim, yellow } = require('./util')
|
|
7
|
+
|
|
8
|
+
const MODEL_RE = /(^|\/)(models?|entit(y|ies)|schemas?|domain|repositor(y|ies)|dao|migrations?|prisma)(\/|\.|$)|Entity\.|Repository\./i
|
|
9
|
+
const CONTROLLER_RE = /(^|\/)(controllers?|routes?|handlers?|views\.py|api|endpoints?|resources?)(\/|\.|$)|Controller\./i
|
|
10
|
+
const JOB_RE = /(^|\/)(jobs?|workers?|tasks?|queues?|mail(ers?)?|notifications?|cron|schedulers?)(\/|\.|$)/i
|
|
11
|
+
|
|
12
|
+
function unitId(u) {
|
|
13
|
+
return `${u.file}:${u.qualified_name || u.name}`
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function buildPlan(root, { units: wantUnits = true, log = () => {} } = {}) {
|
|
17
|
+
const d = detect(root)
|
|
18
|
+
const units = []
|
|
19
|
+
const notes = []
|
|
20
|
+
if (wantUnits) {
|
|
21
|
+
for (const lang of Object.keys(d.langs)) {
|
|
22
|
+
if (!adapters.supported(lang)) {
|
|
23
|
+
notes.push(`${lang}: no recorder; its code is ported from the source and checked through app record/replay`)
|
|
24
|
+
continue
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
log(`analyzing ${lang} functions`)
|
|
28
|
+
const r = await adapters.analyzeUnits(root, lang)
|
|
29
|
+
for (const u of r.units) {
|
|
30
|
+
if (/(^|\/)(tests?|spec|__tests__)\//.test(u.file)) continue
|
|
31
|
+
units.push({ ...plain(u), lang })
|
|
32
|
+
}
|
|
33
|
+
} catch (e) {
|
|
34
|
+
notes.push(`${lang}: function analysis unavailable (${e.message.split('\n')[0]}); routes and files are still planned`)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const fileKind = (rel) =>
|
|
40
|
+
MODEL_RE.test(rel) ? 'model' : CONTROLLER_RE.test(rel) ? 'controller' : JOB_RE.test(rel) ? 'job' : 'logic'
|
|
41
|
+
|
|
42
|
+
const planUnits = units.map((u) => {
|
|
43
|
+
const effects = u.side_effects || []
|
|
44
|
+
const kind = fileKind(u.file)
|
|
45
|
+
const recordable = u.kind === 'function' && (u.params || []).every((p) => p.kind !== 'varargs')
|
|
46
|
+
const pure = effects.length === 0
|
|
47
|
+
let wave = kind === 'model' ? 1 : kind === 'controller' ? 3 : kind === 'job' ? 5 : 2
|
|
48
|
+
const risks = []
|
|
49
|
+
if (effects.length) risks.push(`side effects: ${effects.join(', ')}`)
|
|
50
|
+
if ((u.complexity || 0) >= 10) risks.push(`complexity ${u.complexity}`)
|
|
51
|
+
if ((u.perf_hints || []).length) risks.push(...u.perf_hints)
|
|
52
|
+
return {
|
|
53
|
+
id: unitId(u),
|
|
54
|
+
lang: u.lang,
|
|
55
|
+
file: u.file,
|
|
56
|
+
name: u.name,
|
|
57
|
+
qualified_name: u.qualified_name,
|
|
58
|
+
kind: u.kind,
|
|
59
|
+
owner: u.owner || null,
|
|
60
|
+
instance: !!u.instance,
|
|
61
|
+
line_start: u.line_start,
|
|
62
|
+
line_end: u.line_end,
|
|
63
|
+
params: u.params || [],
|
|
64
|
+
returns: u.returns || null,
|
|
65
|
+
raise_lines: u.raise_lines || [],
|
|
66
|
+
complexity: u.complexity || 0,
|
|
67
|
+
calls: u.internal_deps || [],
|
|
68
|
+
effects,
|
|
69
|
+
area: kind,
|
|
70
|
+
wave,
|
|
71
|
+
recordable,
|
|
72
|
+
start_here: recordable && pure && (u.params || []).length > 0 && (u.complexity || 0) < 10,
|
|
73
|
+
risks,
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const routeUnits = d.routes.map((r) => ({
|
|
78
|
+
id: `route:${r.method} ${r.path}`,
|
|
79
|
+
method: r.method,
|
|
80
|
+
path: r.path,
|
|
81
|
+
file: r.file,
|
|
82
|
+
line: r.line,
|
|
83
|
+
wave: 3,
|
|
84
|
+
area: 'route',
|
|
85
|
+
}))
|
|
86
|
+
|
|
87
|
+
const decisions = []
|
|
88
|
+
const q = (title, question, recommended) => decisions.push({ n: decisions.length + 1, title, question, recommended })
|
|
89
|
+
q('Shape', `The app looks like: ${d.shape}. Which entry points move to Rails?`, d.isServer ? 'Every HTTP route, served by one Rails app' : 'The public API as Ruby service objects in a Rails app')
|
|
90
|
+
q('Frontend', d.hasFrontend
|
|
91
|
+
? `Frontend found (${d.templates.length} templates; ${d.frameworks.filter((f) => f.kind !== 'server').map((f) => f.name).join(', ') || 'server-rendered'}). Rebuild it as ERB views with Turbo Frames/Streams, Stimulus controllers, Tailwind and daisyUI?`
|
|
92
|
+
: 'No frontend found. Add a minimal Hotwire + daisyUI UI, or keep an API-only Rails app?',
|
|
93
|
+
d.hasFrontend ? 'Yes: ERB + Turbo + Stimulus + Tailwind + daisyUI, same pages and flows, new components' : 'API-only (rails new --api is not used; views can be added later)')
|
|
94
|
+
q('Equivalence bar', 'How close must Rails match the original? JSON responses and function results are compared exactly. HTML pages are rebuilt with daisyUI, so compare: visible text, or status + redirects only?', 'JSON exact; HTML by visible text (whitespace and markup ignored); status codes and redirects exact')
|
|
95
|
+
q('Database', 'Keep the existing database and schema (Rails models on the same tables), or migrate data to a new schema?', 'Same database and tables first (ActiveRecord with table_name / primary_key overrides); reshape after cut-over')
|
|
96
|
+
q('Auth', 'How do users sign in today, and must sessions/tokens keep working across the cut-over?', 'Rails 8 authentication generator; keep the same password hashes (bcrypt) and token format where clients depend on them')
|
|
97
|
+
const unmapped = d.deps.filter((x) => !x.rails)
|
|
98
|
+
if (unmapped.length) q('Dependencies', `No known Rails equivalent for: ${unmapped.slice(0, 15).map((x) => x.name).join(', ')}${unmapped.length > 15 ? ', ...' : ''}. Research each before porting the units that use it?`, 'Yes: one research note per dependency in rails/port/research/, from primary sources')
|
|
99
|
+
q('Compatibility', 'Which must stay byte-identical: URLs, JSON field names, status codes, env vars, config files, cookies?', 'URLs, JSON shapes, status codes and env var names stay; internal config moves to Rails credentials')
|
|
100
|
+
q('Checkpoints', 'When do I stop for your go-ahead?', 'After the plan, after the front door, and after each wave')
|
|
101
|
+
q('Cutover', 'Switch all traffic at once after the lift, or run Rails in front of the original (front door) and move route by route?', 'Front door: Rails proxies unported routes to the original; routes move one at a time; lift when the fallback rate is 0')
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
schema: 'ruby-anything/analyze@1',
|
|
105
|
+
root,
|
|
106
|
+
shape: d.shape,
|
|
107
|
+
primary: d.primary,
|
|
108
|
+
languages: d.langs,
|
|
109
|
+
frameworks: d.frameworks,
|
|
110
|
+
deps: d.deps,
|
|
111
|
+
routes: routeUnits,
|
|
112
|
+
templates: d.templates,
|
|
113
|
+
styles: d.staticAssets,
|
|
114
|
+
tests: d.tests,
|
|
115
|
+
units: planUnits,
|
|
116
|
+
start_here: planUnits.filter((u) => u.start_here).sort((a, b) => a.complexity - b.complexity).slice(0, 10).map((u) => u.id),
|
|
117
|
+
decisions,
|
|
118
|
+
notes,
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function planMarkdown(p) {
|
|
123
|
+
const L = []
|
|
124
|
+
const n = (x) => x.length
|
|
125
|
+
L.push(`# Migration plan: ${path.basename(p.root)} to Ruby on Rails`, '')
|
|
126
|
+
L.push(`Shape: **${p.shape}**. Main language: **${p.primary || 'unknown'}**.`, '')
|
|
127
|
+
L.push('Target: Rails 8, Hotwire (Turbo + Stimulus), importmap, Tailwind CSS + daisyUI, Minitest.', '')
|
|
128
|
+
L.push('| Language | Files | Lines |', '|---|---|---|')
|
|
129
|
+
for (const [k, v] of Object.entries(p.languages)) L.push(`| ${k} | ${v.files} | ${v.loc} |`)
|
|
130
|
+
L.push('', `Frameworks: ${p.frameworks.map((f) => f.name).join(', ') || 'none detected'}`, '')
|
|
131
|
+
L.push('## Waves', '')
|
|
132
|
+
L.push('Ported lowest wave first, so every unit\'s dependencies are already Ruby.', '')
|
|
133
|
+
const wave = (w, title, items) => {
|
|
134
|
+
L.push(`### Wave ${w}: ${title} (${n(items)})`, '')
|
|
135
|
+
for (const u of items.slice(0, 80)) {
|
|
136
|
+
if (u.area === 'route') L.push(`- [ ] \`${u.id}\` (${u.file}:${u.line})`)
|
|
137
|
+
else L.push(`- [ ] \`${u.id}\`${u.start_here ? ' **start here**' : ''}${u.recordable ? '' : ' (checked through app replay)'}${u.risks.length ? ` - risks: ${u.risks.join('; ')}` : ''}`)
|
|
138
|
+
}
|
|
139
|
+
if (n(items) > 80) L.push(`- ... ${n(items) - 80} more in plan.json`)
|
|
140
|
+
L.push('')
|
|
141
|
+
}
|
|
142
|
+
wave(1, 'data models (ActiveRecord)', p.units.filter((u) => u.wave === 1))
|
|
143
|
+
wave(2, 'business logic (app/services, plain Ruby)', p.units.filter((u) => u.wave === 2))
|
|
144
|
+
wave(3, 'routes and controllers', [...p.routes, ...p.units.filter((u) => u.wave === 3)])
|
|
145
|
+
L.push(`### Wave 4: views (ERB + Turbo + Stimulus + daisyUI) (${n(p.templates)})`, '')
|
|
146
|
+
for (const t of p.templates.slice(0, 80)) L.push(`- [ ] \`${t}\``)
|
|
147
|
+
L.push('')
|
|
148
|
+
wave(5, 'jobs, mailers, realtime', p.units.filter((u) => u.wave === 5))
|
|
149
|
+
L.push('### Wave 6: lift (remove the front door fallback)', '')
|
|
150
|
+
L.push('## Dependencies', '', '| Dependency | Rails equivalent |', '|---|---|')
|
|
151
|
+
for (const x of p.deps) L.push(`| ${x.name} | ${x.rails || yellowText('unknown: research')} |`)
|
|
152
|
+
L.push('', '## Decisions to settle with the user', '')
|
|
153
|
+
for (const d of p.decisions) L.push(`**Q${d.n} - ${d.title}**: ${d.question}`, '', `> Recommended: ${d.recommended}`, '')
|
|
154
|
+
if (p.notes.length) L.push('## Notes', '', ...p.notes.map((x) => `- ${x}`), '')
|
|
155
|
+
return L.join('\n')
|
|
156
|
+
}
|
|
157
|
+
const yellowText = (s) => `**${s}**`
|
|
158
|
+
|
|
159
|
+
async function cmdAnalyze(argv) {
|
|
160
|
+
const a = parseArgs(argv, ['json', 'noUnits'])
|
|
161
|
+
const root = path.resolve(a._[0] || '.')
|
|
162
|
+
const p = await buildPlan(root, { units: !a.noUnits, log: (m) => !a.json && console.error(dim(m)) })
|
|
163
|
+
const L = layout(root)
|
|
164
|
+
writeJSON(L.planJson, p)
|
|
165
|
+
const md = planMarkdown(p)
|
|
166
|
+
writeFile(a.o || a.output || L.plan, md)
|
|
167
|
+
if (a.json) {
|
|
168
|
+
process.stdout.write(JSON.stringify(p, null, 2) + '\n')
|
|
169
|
+
return 0
|
|
170
|
+
}
|
|
171
|
+
console.log(bold(`${path.basename(root)}: ${p.shape}, mostly ${p.primary}`))
|
|
172
|
+
console.log(` ${p.units.length} functions, ${p.routes.length} routes, ${p.templates.length} templates, ${p.deps.length} dependencies`)
|
|
173
|
+
console.log(` frameworks: ${p.frameworks.map((f) => f.name).join(', ') || 'none'}`)
|
|
174
|
+
if (p.start_here.length) console.log(` start here: ${p.start_here.slice(0, 5).join(', ')}`)
|
|
175
|
+
const unknown = p.deps.filter((x) => !x.rails).length
|
|
176
|
+
if (unknown) console.log(yellow(` ${unknown} dependencies with no known Rails equivalent: research them`))
|
|
177
|
+
for (const x of p.notes) console.log(yellow(` note: ${x}`))
|
|
178
|
+
console.log(` plan: ${path.relative(process.cwd(), a.o || a.output || L.plan)} (and plan.json)`)
|
|
179
|
+
console.log(`\nNext: settle the ${p.decisions.length} decisions with the user, write them to rails/port/DECISIONS.md, then run\n ruby-anything app record ${a._[0] || '.'} --http -- <command that starts the original>`)
|
|
180
|
+
return 0
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
module.exports = { buildPlan, planMarkdown, cmdAnalyze, unitId }
|