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
package/src/cli.js ADDED
@@ -0,0 +1,75 @@
1
+ 'use strict'
2
+ const HELP = `ruby-anything: migrate any app to Ruby on Rails (Hotwire, Tailwind, daisyUI), one piece at a
3
+ time, checked against the original's recorded behavior at every step.
4
+
5
+ Start
6
+ setup [--remove] install the agent skill and register the MCP server
7
+ doctor check Ruby, Rails and the runtimes the original needs
8
+ go [-- <start command>] move the migration to its next stage; writes rails/port/TASK.md
9
+
10
+ Plan
11
+ analyze <repo> [--json] [-o f] languages, routes, templates, functions in waves, decisions
12
+
13
+ One unit (a function)
14
+ bridge <repo> <unit> Ruby skeleton in rails/app/services + TASK.md
15
+ record <repo> <unit> [--inputs f] [--count N] the original's behavior -> rails/port/cases
16
+ diff <repo> <unit> [--json] replay the cases against the Ruby port (must be N/N)
17
+ gate <repo> <unit>|--all|--app done means gate passes
18
+ rules <repo> [--add "<rule>"] behavior the user corrected; every unit keeps it
19
+
20
+ Whole app
21
+ app record <repo> --http [--inputs f] [--db-reset cmd] -- <start command>
22
+ app front-door <repo> Rails 8 app that proxies routes not ported yet to the original
23
+ app wire <repo> <unit> --route "GET /path/:id"
24
+ app replay <repo> [--original] [--case name] [--mode text|status|exact]
25
+ app status <repo> [--write] fallback rate, wired routes, units; writes PORT_MAP.md
26
+ app lift <repo> remove the front door once nothing falls back
27
+
28
+ Agents
29
+ mcp MCP server on stdio (the same steps as tools)
30
+
31
+ Recording runs the original code: work on a copy, with a test database.`
32
+
33
+ async function main(argv) {
34
+ const [cmd, ...rest] = argv
35
+ switch (cmd) {
36
+ case undefined:
37
+ case 'help':
38
+ case '--help':
39
+ case '-h':
40
+ console.log(HELP)
41
+ return 0
42
+ case '--version':
43
+ case '-v':
44
+ console.log(require('../package.json').version)
45
+ return 0
46
+ case 'setup':
47
+ return require('./setup').cmdSetup(rest)
48
+ case 'doctor':
49
+ return require('./setup').cmdDoctor(rest)
50
+ case 'analyze':
51
+ return require('./analyze').cmdAnalyze(rest)
52
+ case 'go':
53
+ return require('./go').cmdGo(rest)
54
+ case 'bridge':
55
+ return require('./units').cmdBridge(rest)
56
+ case 'record':
57
+ return require('./units').cmdRecord(rest)
58
+ case 'diff':
59
+ return require('./units').cmdDiff(rest)
60
+ case 'gate':
61
+ return require('./units').cmdGate(rest)
62
+ case 'rules':
63
+ return require('./units').cmdRules(rest)
64
+ case 'app':
65
+ return require('./app').cmdApp(rest)
66
+ case 'map':
67
+ return require('./app').cmdAppStatus([...rest, '--write'])
68
+ case 'mcp':
69
+ return require('./mcp').cmdMcp(rest)
70
+ default:
71
+ throw new Error(`unknown command "${cmd}". Run ruby-anything help.`)
72
+ }
73
+ }
74
+
75
+ module.exports = { main }
package/src/detect.js ADDED
@@ -0,0 +1,266 @@
1
+ 'use strict'
2
+ // Static detection: languages, frameworks, HTTP routes, frontend templates and the app's shape.
3
+ // Nothing is executed here.
4
+ const fs = require('node:fs')
5
+ const path = require('node:path')
6
+
7
+ const SKIP = new Set(['.git', 'node_modules', 'vendor', 'dist', 'build', 'target', 'out', 'bin', 'obj', '.venv', 'venv',
8
+ '__pycache__', '.next', '.nuxt', 'coverage', '.gradle', '.idea', '.vscode', 'rails', 'tmp', 'log'])
9
+
10
+ const LANGS = {
11
+ python: ['.py'], javascript: ['.js', '.mjs', '.cjs', '.jsx'], typescript: ['.ts', '.tsx', '.mts'], go: ['.go'],
12
+ java: ['.java'], kotlin: ['.kt'], csharp: ['.cs'], php: ['.php'], ruby: ['.rb'], rust: ['.rs'], swift: ['.swift'],
13
+ }
14
+ const TEMPLATES = ['.html', '.htm', '.ejs', '.hbs', '.handlebars', '.pug', '.jinja', '.jinja2', '.j2', '.twig', '.blade.php',
15
+ '.cshtml', '.razor', '.vue', '.svelte', '.jsx', '.tsx', '.gohtml', '.tmpl', '.jsp', '.thymeleaf', '.erb']
16
+
17
+ const FRAMEWORKS = [
18
+ // [name, language, kind, evidence regex over manifest+source]
19
+ ['Express', 'javascript', 'server', /["']express["']/],
20
+ ['Fastify', 'javascript', 'server', /["']fastify["']/],
21
+ ['Koa', 'javascript', 'server', /["']koa["']/],
22
+ ['NestJS', 'typescript', 'server', /@nestjs\/core/],
23
+ ['Next.js', 'javascript', 'fullstack', /["']next["']\s*:/],
24
+ ['React', 'javascript', 'frontend', /["']react["']\s*:/],
25
+ ['Vue', 'javascript', 'frontend', /["']vue["']\s*:/],
26
+ ['Angular', 'typescript', 'frontend', /@angular\/core/],
27
+ ['Svelte', 'javascript', 'frontend', /["']svelte["']\s*:/],
28
+ ['Flask', 'python', 'server', /\bflask\b/i],
29
+ ['FastAPI', 'python', 'server', /\bfastapi\b/i],
30
+ ['Django', 'python', 'server', /\bdjango\b/i],
31
+ ['Spring Boot', 'java', 'server', /spring-boot|org\.springframework\.boot/],
32
+ ['Ktor', 'kotlin', 'server', /io\.ktor/],
33
+ ['ASP.NET Core', 'csharp', 'server', /Microsoft\.AspNetCore|Sdk="Microsoft\.NET\.Sdk\.Web"/],
34
+ ['Laravel', 'php', 'server', /laravel\/framework/],
35
+ ['Symfony', 'php', 'server', /symfony\/framework-bundle/],
36
+ ['Gin', 'go', 'server', /github\.com\/gin-gonic\/gin/],
37
+ ['Echo', 'go', 'server', /github\.com\/labstack\/echo/],
38
+ ['Fiber', 'go', 'server', /github\.com\/gofiber\/fiber/],
39
+ ['net/http', 'go', 'server', /"net\/http"/],
40
+ ['http.server', 'python', 'server', /BaseHTTPRequestHandler|from http\.server import/],
41
+ ['Node http', 'javascript', 'server', /http\.createServer\(/],
42
+ ['Actix', 'rust', 'server', /actix-web/],
43
+ ['Axum', 'rust', 'server', /\baxum\b/],
44
+ ['Sinatra', 'ruby', 'server', /\bsinatra\b/],
45
+ ['Vapor', 'swift', 'server', /vapor\/vapor/],
46
+ ]
47
+
48
+ const MANIFESTS = ['package.json', 'requirements.txt', 'pyproject.toml', 'Pipfile', 'pom.xml', 'build.gradle', 'build.gradle.kts',
49
+ 'go.mod', 'composer.json', 'Cargo.toml', 'Gemfile', 'Package.swift']
50
+
51
+ // Rails equivalents for dependencies the plan mentions; unknown ones are flagged, never guessed.
52
+ const RAILS_EQUIVALENTS = {
53
+ express: 'Rails routing + controllers', fastify: 'Rails routing + controllers', koa: 'Rails routing + controllers',
54
+ '@nestjs/core': 'Rails controllers + service objects', next: 'Rails + Turbo (pages become views)',
55
+ react: 'ERB views + Turbo Frames/Streams + Stimulus', vue: 'ERB views + Stimulus', svelte: 'ERB views + Stimulus',
56
+ '@angular/core': 'ERB views + Stimulus', flask: 'Rails controllers', fastapi: 'Rails API controllers', django: 'Rails',
57
+ mongoose: 'ActiveRecord (or mongoid gem)', sequelize: 'ActiveRecord', prisma: 'ActiveRecord', typeorm: 'ActiveRecord',
58
+ sqlalchemy: 'ActiveRecord', 'spring-boot-starter-data-jpa': 'ActiveRecord', hibernate: 'ActiveRecord',
59
+ 'eloquent': 'ActiveRecord', gorm: 'ActiveRecord', diesel: 'ActiveRecord',
60
+ passport: 'Rails 8 authentication generator (has_secure_password)', jsonwebtoken: 'jwt gem', bcrypt: 'bcrypt gem',
61
+ nodemailer: 'Action Mailer', celery: 'Active Job + Solid Queue', bull: 'Active Job + Solid Queue', bullmq: 'Active Job + Solid Queue',
62
+ 'socket.io': 'Action Cable / Turbo Streams', ws: 'Action Cable', redis: 'redis gem / Solid Cache', axios: 'Net::HTTP or faraday gem',
63
+ 'node-fetch': 'Net::HTTP or faraday gem', requests: 'Net::HTTP or faraday gem', lodash: 'Ruby core / ActiveSupport',
64
+ moment: 'ActiveSupport::TimeWithZone', dayjs: 'ActiveSupport::TimeWithZone', zod: 'ActiveModel validations',
65
+ joi: 'ActiveModel validations', pydantic: 'ActiveModel validations', multer: 'Active Storage', stripe: 'stripe gem',
66
+ tailwindcss: 'tailwindcss-rails + daisyUI', bootstrap: 'daisyUI components', jest: 'Minitest', pytest: 'Minitest',
67
+ 'spring-boot-starter-web': 'Rails controllers', 'spring-boot-starter-thymeleaf': 'ERB views',
68
+ 'spring-boot-starter-security': 'Rails 8 authentication generator', 'spring-boot-starter-validation': 'ActiveModel validations',
69
+ 'laravel/framework': 'Rails', 'github.com/gin-gonic/gin': 'Rails routing + controllers',
70
+ }
71
+
72
+ function walk(root, onFile, depth = 0) {
73
+ let entries = []
74
+ try {
75
+ entries = fs.readdirSync(root, { withFileTypes: true })
76
+ } catch {
77
+ return
78
+ }
79
+ for (const e of entries) {
80
+ if (e.name.startsWith('.') && e.name !== '.env.example') continue
81
+ const full = path.join(root, e.name)
82
+ if (e.isDirectory()) {
83
+ if (!SKIP.has(e.name) && depth < 12) walk(full, onFile, depth + 1)
84
+ } else if (e.isFile()) onFile(full)
85
+ }
86
+ }
87
+
88
+ function langOf(file) {
89
+ const ext = path.extname(file).toLowerCase()
90
+ for (const [lang, exts] of Object.entries(LANGS)) if (exts.includes(ext)) return lang
91
+ return null
92
+ }
93
+
94
+ function isTest(rel) {
95
+ return /(^|\/)(tests?|spec|__tests__|src\/test)\//.test(rel) || /[._-](test|spec)\.[a-z]+$|Tests?\.(java|kt|cs)$|_test\.go$/.test(rel)
96
+ }
97
+
98
+ function read(file, max = 400000) {
99
+ try {
100
+ const st = fs.statSync(file)
101
+ if (st.size > max) return ''
102
+ return fs.readFileSync(file, 'utf8')
103
+ } catch {
104
+ return ''
105
+ }
106
+ }
107
+
108
+ // ------------------------------------------------------------------ routes
109
+ const ROUTE_RULES = [
110
+ // Express / Koa-router / Fastify: app.get('/x', ...)
111
+ { langs: ['javascript', 'typescript'], re: /\b(?:app|router|server|api|fastify|r)\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]/g, m: 1, p: 2 },
112
+ // NestJS
113
+ { langs: ['typescript'], re: /@(Get|Post|Put|Patch|Delete)\(\s*['"`]?([^'"`)]*)['"`]?\s*\)/g, m: 1, p: 2, prefixRe: /@Controller\(\s*['"`]([^'"`]*)['"`]/ },
114
+ // Flask
115
+ { langs: ['python'], re: /@\w+\.route\(\s*['"]([^'"]+)['"](?:[^)]*methods\s*=\s*\[([^\]]*)\])?/g, p: 1, methods: 2 },
116
+ // FastAPI
117
+ { langs: ['python'], re: /@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]+)['"]/g, m: 1, p: 2 },
118
+ // Django
119
+ { langs: ['python'], re: /\b(?:re_)?path\(\s*r?['"]([^'"]*)['"]/g, p: 1, any: true, prefix: '/' },
120
+ // Spring
121
+ { langs: ['java', 'kotlin'], re: /@(Get|Post|Put|Patch|Delete|Request)Mapping\(\s*(?:value\s*=\s*|path\s*=\s*)?\{?\s*"([^"]*)"/g, m: 1, p: 2, prefixRe: /@RequestMapping\(\s*(?:value\s*=\s*|path\s*=\s*)?"([^"]*)"\s*\)\s*(?:public\s+)?(?:class|@)/ },
122
+ { langs: ['java', 'kotlin'], re: /@(Get|Post|Put|Patch|Delete)Mapping\s*(?:\(\s*\))?\s*\n/g, m: 1, empty: true, prefixRe: /@RequestMapping\(\s*(?:value\s*=\s*|path\s*=\s*)?"([^"]*)"\s*\)\s*(?:public\s+)?(?:class|@)/ },
123
+ // ASP.NET
124
+ { langs: ['csharp'], re: /\.Map(Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"/g, m: 1, p: 2 },
125
+ { langs: ['csharp'], re: /\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)"\s*\))?\]/g, m: 1, p: 2, prefixRe: /\[Route\(\s*"([^"]*)"\s*\)\]/ },
126
+ // Laravel
127
+ { langs: ['php'], re: /Route::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]/g, m: 1, p: 2 },
128
+ // Go: gin/echo/fiber/chi and net/http
129
+ { langs: ['go'], re: /\.(GET|POST|PUT|PATCH|DELETE|Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"/g, m: 1, p: 2 },
130
+ { langs: ['go'], re: /HandleFunc\(\s*"(?:(GET|POST|PUT|PATCH|DELETE)\s+)?([^"]+)"/g, m: 1, p: 2, any: true },
131
+ // Rust: axum/actix
132
+ { langs: ['rust'], re: /\.route\(\s*"([^"]+)"\s*,\s*(get|post|put|patch|delete)/g, p: 1, m: 2 },
133
+ { langs: ['rust'], re: /#\[(get|post|put|patch|delete)\(\s*"([^"]+)"/g, m: 1, p: 2 },
134
+ // Sinatra
135
+ { langs: ['ruby'], re: /^\s*(get|post|put|patch|delete)\s+['"]([^'"]+)['"]/gm, m: 1, p: 2 },
136
+ ]
137
+
138
+ function normPath(p) {
139
+ let s = ('/' + String(p || '').trim()).replace(/\/+/g, '/')
140
+ s = s.replace(/^\/\^/, '/').replace(/\$$/, '')
141
+ // {id} <id> <int:id> :id -> :id
142
+ s = s.replace(/\{(\w+)(?::[^}]*)?\}/g, ':$1').replace(/<(?:\w+:)?(\w+)>/g, ':$1').replace(/\(\?P<(\w+)>[^)]*\)/g, ':$1')
143
+ if (s.length > 1) s = s.replace(/\/$/, '')
144
+ return s
145
+ }
146
+
147
+ function extractRoutes(rel, lang, text) {
148
+ const out = []
149
+ for (const rule of ROUTE_RULES) {
150
+ if (!rule.langs.includes(lang)) continue
151
+ let prefix = rule.prefix || ''
152
+ if (rule.prefixRe) {
153
+ const pm = text.match(rule.prefixRe)
154
+ if (pm) prefix = pm[1]
155
+ }
156
+ rule.re.lastIndex = 0
157
+ let m
158
+ while ((m = rule.re.exec(text))) {
159
+ const line = text.slice(0, m.index).split('\n').length
160
+ let methods
161
+ if (rule.methods && m[rule.methods]) methods = m[rule.methods].match(/[A-Za-z]+/g).map((x) => x.toUpperCase())
162
+ else if (rule.m && m[rule.m]) methods = [m[rule.m].toUpperCase()]
163
+ else methods = rule.any ? ['ANY'] : ['GET']
164
+ methods = methods.map((x) => (x === 'REQUEST' || x === 'ALL' ? 'ANY' : x))
165
+ const p = rule.empty ? '' : m[rule.p] || ''
166
+ if (rule.prefixRe && rule.m === 1 && m[1] === 'Request' && m[2] === prefix) continue // the class-level mapping itself
167
+ for (const method of methods) out.push({ method, path: normPath(prefix + '/' + p), file: rel, line })
168
+ }
169
+ }
170
+ return out
171
+ }
172
+
173
+ // ------------------------------------------------------------------ main
174
+ function detect(root) {
175
+ const files = []
176
+ const langs = {}
177
+ const routes = []
178
+ const templates = []
179
+ const staticAssets = []
180
+ const manifests = {}
181
+ const tests = []
182
+ let evidence = ''
183
+
184
+ walk(root, (full) => {
185
+ const rel = path.relative(root, full).split(path.sep).join('/')
186
+ const base = path.basename(full)
187
+ if (MANIFESTS.includes(base) && !rel.includes('/node_modules/')) {
188
+ const text = read(full)
189
+ manifests[rel] = text
190
+ evidence += '\n' + text
191
+ }
192
+ const lower = base.toLowerCase()
193
+ if (TEMPLATES.some((e) => lower.endsWith(e)) && !lower.endsWith('.d.ts')) {
194
+ if (!/\.(jsx|tsx)$/.test(lower) || /<[A-Za-z]/.test(read(full, 200000))) templates.push(rel)
195
+ }
196
+ if (/\.(css|scss|sass|less)$/.test(lower)) staticAssets.push(rel)
197
+ const lang = langOf(full)
198
+ if (!lang) return
199
+ const text = read(full)
200
+ const loc = text ? text.split('\n').length : 0
201
+ if (isTest(rel)) {
202
+ tests.push(rel)
203
+ return
204
+ }
205
+ langs[lang] = langs[lang] || { files: 0, loc: 0 }
206
+ langs[lang].files++
207
+ langs[lang].loc += loc
208
+ files.push({ rel, lang, loc })
209
+ if (text) {
210
+ evidence += '\n' + text.slice(0, 4000)
211
+ routes.push(...extractRoutes(rel, lang, text))
212
+ }
213
+ })
214
+
215
+ const primary = Object.entries(langs).sort((a, b) => b[1].loc - a[1].loc)[0]?.[0] || null
216
+ const frameworks = FRAMEWORKS.filter(([, , , re]) => re.test(evidence)).map(([name, language, kind]) => ({ name, language, kind }))
217
+ const isServer = routes.length > 0 || frameworks.some((f) => f.kind !== 'frontend')
218
+ const hasFrontend = templates.length > 0 || frameworks.some((f) => f.kind !== 'server')
219
+ const shape = isServer ? (hasFrontend ? 'web app (server + frontend)' : 'HTTP API') : hasFrontend ? 'frontend app' : 'library or CLI'
220
+
221
+ // dedupe routes
222
+ const seen = new Set()
223
+ const uniq = routes.filter((r) => {
224
+ const k = `${r.method} ${r.path}`
225
+ if (seen.has(k)) return false
226
+ seen.add(k)
227
+ return true
228
+ })
229
+
230
+ const deps = []
231
+ for (const [rel, text] of Object.entries(manifests)) {
232
+ const names = new Set()
233
+ if (rel.endsWith('package.json')) {
234
+ try {
235
+ const j = JSON.parse(text)
236
+ Object.keys({ ...j.dependencies }).forEach((n) => names.add(n))
237
+ } catch {}
238
+ } else if (/requirements\.txt|Pipfile/.test(rel)) {
239
+ text.split('\n').forEach((l) => {
240
+ const n = l.trim().match(/^([A-Za-z0-9_.-]+)/)
241
+ if (n && !l.trim().startsWith('#') && !l.includes('[')) names.add(n[1].toLowerCase())
242
+ })
243
+ } else if (rel.endsWith('pom.xml')) {
244
+ for (const m of text.matchAll(/<artifactId>([^<]+)<\/artifactId>/g)) names.add(m[1])
245
+ } else if (/build\.gradle/.test(rel)) {
246
+ for (const m of text.matchAll(/["']([\w.-]+):([\w.-]+)(?::[\w.-]+)?["']/g)) names.add(m[2])
247
+ } else if (rel.endsWith('go.mod')) {
248
+ for (const m of text.matchAll(/^\s*(github\.com\/[\w.-]+\/[\w.-]+|[\w.-]+\.[\w]+\/[\w./-]+)\s+v/gm)) names.add(m[1])
249
+ } else if (rel.endsWith('composer.json')) {
250
+ try {
251
+ Object.keys(JSON.parse(text).require || {}).forEach((n) => names.add(n))
252
+ } catch {}
253
+ } else if (rel.endsWith('Cargo.toml')) {
254
+ const sec = text.split(/\[dependencies\]/)[1] || ''
255
+ for (const m of sec.split(/\n\[/)[0].matchAll(/^([\w-]+)\s*=/gm)) names.add(m[1])
256
+ }
257
+ for (const n of names) {
258
+ if (/^(php|ext-|java|kotlin-stdlib|junit|spring-boot-starter-test|spring-boot-maven-plugin|maven-)/.test(n)) continue
259
+ deps.push({ name: n, manifest: rel, rails: RAILS_EQUIVALENTS[n] || RAILS_EQUIVALENTS[n.toLowerCase()] || null })
260
+ }
261
+ }
262
+
263
+ return { root, primary, langs, files, frameworks, routes: uniq, templates, staticAssets, tests, deps, shape, isServer, hasFrontend }
264
+ }
265
+
266
+ module.exports = { detect, LANGS, langOf, normPath, isTest }
package/src/go.js ADDED
@@ -0,0 +1,139 @@
1
+ 'use strict'
2
+ // `go`: one command that moves the migration to its next stage and writes rails/port/TASK.md.
3
+ // Run it, do what TASK.md says, run it again.
4
+ const fs = require('node:fs')
5
+ const path = require('node:path')
6
+ const { layout, loadState, readJSON, writeFile, parseArgs, bold, green, yellow, relTo } = require('./util')
7
+ const { cmdAnalyze } = require('./analyze')
8
+ const app = require('./app')
9
+
10
+ function decisionsSettled(L) {
11
+ if (!fs.existsSync(L.decisions)) return false
12
+ return /^## ADR-\d+/m.test(fs.readFileSync(L.decisions, 'utf8'))
13
+ }
14
+
15
+ function nextRoute(L) {
16
+ const plan = readJSON(L.planJson, { routes: [] })
17
+ const st = app.cmdAppStatus
18
+ void st
19
+ const cases = app.caseFiles(L).map((f) => readJSON(f))
20
+ const fr = app.fallbackRate(L, cases)
21
+ const firstCase = cases.find((c) => fr.names.includes(c.name))
22
+ const route = firstCase
23
+ ? (plan.routes || []).find((r) => {
24
+ const re = new RegExp('^' + r.path.replace(/:\w+/g, '[^/]+') + '/?$')
25
+ return (r.method === firstCase.request.method || r.method === 'ANY') && re.test(firstCase.request.path.split('?')[0])
26
+ })
27
+ : null
28
+ return { fr, firstCase, route }
29
+ }
30
+
31
+ function task(L, stage, body) {
32
+ writeFile(L.task, `# Next: ${stage}\n\n${body.trim()}\n\nWhen it is done, run \`ruby-anything go\` again.\n`)
33
+ console.log(`${bold('stage')}: ${stage}`)
34
+ console.log(`task: ${relTo(process.cwd(), L.task)}`)
35
+ }
36
+
37
+ async function cmdGo(argv) {
38
+ const a = parseArgs(argv)
39
+ const L = layout(a.repo || a._[0] || '.')
40
+ const repo = relTo(process.cwd(), L.root) || '.'
41
+ const command = a.rest
42
+ const st = loadState(L)
43
+
44
+ // 1. plan
45
+ if (!fs.existsSync(L.planJson)) {
46
+ await cmdAnalyze([L.root])
47
+ task(L, 'grill the user', `
48
+ The plan is in \`rails/port/PLAN.md\`. Do not port anything yet.
49
+
50
+ 1. Read PLAN.md and plan.json. Facts are yours to find (read the code, run the app); decisions are the user's.
51
+ 2. Ask the decisions listed under "Decisions to settle with the user" in rounds, each with your
52
+ recommended answer, until every one is settled.
53
+ 3. Write each decision to \`rails/port/DECISIONS.md\` as \`## ADR-001: <title>\` (Status, Context, Decision, Consequences).
54
+ 4. Start \`rails/port/GLOSSARY.md\` (domain terms and their Ruby names) and \`rails/port/MAP.md\` (the waves, each unit open).`)
55
+ return 0
56
+ }
57
+ if (!decisionsSettled(L)) {
58
+ task(L, 'grill the user', 'DECISIONS.md has no ADR yet. Settle the decisions in PLAN.md with the user and write them as ADRs (## ADR-001: ...).')
59
+ return 0
60
+ }
61
+
62
+ // 2. record the whole app
63
+ if (!app.caseFiles(L).length) {
64
+ if (!command.length) {
65
+ task(L, 'record the original', `
66
+ Record what the original does from the outside, so every later step is held to it.
67
+
68
+ ruby-anything go -- <command that starts the original; it must read PORT or use {port}>
69
+
70
+ Collect real requests first (tests, docs, curl examples, forms, error paths: bad input, missing
71
+ records, unauthenticated) as JSON lines \`{"method","path","headers","body"}\` in
72
+ \`rails/port/app-cases/inputs.jsonl\`. GET routes without parameters are discovered for you.
73
+ Recording runs the real code: use a copy of the database (\`--db-reset "<command>"\`).`)
74
+ return 0
75
+ }
76
+ const inputs = path.join(L.appCases, 'inputs.jsonl')
77
+ const args = [L.root, '--http', ...(fs.existsSync(inputs) ? ['--inputs', inputs] : []), ...(a.dbReset ? ['--db-reset', a.dbReset] : []), '--', ...command]
78
+ const code = await app.cmdAppRecord(args)
79
+ if (code !== 0) return code
80
+ const orig = await app.cmdAppReplay([L.root, '--original'])
81
+ if (orig !== 0) {
82
+ task(L, 'stabilise the recording', 'The original does not replay its own recording 100%. Add [..] wildcards for noise (timestamps, ids) in the case files, or pin it with inputs, then `ruby-anything app replay --original` until it passes.')
83
+ return 1
84
+ }
85
+ }
86
+
87
+ // 3. front door
88
+ if (!fs.existsSync(path.join(L.rails, 'Gemfile')) || (!app.isLifted(L) && !fs.existsSync(path.join(L.rails, 'config', 'ruby_anything.yml')))) {
89
+ const code = await app.cmdAppFrontDoor([L.root])
90
+ if (code !== 0) return code
91
+ }
92
+
93
+ // 4. replay through Rails and pick the next route
94
+ if (app.isLifted(L)) {
95
+ console.log(green('lifted: the app runs on Rails alone. Run ruby-anything app gate --app in CI.'))
96
+ return 0
97
+ }
98
+ const rc = await app.cmdAppReplay([L.root])
99
+ const { fr, firstCase, route } = nextRoute(L)
100
+ if (rc !== 0) {
101
+ task(L, 'fix the replay', `
102
+ \`ruby-anything app replay ${repo}\` is red. Fix one case at a time:
103
+
104
+ ruby-anything app replay ${repo} --case <name from the report>
105
+
106
+ Read its difference, form one hypothesis, change the Rails code, rerun that case until green, then
107
+ the full replay. Never edit a recorded case without the user's yes (record why in DECISIONS.md).`)
108
+ return 1
109
+ }
110
+ if (fr.fallback === 0) {
111
+ const g = await app.cmdAppGate([L.root])
112
+ if (g !== 0) {
113
+ task(L, 'pass the app gate', `Every route is wired. Make \`ruby-anything gate ${repo} --app\` pass, then \`ruby-anything app lift ${repo}\`.`)
114
+ return 1
115
+ }
116
+ task(L, 'lift', `Fallback rate 0 and the gate passes. Ask the user, then run \`ruby-anything app lift ${repo}\`.`)
117
+ return 0
118
+ }
119
+ const plan = readJSON(L.planJson, { units: [] })
120
+ const unitsInFile = route ? plan.units.filter((u) => u.file === route.file) : []
121
+ task(L, `port ${route ? route.id : `${firstCase.request.method} ${firstCase.request.path}`}`, `
122
+ Fallback rate: ${fr.fallback}/${fr.total}. Next route still answered by the original:
123
+ **${firstCase.request.method} ${firstCase.request.path}**${route ? ` (defined at \`${route.file}:${route.line}\`)` : ''}.
124
+
125
+ 1. Claim it in \`rails/port/MAP.md\`. Run \`ruby-anything rules ${repo}\` and follow every rule.
126
+ 2. Port the logic it needs first, unit by unit (wave 1-2 before 3):
127
+ ${unitsInFile.filter((u) => u.recordable).slice(0, 8).map((u) => ` - \`${u.id}\`: \`ruby-anything bridge ${repo} "${u.id}"\`, \`record\`, port, \`diff\`, \`gate\``).join('\n') || ' - (no recordable functions in that file: port the handler directly)'}
128
+ 3. Write the Rails side: model (ActiveRecord on the same table), route in \`config/routes.rb\`,
129
+ controller action, and for HTML an ERB view with Turbo + Stimulus + Tailwind + daisyUI
130
+ (read the skill's frontend.md). Same URL, status codes, redirects and JSON shape.
131
+ 4. \`ruby-anything app wire ${repo} <unit-name> --route "${route ? `${route.method === 'ANY' ? 'GET' : route.method} ${route.path}` : `${firstCase.request.method} ${firstCase.request.path}`}"\`
132
+ 5. \`ruby-anything app replay ${repo}\`: 100% again, lower fallback rate. Add a Minitest test for the action.
133
+ 6. Mark it done in MAP.md; at a checkpoint from DECISIONS.md, report to the user and wait.`)
134
+ void st
135
+ void yellow
136
+ return 0
137
+ }
138
+
139
+ module.exports = { cmdGo }
package/src/mcp.js ADDED
@@ -0,0 +1,89 @@
1
+ 'use strict'
2
+ // MCP server over stdio (JSON-RPC 2.0, newline-delimited). Every tool runs the same code as the
3
+ // CLI command of the same name and returns its output.
4
+ const path = require('node:path')
5
+ const { spawn } = require('node:child_process')
6
+ const { PKG } = require('./util')
7
+
8
+ const repo = { type: 'string', description: 'Path to the repository being migrated (default: current directory)' }
9
+ const unit = { type: 'string', description: 'Unit id from rails/port/plan.json, e.g. "src/pricing.py:discount"' }
10
+ const flags = { type: 'array', items: { type: 'string' }, description: 'Extra CLI flags, e.g. ["--json"]' }
11
+
12
+ const TOOLS = [
13
+ ['go', 'Move the whole-app migration to its next stage and write rails/port/TASK.md. Pass the command that starts the original app.', { repo, command: { type: 'array', items: { type: 'string' }, description: 'Command that starts the original (reads PORT or uses {port})' }, flags }, (a) => ['go', ...(a.repo ? ['--repo', a.repo] : []), ...(a.flags || []), ...(a.command?.length ? ['--', ...a.command] : [])]],
14
+ ['analyze', 'Plan the migration: languages, frameworks, routes, templates, functions in waves, dependencies with Rails equivalents, and the decisions to settle with the user.', { repo, flags }, (a) => ['analyze', a.repo || '.', '--json', ...(a.flags || [])]],
15
+ ['bridge', 'Create the Ruby skeleton for one unit (app/services) and its TASK.md.', { repo, unit, flags }, (a) => ['bridge', a.repo || '.', a.unit, ...(a.flags || [])]],
16
+ ['record', "Run the original unit on generated edge cases (plus --inputs) and save its behavior to rails/port/cases.", { repo, unit, flags }, (a) => ['record', a.repo || '.', a.unit, ...(a.flags || [])]],
17
+ ['diff', 'Replay the recorded cases against the Ruby port; must be N/N.', { repo, unit, flags }, (a) => ['diff', a.repo || '.', a.unit, '--json', ...(a.flags || [])]],
18
+ ['gate', 'Done means gate passes: recording untouched, no stubs, no copied answers, error paths covered, tests kept, every case matching. Use flags ["--app"] for the whole app.', { repo, unit, flags }, (a) => ['gate', a.repo || '.', ...(a.unit ? [a.unit] : []), '--json', ...(a.flags || [])]],
19
+ ['rules', 'List the behavior rules the user corrected (follow them all), or add one with flags ["--add", "<rule>"].', { repo, flags }, (a) => ['rules', a.repo || '.', ...(a.flags || [])]],
20
+ ['app_record', 'Record the whole original app over HTTP. command starts it.', { repo, command: { type: 'array', items: { type: 'string' } }, flags }, (a) => ['app', 'record', a.repo || '.', '--http', ...(a.flags || []), '--', ...(a.command || [])]],
21
+ ['app_replay', 'Replay every recorded HTTP case against Rails (front door included) or, with ["--original"], the original.', { repo, flags }, (a) => ['app', 'replay', a.repo || '.', '--json', ...(a.flags || [])]],
22
+ ['app_front_door', 'Create the Rails 8 app (Hotwire, Tailwind, daisyUI) that proxies every route not ported yet to the original.', { repo, flags }, (a) => ['app', 'front-door', a.repo || '.', ...(a.flags || [])]],
23
+ ['app_wire', 'Mark a route as answered by Rails (stops proxying it).', { repo, unit: { type: 'string', description: 'Unit name, used for the kill switch' }, route: { type: 'string', description: 'e.g. "GET /users/:id"' }, flags }, (a) => ['app', 'wire', a.repo || '.', a.unit, '--route', a.route, ...(a.flags || [])]],
24
+ ['app_status', 'Measured state: fallback rate, wired routes, units done, routes left. Writes rails/port/PORT_MAP.md.', { repo, flags }, (a) => ['app', 'status', a.repo || '.', '--json', '--write', ...(a.flags || [])]],
25
+ ['app_lift', 'Remove the front door once nothing falls back and every gate passes.', { repo, flags }, (a) => ['app', 'lift', a.repo || '.', ...(a.flags || [])]],
26
+ ['doctor', 'Check the runtimes (Ruby, Rails, and each source language) and print the fix for each missing one.', { flags }, (a) => ['doctor', ...(a.flags || [])]],
27
+ ]
28
+
29
+ function runCli(args, cwd) {
30
+ return new Promise((resolve) => {
31
+ const child = spawn(process.execPath, [path.join(PKG, 'bin', 'ruby-anything.js'), ...args], { cwd, env: { ...process.env, NO_COLOR: '1' } })
32
+ let out = ''
33
+ child.stdout.on('data', (d) => (out += d))
34
+ child.stderr.on('data', (d) => (out += d))
35
+ child.on('close', (code) => resolve({ code, out }))
36
+ })
37
+ }
38
+
39
+ async function cmdMcp() {
40
+ const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n')
41
+ let buf = ''
42
+ process.stdin.setEncoding('utf8')
43
+ process.stdin.on('data', async (chunk) => {
44
+ buf += chunk
45
+ let i
46
+ while ((i = buf.indexOf('\n')) >= 0) {
47
+ const line = buf.slice(0, i).trim()
48
+ buf = buf.slice(i + 1)
49
+ if (!line) continue
50
+ let msg
51
+ try {
52
+ msg = JSON.parse(line)
53
+ } catch {
54
+ continue
55
+ }
56
+ handle(msg).then((res) => res && send(res))
57
+ }
58
+ })
59
+ async function handle(msg) {
60
+ const { id, method, params } = msg
61
+ if (method === 'initialize') {
62
+ return { jsonrpc: '2.0', id, result: { protocolVersion: params?.protocolVersion || '2024-11-05', capabilities: { tools: {}, prompts: {} }, serverInfo: { name: 'ruby-anything', version: require('../package.json').version }, instructions: 'Migrate an app to Ruby on Rails (Hotwire, Tailwind, daisyUI) one piece at a time, checked against the original. Load the ruby-anything skill and start with the go tool.' } }
63
+ }
64
+ if (method === 'notifications/initialized' || id === undefined) return null
65
+ if (method === 'ping') return { jsonrpc: '2.0', id, result: {} }
66
+ if (method === 'tools/list') {
67
+ return { jsonrpc: '2.0', id, result: { tools: TOOLS.map(([name, description, properties]) => ({ name, description, inputSchema: { type: 'object', properties } })) } }
68
+ }
69
+ if (method === 'tools/call') {
70
+ const t = TOOLS.find((x) => x[0] === params?.name)
71
+ if (!t) return { jsonrpc: '2.0', id, error: { code: -32602, message: `unknown tool ${params?.name}` } }
72
+ const r = await runCli(t[3](params.arguments || {}), process.cwd())
73
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: r.out || `(exit ${r.code})` }], isError: r.code !== 0 && !/^(diff|gate|app_replay)$/.test(t[0]) } }
74
+ }
75
+ if (method === 'prompts/list') {
76
+ return { jsonrpc: '2.0', id, result: { prompts: [{ name: 'port_whole_app', description: 'Migrate the whole app to Rails + Hotwire + daisyUI' }, { name: 'port_unit', description: 'Port one function and pass its gate', arguments: [{ name: 'unit', required: true }] }] } }
77
+ }
78
+ if (method === 'prompts/get') {
79
+ const text = params?.name === 'port_unit'
80
+ ? `Port ${params.arguments?.unit} with ruby-anything: bridge, record, write the Ruby, diff until N/N, gate. Follow the ruby-anything skill.`
81
+ : 'Migrate this app to Ruby on Rails with Hotwire, Tailwind and daisyUI using ruby-anything. Follow the ruby-anything skill: start with the go tool, grill me on the decisions, then port route by route until gate --app passes.'
82
+ return { jsonrpc: '2.0', id, result: { messages: [{ role: 'user', content: { type: 'text', text } }] } }
83
+ }
84
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } }
85
+ }
86
+ return new Promise(() => {}) // run until stdin closes
87
+ }
88
+
89
+ module.exports = { cmdMcp, TOOLS }