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.
Files changed (50) 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 +100 -2
  6. package/action.yml +56 -0
  7. package/adapters/node/harness.mjs +348 -0
  8. package/adapters/node/package-lock.json +26 -0
  9. package/adapters/node/package.json +7 -0
  10. package/adapters/polyglot/harness.py +350 -0
  11. package/adapters/polyglot/lang_csharp.py +222 -0
  12. package/adapters/polyglot/lang_go.py +283 -0
  13. package/adapters/polyglot/lang_java.py +510 -0
  14. package/adapters/polyglot/lang_kotlin.py +133 -0
  15. package/adapters/polyglot/lang_php.py +156 -0
  16. package/adapters/polyglot/lang_ruby.py +148 -0
  17. package/adapters/polyglot/lang_rust.py +430 -0
  18. package/adapters/polyglot/lang_swift.py +337 -0
  19. package/adapters/python/harness.py +459 -0
  20. package/bin/ruby-anything.js +10 -0
  21. package/docs/assets/how-it-works-dark.svg +51 -0
  22. package/docs/assets/how-it-works-light.svg +51 -0
  23. package/harness/ruby_replay.rb +155 -0
  24. package/package.json +52 -4
  25. package/skills/ruby-anything/SKILL.md +146 -0
  26. package/skills/ruby-anything/frontend.md +64 -0
  27. package/skills/ruby-anything/languages/csharp.md +43 -0
  28. package/skills/ruby-anything/languages/go.md +36 -0
  29. package/skills/ruby-anything/languages/java.md +54 -0
  30. package/skills/ruby-anything/languages/javascript.md +50 -0
  31. package/skills/ruby-anything/languages/kotlin.md +27 -0
  32. package/skills/ruby-anything/languages/php.md +47 -0
  33. package/skills/ruby-anything/languages/python.md +49 -0
  34. package/skills/ruby-anything/languages/rust.md +31 -0
  35. package/skills/ruby-anything/languages/swift.md +27 -0
  36. package/skills/ruby-anything/whole-app.md +204 -0
  37. package/src/adapters.js +63 -0
  38. package/src/analyze.js +183 -0
  39. package/src/app.js +774 -0
  40. package/src/cli.js +80 -0
  41. package/src/cli_app.js +251 -0
  42. package/src/detect.js +266 -0
  43. package/src/drift.js +124 -0
  44. package/src/effects.js +145 -0
  45. package/src/fromtests.js +105 -0
  46. package/src/go.js +165 -0
  47. package/src/mcp.js +89 -0
  48. package/src/setup.js +106 -0
  49. package/src/units.js +452 -0
  50. package/src/util.js +312 -0
package/src/cli.js ADDED
@@ -0,0 +1,80 @@
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] [--pin-clock] [--from-tests -- <test cmd>]
16
+ the original's behavior -> rails/port/cases
17
+ diff <repo> <unit> [--json] replay the cases against the Ruby port (must be N/N)
18
+ gate <repo> <unit>|--all|--app done means gate passes
19
+ rules <repo> [--add "<rule>"] behavior the user corrected; every unit keeps it
20
+ drift <repo> has the original changed since recording? (units + app)
21
+
22
+ Whole app
23
+ app record <repo> --http [--inputs f] [--db-reset cmd] [--db-dump cmd]
24
+ [--effect-env NAME=http|smtp|smtp_host|smtp_port,...] -- <start command>
25
+ app front-door <repo> Rails 8 app that proxies routes not ported yet to the original
26
+ app wire <repo> <unit> --route "GET /path/:id"
27
+ app replay <repo> [--original] [--case name] [--mode text|status|exact]
28
+ app status <repo> [--write] fallback rate, wired routes, units; writes PORT_MAP.md
29
+ app lift <repo> remove the front door once nothing falls back
30
+
31
+ Agents
32
+ mcp MCP server on stdio (the same steps as tools)
33
+
34
+ Recording runs the original code: work on a copy, with a test database.`
35
+
36
+ async function main(argv) {
37
+ const [cmd, ...rest] = argv
38
+ switch (cmd) {
39
+ case undefined:
40
+ case 'help':
41
+ case '--help':
42
+ case '-h':
43
+ console.log(HELP)
44
+ return 0
45
+ case '--version':
46
+ case '-v':
47
+ console.log(require('../package.json').version)
48
+ return 0
49
+ case 'setup':
50
+ return require('./setup').cmdSetup(rest)
51
+ case 'doctor':
52
+ return require('./setup').cmdDoctor(rest)
53
+ case 'analyze':
54
+ return require('./analyze').cmdAnalyze(rest)
55
+ case 'go':
56
+ return require('./go').cmdGo(rest)
57
+ case 'bridge':
58
+ return require('./units').cmdBridge(rest)
59
+ case 'record':
60
+ return require('./units').cmdRecord(rest)
61
+ case 'diff':
62
+ return require('./units').cmdDiff(rest)
63
+ case 'gate':
64
+ return require('./units').cmdGate(rest)
65
+ case 'rules':
66
+ return require('./units').cmdRules(rest)
67
+ case 'app':
68
+ return require('./app').cmdApp(rest)
69
+ case 'drift':
70
+ return require('./drift').cmdDrift(rest)
71
+ case 'map':
72
+ return require('./app').cmdAppStatus([...rest, '--write'])
73
+ case 'mcp':
74
+ return require('./mcp').cmdMcp(rest)
75
+ default:
76
+ throw new Error(`unknown command "${cmd}". Run ruby-anything help.`)
77
+ }
78
+ }
79
+
80
+ module.exports = { main }
package/src/cli_app.js ADDED
@@ -0,0 +1,251 @@
1
+ 'use strict'
2
+ // Whole CLI apps: record what each invocation does (exit code, stdout, stderr, files written),
3
+ // put a Ruby front door in front of the original (rails/bin/<name>: ported commands run in Rails,
4
+ // the rest exec the original), wire commands one at a time, replay, lift.
5
+ //
6
+ // ruby-anything app record <repo> --cli --inputs cli.jsonl -- python tool.py
7
+ // cli.jsonl: {"name": "...", "args": ["export", "--csv"], "stdin": "...", "env": {"K": "v"}}
8
+ const fs = require('node:fs')
9
+ const os = require('node:os')
10
+ const path = require('node:path')
11
+ const crypto = require('node:crypto')
12
+ const { spawnSync } = require('node:child_process')
13
+ const { IS_WIN, readJSON, writeJSON, writeFile, slug, camel, canon, relTo, green, red, yellow, bold, dim } = require('./util')
14
+
15
+ const HEAVY = new Set(['node_modules', 'vendor', '.venv', 'venv', '.git', 'target', '.gradle', 'bin', 'obj'])
16
+ const SKIP = new Set(['rails', '.ra-runs'])
17
+
18
+ // A throwaway copy of the repo to run one invocation in. Heavy folders are linked, not copied.
19
+ function sandboxCopy(root) {
20
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ra-cli-'))
21
+ for (const e of fs.readdirSync(root, { withFileTypes: true })) {
22
+ if (SKIP.has(e.name)) continue
23
+ const from = path.join(root, e.name)
24
+ const to = path.join(dir, e.name)
25
+ if (e.isDirectory() && HEAVY.has(e.name)) {
26
+ try {
27
+ fs.symlinkSync(from, to, IS_WIN ? 'junction' : 'dir')
28
+ } catch {
29
+ fs.cpSync(from, to, { recursive: true })
30
+ }
31
+ } else fs.cpSync(from, to, { recursive: true })
32
+ }
33
+ return dir
34
+ }
35
+
36
+ function snapshot(dir) {
37
+ const out = {}
38
+ const walk = (d, rel) => {
39
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
40
+ if (HEAVY.has(e.name) || SKIP.has(e.name) || e.name === '__pycache__') continue
41
+ const p = path.join(d, e.name)
42
+ const r = rel ? `${rel}/${e.name}` : e.name
43
+ if (e.isDirectory()) walk(p, r)
44
+ else if (e.isFile()) out[r] = crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex')
45
+ }
46
+ }
47
+ walk(dir, '')
48
+ return out
49
+ }
50
+
51
+ function fileChanges(dir, before) {
52
+ const after = snapshot(dir)
53
+ const out = []
54
+ for (const [p, sha] of Object.entries(after)) {
55
+ if (before[p] === sha) continue
56
+ const buf = fs.readFileSync(path.join(dir, p))
57
+ const text = buf.length <= 65536 && !buf.includes(0) ? buf.toString('utf8').replace(/\r\n/g, '\n').split('\n') : null
58
+ out.push({ path: p, status: before[p] ? 'changed' : 'added', ...(text ? { text } : { sha256: sha }) })
59
+ }
60
+ for (const p of Object.keys(before)) if (!(p in after)) out.push({ path: p, status: 'deleted' })
61
+ return out.sort((x, y) => (x.path < y.path ? -1 : 1))
62
+ }
63
+
64
+ const lines = (s) => String(s || '').replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n').filter((l, i, a) => a.length > 1 || l !== '')
65
+
66
+ // Runs `command + input.args` in a fresh copy of the repo.
67
+ function invoke(root, command, input, extraEnv = {}) {
68
+ const dir = sandboxCopy(root)
69
+ try {
70
+ const before = snapshot(dir)
71
+ const argv = [...command, ...(input.args || [])]
72
+ const r = spawnSync(argv[0], argv.slice(1), {
73
+ cwd: dir,
74
+ input: input.stdin || '',
75
+ encoding: 'utf8',
76
+ env: { ...process.env, ...extraEnv, ...(input.env || {}) },
77
+ shell: IS_WIN,
78
+ timeout: 120000,
79
+ maxBuffer: 64 << 20,
80
+ })
81
+ if (r.error && r.error.code === 'ETIMEDOUT') return { code: null, stdout: [], stderr: ['timed out after 120s'], files: [] }
82
+ return { code: r.status, stdout: lines(r.stdout), stderr: lines(r.stderr), files: fileChanges(dir, before) }
83
+ } finally {
84
+ fs.rmSync(dir, { recursive: true, force: true })
85
+ }
86
+ }
87
+
88
+ function cliDir(L) {
89
+ return path.join(L.appCases, 'cli')
90
+ }
91
+
92
+ function cliCases(L) {
93
+ const d = cliDir(L)
94
+ return fs.existsSync(d) ? fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort().map((f) => readJSON(path.join(d, f))) : []
95
+ }
96
+
97
+ // ------------------------------------------------------------------ record
98
+ function recordCli(L, a, s, mergeNoise) {
99
+ if (!a.inputs) throw new Error('usage: ruby-anything app record <repo> --cli --inputs cli.jsonl -- <command that runs the original>\n cli.jsonl: {"name", "args": [...], "stdin", "env"} per line')
100
+ const inputs = fs.readFileSync(path.resolve(a.inputs), 'utf8').split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l))
101
+ const dir = cliDir(L)
102
+ fs.rmSync(dir, { recursive: true, force: true })
103
+ const noisy = []
104
+ inputs.forEach((input, i) => {
105
+ const first = invoke(L.root, a.rest, input)
106
+ const second = invoke(L.root, a.rest, input)
107
+ const output = mergeNoise(first, second)
108
+ if (canon(first) !== canon(second)) noisy.push(input.name || (input.args || []).join(' '))
109
+ const name = `${String(i + 1).padStart(3, '0')}-${slug(input.name || (input.args || []).join(' ') || 'no-args').slice(0, 50)}`
110
+ writeFile(path.join(dir, `${name}.json`), JSON.stringify({ name, kind: 'cli', input: { args: input.args || [], stdin: input.stdin || '', env: input.env || {} }, output }, null, 2) + '\n')
111
+ console.log(` ${[...a.rest, ...(input.args || [])].join(' ')} -> exit ${first.code}${first.files.length ? dim(` (${first.files.length} files written)`) : ''}`)
112
+ })
113
+ s.kind = 'cli'
114
+ s.original = a.rest
115
+ s.cli_name = s.cli_name || a.name || slug(path.basename(L.root)) || 'app'
116
+ if (a.ignoreStderr) s.ignore_stderr = true
117
+ writeJSON(L.settings, s)
118
+ console.log(`${inputs.length} CLI cases -> ${relTo(L.root, dir)}`)
119
+ if (noisy.length) console.log(yellow(`${noisy.length} invocations changed between two runs: [..] wildcards were added (${noisy.slice(0, 5).join(', ')})`))
120
+ console.log(`next: ruby-anything app replay ${relTo(process.cwd(), L.root) || '.'} --original (the original must pass 100%)`)
121
+ return 0
122
+ }
123
+
124
+ // ------------------------------------------------------------------ compare / replay
125
+ function compareCli(rec, got, matches, s) {
126
+ if (rec.code !== got.code) return `exit code ${rec.code} vs ${got.code}`
127
+ if (!matches(rec.stdout, got.stdout)) {
128
+ const i = rec.stdout.findIndex((l, k) => !matches(l, got.stdout[k] ?? null))
129
+ return `stdout line ${i + 1}: ${JSON.stringify(rec.stdout[i] ?? '(end)').slice(0, 80)} vs ${JSON.stringify(got.stdout[i] ?? '(end)').slice(0, 80)}`
130
+ }
131
+ if (!s.ignore_stderr && !matches(rec.stderr, got.stderr)) return `stderr differs: ${JSON.stringify(got.stderr.slice(0, 2)).slice(0, 120)}`
132
+ if (!matches(rec.files, got.files)) {
133
+ const want = rec.files.map((f) => `${f.status} ${f.path}`)
134
+ const have = got.files.map((f) => `${f.status} ${f.path}`)
135
+ return canon(want) !== canon(have) ? `files written: expected [${want.join(', ')}], got [${have.join(', ')}]` : `contents of ${rec.files.find((f, k) => !matches(f, got.files[k])).path} differ`
136
+ }
137
+ return null
138
+ }
139
+
140
+ function config(L) {
141
+ return readJSON(path.join(L.rails, 'config', 'ruby_anything.yml'), null)
142
+ }
143
+
144
+ function wiredCommand(cfg, args) {
145
+ if (!cfg) return null
146
+ const cmd = args[0]
147
+ const cmds = cfg.commands || []
148
+ return cmds.find((w) => w.command === cmd) || (cmds.find((w) => w.command === '*') && !cmds.some((w) => w.command === cmd) ? cmds.find((w) => w.command === '*') : null)
149
+ }
150
+
151
+ function fallbackCli(L, cases) {
152
+ const cfg = config(L)
153
+ if (cfg && cfg.lifted) return { fallback: 0, total: cases.length, names: [] }
154
+ const fb = cases.filter((c) => !wiredCommand(cfg, c.input.args))
155
+ return { fallback: fb.length, total: cases.length, names: fb.map((c) => c.name) }
156
+ }
157
+
158
+ function replayCli(L, a, s, cases, matches) {
159
+ let command
160
+ if (a.original) command = s.original
161
+ else if (a.build) command = String(a.build).split(' ')
162
+ else {
163
+ const script = path.join(L.rails, 'bin', s.cli_name)
164
+ if (!fs.existsSync(script)) throw new Error(`no CLI front door: ruby-anything app front-door ${relTo(process.cwd(), L.root) || '.'}`)
165
+ command = ['ruby', script]
166
+ }
167
+ const env = a.noOriginal ? { RUBY_ANYTHING_NO_FALLBACK: '1' } : {}
168
+ return cases
169
+ .filter((c) => !a.case || c.name.includes(a.case))
170
+ .map((c) => {
171
+ const got = invoke(L.root, command, c.input, env)
172
+ const why = compareCli(c.output, got, matches, s)
173
+ return { name: c.name, ok: !why, why, request: [s.cli_name, ...c.input.args].join(' ') }
174
+ })
175
+ }
176
+
177
+ // ------------------------------------------------------------------ front door
178
+ const CLI_FRONT_DOOR = (name) => `#!/usr/bin/env ruby
179
+ # frozen_string_literal: true
180
+
181
+ # ruby-anything front door for the ${name} CLI. Commands listed in config/ruby_anything.yml run
182
+ # here, in Ruby (app/cli/<unit>.rb, Cli::<Unit>.call(argv) returning the exit code); every other
183
+ # invocation execs the original. Kill switch: RUBY_ANYTHING_UNIT_<NAME>=original.
184
+ # \`ruby-anything app lift\` sets lifted: true once nothing falls back.
185
+ require "json"
186
+
187
+ ROOT = File.expand_path("..", __dir__)
188
+ cfg = JSON.parse(File.read(File.join(ROOT, "config", "ruby_anything.yml"))) rescue {}
189
+ commands = Array(cfg["commands"])
190
+ entry = commands.find { |c| c["command"] == ARGV.first } ||
191
+ (commands.find { |c| c["command"] == "*" } unless commands.any? { |c| c["command"] == ARGV.first })
192
+ entry = nil if entry && ENV["RUBY_ANYTHING_UNIT_#{entry['unit'].upcase.gsub(/[^A-Z0-9]/, '_')}"] == "original"
193
+
194
+ if entry
195
+ ENV["RAILS_ENV"] ||= "development"
196
+ require File.join(ROOT, "config", "environment")
197
+ unit = entry["unit"].split("_").map(&:capitalize).join
198
+ status = Object.const_get("Cli::#{unit}").call(ARGV.dup)
199
+ $stdout.flush
200
+ exit(status.is_a?(Integer) ? status : 0)
201
+ elsif cfg["lifted"] || ENV["RUBY_ANYTHING_NO_FALLBACK"]
202
+ warn "${name}: unknown command #{ARGV.first.inspect}"
203
+ exit 64
204
+ else
205
+ exec(*Array(cfg["original"]), *ARGV)
206
+ end
207
+ `
208
+
209
+ function frontDoorCli(L, s) {
210
+ const name = s.cli_name || 'app'
211
+ const script = path.join(L.rails, 'bin', name)
212
+ writeFile(script, CLI_FRONT_DOOR(name))
213
+ try {
214
+ fs.chmodSync(script, 0o755)
215
+ } catch {}
216
+ const cfgFile = path.join(L.rails, 'config', 'ruby_anything.yml')
217
+ const cfg = readJSON(cfgFile, null) || { commands: [] }
218
+ cfg.original = s.original
219
+ writeJSON(cfgFile, cfg) // JSON is valid YAML
220
+ writeFile(
221
+ path.join(L.rails, 'app', 'cli', '.keep'),
222
+ '',
223
+ )
224
+ console.log(`CLI front door: ${relTo(process.cwd(), script)} runs wired commands in Ruby and execs the original for the rest.`)
225
+ }
226
+
227
+ function wireCommand(L, unit, command, remove) {
228
+ const cfgFile = path.join(L.rails, 'config', 'ruby_anything.yml')
229
+ const cfg = readJSON(cfgFile, null)
230
+ if (!cfg) throw new Error(`no CLI front door: ruby-anything app front-door ${relTo(process.cwd(), L.root) || '.'}`)
231
+ cfg.commands = (cfg.commands || []).filter((c) => c.command !== command)
232
+ if (!remove) cfg.commands.push({ command, unit: slug(unit) })
233
+ writeJSON(cfgFile, cfg)
234
+ const klass = camel(slug(unit))
235
+ const file = path.join(L.rails, 'app', 'cli', `${slug(unit)}.rb`)
236
+ if (!remove && !fs.existsSync(file)) {
237
+ writeFile(file, `# frozen_string_literal: true\n\n# \`${command === '*' ? '(default command)' : command}\` of the original CLI. Return the exit code.\nmodule Cli\n class ${klass}\n def self.call(argv)\n raise NotImplementedError, "port the ${command} command"\n end\n end\nend\n`)
238
+ console.log(`created ${relTo(L.root, file)}: Cli::${klass}.call(argv)`)
239
+ }
240
+ return cfg
241
+ }
242
+
243
+ function liftCli(L) {
244
+ const cfgFile = path.join(L.rails, 'config', 'ruby_anything.yml')
245
+ const cfg = readJSON(cfgFile, {})
246
+ cfg.lifted = true
247
+ delete cfg.original
248
+ writeJSON(cfgFile, cfg)
249
+ }
250
+
251
+ module.exports = { recordCli, replayCli, frontDoorCli, wireCommand, fallbackCli, liftCli, cliCases, compareCli, invoke }
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 }