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/drift.js ADDED
@@ -0,0 +1,124 @@
1
+ 'use strict'
2
+ // drift: has the original changed since it was recorded? Re-runs the original on every recorded
3
+ // unit case and HTTP case and lists what now differs, plus routes no case records.
4
+ // Run it after pulling upstream changes, and in CI while the original is still developed.
5
+ const fs = require('node:fs')
6
+ const path = require('node:path')
7
+ const adapters = require('./adapters')
8
+ const app = require('./app')
9
+ const { layout, loadState, readJSON, readCases, parseArgs, sha256, canon, plain, green, red, yellow, bold, relTo } = require('./util')
10
+ const { loadPlan, compareCase } = require('./units')
11
+
12
+ async function unitDrift(L, log) {
13
+ const plan = loadPlan(L)
14
+ const st = loadState(L)
15
+ const out = []
16
+ for (const [id, entry] of Object.entries(st.units || {})) {
17
+ if (!entry.cases_file) continue
18
+ const u = plan.units.find((x) => x.id === id)
19
+ if (!u) {
20
+ out.push({ unit: id, missing: true })
21
+ continue
22
+ }
23
+ const src = path.join(L.root, u.file)
24
+ if (!fs.existsSync(src)) {
25
+ out.push({ unit: id, missing: true })
26
+ continue
27
+ }
28
+ const sourceChanged = entry.source_sha && sha256(fs.readFileSync(src)) !== entry.source_sha
29
+ const cases = readCases(path.join(L.root, entry.cases_file))
30
+ log(`re-running ${id} on ${cases.length} recorded cases`)
31
+ let fresh
32
+ try {
33
+ fresh = await adapters.record(L.root, u.lang, {
34
+ moduleFile: u.file,
35
+ fn: u.name,
36
+ cases: cases.map((c) => ({ ref: c.ref, args: c.args, kwargs: c.kwargs, origin: c.origin })),
37
+ count: 0,
38
+ pinClock: !!entry.pin_clock,
39
+ })
40
+ } catch (e) {
41
+ out.push({ unit: id, error: e.message.split('\n')[0], sourceChanged })
42
+ continue
43
+ }
44
+ const byRef = Object.fromEntries(fresh.cases.map((c) => [c.ref, c]))
45
+ const changed = []
46
+ for (const c of cases) {
47
+ const now = byRef[c.ref]
48
+ if (!now) continue
49
+ const r = compareCase(c, now, { messages: true })
50
+ if (!r.ok) changed.push({ ref: c.ref, args: plain(c.args), at: r.at, detail: r.detail })
51
+ }
52
+ out.push({ unit: id, total: cases.length, changed, sourceChanged })
53
+ }
54
+ return out
55
+ }
56
+
57
+ async function cmdDrift(argv) {
58
+ const a = parseArgs(argv, ['json', 'noApp', 'noUnits'])
59
+ const L = layout(a._[0])
60
+ const repo = relTo(process.cwd(), L.root) || '.'
61
+ const log = a.json ? () => {} : (m) => console.error(m)
62
+ const report = { units: [], app: null, unrecorded: [] }
63
+
64
+ if (!a.noUnits && fs.existsSync(L.planJson)) report.units = await unitDrift(L, log)
65
+
66
+ const cases = app.loadCases(L)
67
+ if (!a.noApp && cases.length) {
68
+ log(`replaying ${cases.length} HTTP cases against the original`)
69
+ const quiet = console.log
70
+ const write = process.stdout.write.bind(process.stdout)
71
+ console.log = () => {}
72
+ process.stdout.write = () => true
73
+ try {
74
+ await app.cmdAppReplay([L.root, '--original', '--json'])
75
+ } catch (e) {
76
+ report.app = { error: e.message.split('\n')[0] }
77
+ } finally {
78
+ console.log = quiet
79
+ process.stdout.write = write
80
+ }
81
+ if (!report.app) {
82
+ const rep = readJSON(path.join(L.reports, 'last-replay.json'))
83
+ report.app = { total: rep.total, changed: rep.failures }
84
+ }
85
+ // routes in the code that no case records (new endpoints upstream)
86
+ const plan = readJSON(L.planJson, { routes: [] })
87
+ const recorded = cases.filter((c) => c.request).map((c) => `${c.request.method} ${c.request.path.split('?')[0]}`)
88
+ for (const r of cases[0] && cases[0].kind === 'cli' ? [] : plan.routes || []) {
89
+ const re = new RegExp('^' + (r.method === 'ANY' ? '[A-Z]+' : r.method) + ' ' + r.path.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/:\w+/g, '[^/]+') + '/?$')
90
+ if (!recorded.some((x) => re.test(x))) report.unrecorded.push(r.id)
91
+ }
92
+ }
93
+
94
+ const drifted = report.units.filter((u) => u.missing || u.error || (u.changed && u.changed.length) || u.sourceChanged)
95
+ const appChanged = report.app && (report.app.error || report.app.changed.length)
96
+ if (a.json) {
97
+ process.stdout.write(JSON.stringify(report, null, 2) + '\n')
98
+ } else {
99
+ for (const u of report.units) {
100
+ if (u.missing) console.log(red(`gone ${u.unit}: the function is no longer in the original`))
101
+ else if (u.error) console.log(red(`error ${u.unit}: ${u.error}`))
102
+ else if (u.changed.length) {
103
+ console.log(red(`drift ${u.unit}: ${u.changed.length}/${u.total} recorded cases now answer differently`))
104
+ console.log(` e.g. ${u.changed[0].ref} args=${JSON.stringify(u.changed[0].args).slice(0, 80)} at ${u.changed[0].at}: ${u.changed[0].detail}`)
105
+ } else if (u.sourceChanged) console.log(yellow(`same ${u.unit} (${u.total} cases), but its file was edited since recording: record again to cover new paths`))
106
+ else console.log(green(`same ${u.unit} (${u.total} cases)`))
107
+ }
108
+ if (report.app) {
109
+ if (report.app.error) console.log(red(`app: ${report.app.error}`))
110
+ else if (report.app.changed.length) {
111
+ console.log(red(`app drift: ${report.app.changed.length}/${report.app.total} HTTP cases now answer differently`))
112
+ for (const f of report.app.changed.slice(0, 5)) console.log(` ${f.request || f.name}: ${f.why}`)
113
+ } else console.log(green(`app: all ${report.app.total} HTTP cases still answer the same`))
114
+ }
115
+ if (report.unrecorded.length) console.log(yellow(`${report.unrecorded.length} routes in the code have no recorded case: ${report.unrecorded.slice(0, 6).join(', ')}`))
116
+ if (drifted.length || appChanged) {
117
+ console.log(bold('\nThe original changed. For each drifted unit: ruby-anything record, then diff: the new mismatches are what changed upstream.'))
118
+ if (appChanged) console.log(bold(`For the app: ruby-anything app record ${repo} ... again (keep the same inputs), then app replay.`))
119
+ }
120
+ }
121
+ return drifted.length || appChanged || report.unrecorded.length ? 1 : 0
122
+ }
123
+
124
+ module.exports = { cmdDrift }
package/src/effects.js ADDED
@@ -0,0 +1,145 @@
1
+ 'use strict'
2
+ // Side effects of a request: outgoing HTTP calls and emails, captured by local stand-in servers
3
+ // the app is pointed at through environment variables, plus a database dump after writes.
4
+ //
5
+ // --effect-env PAYMENT_API_URL=http,SMTP_URL=smtp,MAIL_HOST=smtp_host,MAIL_PORT=smtp_port
6
+ // --db-dump "sqlite3 db.sqlite3 .dump"
7
+ const http = require('node:http')
8
+ const net = require('node:net')
9
+ const { parseJSON, runSync } = require('./util')
10
+
11
+ const KINDS = ['http', 'smtp', 'smtp_host', 'smtp_port']
12
+
13
+ function parseEffectEnv(spec) {
14
+ if (!spec) return []
15
+ return String(spec)
16
+ .split(',')
17
+ .map((x) => x.trim())
18
+ .filter(Boolean)
19
+ .map((pair) => {
20
+ const [name, kind] = pair.split('=')
21
+ if (!name || !KINDS.includes(kind)) throw new Error(`--effect-env takes NAME=KIND pairs, KIND one of ${KINDS.join(', ')}: got "${pair}"`)
22
+ return { name, kind }
23
+ })
24
+ }
25
+
26
+ function listen(server) {
27
+ return new Promise((resolve, reject) => {
28
+ server.once('error', reject)
29
+ server.listen(0, '127.0.0.1', () => resolve(server.address().port))
30
+ })
31
+ }
32
+
33
+ function bodyValue(text, type) {
34
+ if (!text) return null
35
+ if (/json/.test(type || '')) {
36
+ try {
37
+ return parseJSON(text)
38
+ } catch {}
39
+ }
40
+ if (/x-www-form-urlencoded/.test(type || '')) return Object.fromEntries(new URLSearchParams(text))
41
+ return text
42
+ }
43
+
44
+ // Stand-in for an external API: records each call and answers from `replies` or with 200 {}.
45
+ async function httpSink(log, replies = []) {
46
+ const server = http.createServer((req, res) => {
47
+ let data = ''
48
+ req.on('data', (d) => (data += d))
49
+ req.on('end', () => {
50
+ const type = (req.headers['content-type'] || '').split(';')[0]
51
+ log.push({ kind: 'http', method: req.method, path: req.url, type: type || null, body: bodyValue(data, type) })
52
+ const r = replies.find((x) => (!x.method || x.method === req.method) && (!x.path || x.path === req.url.split('?')[0])) || {}
53
+ const body = r.body === undefined ? {} : r.body
54
+ res.writeHead(r.status || 200, { 'content-type': typeof body === 'string' ? 'text/plain' : 'application/json' })
55
+ res.end(typeof body === 'string' ? body : JSON.stringify(body))
56
+ })
57
+ })
58
+ return { server, port: await listen(server) }
59
+ }
60
+
61
+ // Minimal SMTP server: enough for nodemailer, smtplib, Action Mailer, JavaMail, PHPMailer, net/smtp.
62
+ async function smtpSink(log) {
63
+ const server = net.createServer((sock) => {
64
+ let buf = ''
65
+ let inData = false
66
+ let mail = { from: null, to: [], data: '' }
67
+ const say = (s) => sock.write(s + '\r\n')
68
+ say('220 ruby-anything ESMTP')
69
+ sock.on('data', (d) => {
70
+ buf += d.toString('utf8')
71
+ let i
72
+ while ((i = buf.indexOf('\r\n')) >= 0 || (inData && buf.includes('\r\n.\r\n'))) {
73
+ if (inData) {
74
+ const end = buf.indexOf('\r\n.\r\n')
75
+ if (end < 0) return
76
+ mail.data = buf.slice(0, end)
77
+ buf = buf.slice(end + 5)
78
+ inData = false
79
+ const [head, ...rest] = mail.data.split(/\r?\n\r?\n/)
80
+ const header = (name) => (head.match(new RegExp(`^${name}:\\s*(.*)$`, 'mi')) || [])[1] || null
81
+ log.push({ kind: 'smtp', from: mail.from, to: mail.to.sort(), subject: header('Subject'), body: rest.join('\n\n').replace(/\r\n/g, '\n').trim() })
82
+ mail = { from: null, to: [], data: '' }
83
+ say('250 OK queued')
84
+ continue
85
+ }
86
+ const line = buf.slice(0, i)
87
+ buf = buf.slice(i + 2)
88
+ const cmd = line.slice(0, 4).toUpperCase()
89
+ if (cmd === 'EHLO') sock.write('250-ruby-anything\r\n250-8BITMIME\r\n250 SMTPUTF8\r\n')
90
+ else if (cmd === 'HELO') say('250 ruby-anything')
91
+ else if (cmd === 'MAIL') (mail.from = (line.match(/<([^>]*)>/) || [])[1] || null), say('250 OK')
92
+ else if (cmd === 'RCPT') mail.to.push((line.match(/<([^>]*)>/) || [])[1]), say('250 OK')
93
+ else if (cmd === 'DATA') (inData = true), say('354 End data with <CR><LF>.<CR><LF>')
94
+ else if (cmd === 'QUIT') say('221 Bye'), sock.end()
95
+ else if (cmd === 'RSET') (mail = { from: null, to: [], data: '' }), say('250 OK')
96
+ else say('250 OK') // NOOP, AUTH-less clients, STARTTLS refused politely below
97
+ }
98
+ })
99
+ sock.on('error', () => {})
100
+ })
101
+ return { server, port: await listen(server) }
102
+ }
103
+
104
+ // Starts the sinks the env spec needs. Returns { env, take, stop }.
105
+ async function startEffects(spec, { replies } = {}) {
106
+ const pairs = parseEffectEnv(spec)
107
+ const log = []
108
+ const env = {}
109
+ const servers = []
110
+ let httpPort = null
111
+ let smtpPort = null
112
+ if (pairs.some((p) => p.kind === 'http')) {
113
+ const s = await httpSink(log, replies)
114
+ servers.push(s.server)
115
+ httpPort = s.port
116
+ }
117
+ if (pairs.some((p) => p.kind.startsWith('smtp'))) {
118
+ const s = await smtpSink(log)
119
+ servers.push(s.server)
120
+ smtpPort = s.port
121
+ }
122
+ for (const p of pairs) {
123
+ if (p.kind === 'http') env[p.name] = `http://127.0.0.1:${httpPort}`
124
+ if (p.kind === 'smtp') env[p.name] = `smtp://127.0.0.1:${smtpPort}`
125
+ if (p.kind === 'smtp_host') env[p.name] = '127.0.0.1'
126
+ if (p.kind === 'smtp_port') env[p.name] = String(smtpPort)
127
+ }
128
+ return {
129
+ env,
130
+ active: pairs.length > 0,
131
+ take: () => log.splice(0, log.length),
132
+ stop: () => servers.forEach((s) => s.close()),
133
+ }
134
+ }
135
+
136
+ function dbDump(cmd, cwd) {
137
+ if (!cmd) return null
138
+ const r = runSync(cmd, [], { cwd, shell: true })
139
+ if (r.code !== 0) throw new Error(`--db-dump failed: ${r.stderr.trim().slice(-300)}`)
140
+ return r.stdout.replace(/\r\n/g, '\n').split('\n').filter((l) => l.trim())
141
+ }
142
+
143
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
144
+
145
+ module.exports = { startEffects, parseEffectEnv, dbDump, sleep }
@@ -0,0 +1,105 @@
1
+ 'use strict'
2
+ // record --from-tests: run the original's own test suite with the unit's function instrumented,
3
+ // and turn every call it makes into a recorded case. The source file is edited for the run only
4
+ // and restored byte for byte afterwards (also after a crash: a .ra-backup copy is kept until then).
5
+ const fs = require('node:fs')
6
+ const os = require('node:os')
7
+ const path = require('node:path')
8
+ const { spawnSync } = require('node:child_process')
9
+ const { IS_WIN, parseJSON } = require('./util')
10
+
11
+ const MAX_CALLS = 2000
12
+
13
+ function pyInstrument(text, fn, capFile) {
14
+ if (!new RegExp(`^(async\\s+)?def\\s+${fn}\\s*\\(`, 'm').test(text)) return null
15
+ return `${text.replace(/\s*$/, '\n')}
16
+
17
+ # --- ruby-anything --from-tests capture (removed after the run) ---
18
+ def __ra_wrap(__ra_f):
19
+ import functools as __ra_ft, json as __ra_json
20
+ @__ra_ft.wraps(__ra_f)
21
+ def __ra_w(*a, **k):
22
+ try:
23
+ with open(${JSON.stringify(capFile)}, "a", encoding="utf-8") as __ra_o:
24
+ __ra_o.write(__ra_json.dumps({"args": list(a), "kwargs": k}, allow_nan=False) + "\\n")
25
+ except Exception:
26
+ pass
27
+ return __ra_f(*a, **k)
28
+ return __ra_w
29
+ ${fn} = __ra_wrap(${fn})
30
+ `
31
+ }
32
+
33
+ function jsInstrument(text, fn, capFile) {
34
+ const re = new RegExp(`(^|\\n)([ \\t]*(?:export\\s+(?:default\\s+)?)?)(async\\s+)?function\\s*(\\*?)\\s*${fn}\\s*\\(`)
35
+ const m = re.exec(text)
36
+ if (!m || m[4]) return null // generators stay out
37
+ const cap = `(function(__a){try{var __fs=(typeof require!=="undefined"?require("fs"):process.getBuiltinModule("fs"));__fs.appendFileSync(${JSON.stringify(capFile)},JSON.stringify({args:__a})+"\\n")}catch(e){}})`
38
+ const wrapper = `${m[1]}${m[2]}function ${fn}(...__ra_a){${cap}(__ra_a);return __ra_orig_${fn}.apply(this,__ra_a)}\n${m[3] || ''}function __ra_orig_${fn}(`
39
+ return text.slice(0, m.index) + wrapper + text.slice(m.index + m[0].length)
40
+ }
41
+
42
+ const INSTRUMENT = { python: pyInstrument, javascript: jsInstrument, typescript: jsInstrument }
43
+
44
+ function restoreLeftovers(file) {
45
+ const bak = file + '.ra-backup'
46
+ if (fs.existsSync(bak)) {
47
+ fs.copyFileSync(bak, file)
48
+ fs.rmSync(bak)
49
+ }
50
+ }
51
+
52
+ // Returns [{args, kwargs, origin: 'test'}] for every distinct JSON-encodable call.
53
+ function captureFromTests(root, unit, command, { timeoutMs = 900000, log = () => {} } = {}) {
54
+ const instrument = INSTRUMENT[unit.lang]
55
+ if (!instrument) throw new Error(`--from-tests supports Python, TypeScript and JavaScript; record ${unit.lang} with --inputs`)
56
+ if (!command.length) throw new Error('usage: ruby-anything record <repo> <unit> --from-tests -- <test command, e.g. pytest or npx jest>')
57
+ if (unit.owner) throw new Error(`${unit.id} is a method; --from-tests instruments top-level functions`)
58
+ const file = path.join(root, unit.file)
59
+ restoreLeftovers(file)
60
+ const original = fs.readFileSync(file)
61
+ const capFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'ra-tests-')), 'calls.jsonl').split(path.sep).join('/')
62
+ const edited = instrument(original.toString('utf8'), unit.name, capFile)
63
+ if (!edited) throw new Error(`could not instrument ${unit.name} in ${unit.file} (only plain function declarations)`)
64
+ fs.copyFileSync(file, file + '.ra-backup')
65
+ const restore = () => {
66
+ fs.writeFileSync(file, original)
67
+ fs.rmSync(file + '.ra-backup', { force: true })
68
+ }
69
+ const onSignal = () => {
70
+ restore()
71
+ process.exit(130)
72
+ }
73
+ process.once('SIGINT', onSignal)
74
+ let run
75
+ try {
76
+ fs.writeFileSync(file, edited)
77
+ log(`running the tests with ${unit.name} instrumented: ${command.join(' ')}`)
78
+ const env = { ...process.env, CI: '1' }
79
+ delete env.NODE_TEST_CONTEXT // a parent `node --test` would swallow the child's tests
80
+ run = spawnSync(command[0], command.slice(1), { cwd: root, encoding: 'utf8', shell: IS_WIN, timeout: timeoutMs, env, maxBuffer: 256 << 20 })
81
+ } finally {
82
+ restore()
83
+ process.removeListener('SIGINT', onSignal)
84
+ }
85
+ const seen = new Set()
86
+ const calls = []
87
+ if (fs.existsSync(capFile)) {
88
+ for (const line of fs.readFileSync(capFile, 'utf8').split('\n')) {
89
+ if (!line.trim() || calls.length >= MAX_CALLS) continue
90
+ let c
91
+ try {
92
+ c = parseJSON(line)
93
+ } catch {
94
+ continue
95
+ }
96
+ const key = line
97
+ if (seen.has(key)) continue
98
+ seen.add(key)
99
+ calls.push({ args: c.args || [], kwargs: c.kwargs || {}, origin: 'test' })
100
+ }
101
+ }
102
+ return { calls, status: run ? run.status : null, output: run ? (run.stdout || '') + (run.stderr || '') : '' }
103
+ }
104
+
105
+ module.exports = { captureFromTests, pyInstrument, jsInstrument }
package/src/go.js ADDED
@@ -0,0 +1,165 @@
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.loadCases(L)
20
+ const fr = app.fallbackRate(L, cases)
21
+ const firstCase = cases.find((c) => fr.names.includes(c.name))
22
+ const route = firstCase && firstCase.request
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, ['cli'])
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.loadCases(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 cliInputs = path.join(L.appCases, 'cli.jsonl')
77
+ if (a.cli || fs.existsSync(cliInputs)) {
78
+ if (!fs.existsSync(cliInputs)) {
79
+ task(L, 'collect CLI invocations', `Write one JSON line per invocation to \`rails/port/app-cases/cli.jsonl\`: {"name", "args": [...], "stdin", "env"}. Cover every command and flag, --help, bad input and each error exit code. Then run \`ruby-anything go --cli -- ${command.join(' ') || '<command>'}\` again.`)
80
+ return 0
81
+ }
82
+ const code = await app.cmdAppRecord([L.root, '--cli', '--inputs', cliInputs, '--', ...command])
83
+ if (code !== 0) return code
84
+ if ((await app.cmdAppReplay([L.root, '--original'])) !== 0) {
85
+ task(L, 'stabilise the recording', 'The original does not replay its own recording 100%: add [..] wildcards for noise in rails/port/app-cases/cli/*.json, then `ruby-anything app replay --original`.')
86
+ return 1
87
+ }
88
+ } else {
89
+ const inputs = path.join(L.appCases, 'inputs.jsonl')
90
+ const args = [L.root, '--http', ...(fs.existsSync(inputs) ? ['--inputs', inputs] : []), ...(a.dbReset ? ['--db-reset', a.dbReset] : []), '--', ...command]
91
+ const code = await app.cmdAppRecord(args)
92
+ if (code !== 0) return code
93
+ const orig = await app.cmdAppReplay([L.root, '--original'])
94
+ if (orig !== 0) {
95
+ 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.')
96
+ return 1
97
+ }
98
+ }
99
+ }
100
+
101
+ // 3. front door
102
+ if (!fs.existsSync(path.join(L.rails, 'Gemfile')) || (!app.isLifted(L) && !fs.existsSync(path.join(L.rails, 'config', 'ruby_anything.yml')))) {
103
+ const code = await app.cmdAppFrontDoor([L.root])
104
+ if (code !== 0) return code
105
+ }
106
+
107
+ // 4. replay through Rails and pick the next route
108
+ if (app.isLifted(L)) {
109
+ console.log(green('lifted: the app runs on Rails alone. Run ruby-anything app gate --app in CI.'))
110
+ return 0
111
+ }
112
+ const rc = await app.cmdAppReplay([L.root])
113
+ const { fr, firstCase, route } = nextRoute(L)
114
+ if (rc !== 0) {
115
+ task(L, 'fix the replay', `
116
+ \`ruby-anything app replay ${repo}\` is red. Fix one case at a time:
117
+
118
+ ruby-anything app replay ${repo} --case <name from the report>
119
+
120
+ Read its difference, form one hypothesis, change the Rails code, rerun that case until green, then
121
+ the full replay. Never edit a recorded case without the user's yes (record why in DECISIONS.md).`)
122
+ return 1
123
+ }
124
+ if (fr.fallback === 0) {
125
+ const g = await app.cmdAppGate([L.root])
126
+ if (g !== 0) {
127
+ task(L, 'pass the app gate', `Every route is wired. Make \`ruby-anything gate ${repo} --app\` pass, then \`ruby-anything app lift ${repo}\`.`)
128
+ return 1
129
+ }
130
+ task(L, 'lift', `Fallback rate 0 and the gate passes. Ask the user, then run \`ruby-anything app lift ${repo}\`.`)
131
+ return 0
132
+ }
133
+ if (app.settings(L).kind === 'cli') {
134
+ const c = app.loadCases(L).find((x) => fr.names.includes(x.name))
135
+ const cmd = c.input.args[0] || '(no arguments)'
136
+ task(L, `port the ${cmd} command`, `
137
+ Fallback rate: ${fr.fallback}/${fr.total}. Next invocation still answered by the original: **${[app.settings(L).cli_name, ...c.input.args].join(' ')}**.
138
+
139
+ 1. Claim it in \`rails/port/MAP.md\`; run \`ruby-anything rules ${repo}\`.
140
+ 2. Port the functions it calls (bridge, record, diff, gate per unit).
141
+ 3. \`ruby-anything app wire ${repo} <unit> --command ${c.input.args[0] || '*'}\` creates \`rails/app/cli/<unit>.rb\`: write \`Cli::<Unit>.call(argv)\` (read $stdin, print to $stdout/$stderr, return the exit code; same files written).
142
+ 4. \`ruby-anything app replay ${repo}\`: 100% again, lower fallback rate.`)
143
+ return 0
144
+ }
145
+ const plan = readJSON(L.planJson, { units: [] })
146
+ const unitsInFile = route ? plan.units.filter((u) => u.file === route.file) : []
147
+ task(L, `port ${route ? route.id : `${firstCase.request.method} ${firstCase.request.path}`}`, `
148
+ Fallback rate: ${fr.fallback}/${fr.total}. Next route still answered by the original:
149
+ **${firstCase.request.method} ${firstCase.request.path}**${route ? ` (defined at \`${route.file}:${route.line}\`)` : ''}.
150
+
151
+ 1. Claim it in \`rails/port/MAP.md\`. Run \`ruby-anything rules ${repo}\` and follow every rule.
152
+ 2. Port the logic it needs first, unit by unit (wave 1-2 before 3):
153
+ ${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)'}
154
+ 3. Write the Rails side: model (ActiveRecord on the same table), route in \`config/routes.rb\`,
155
+ controller action, and for HTML an ERB view with Turbo + Stimulus + Tailwind + daisyUI
156
+ (read the skill's frontend.md). Same URL, status codes, redirects and JSON shape.
157
+ 4. \`ruby-anything app wire ${repo} <unit-name> --route "${route ? `${route.method === 'ANY' ? 'GET' : route.method} ${route.path}` : `${firstCase.request.method} ${firstCase.request.path}`}"\`
158
+ 5. \`ruby-anything app replay ${repo}\`: 100% again, lower fallback rate. Add a Minitest test for the action.
159
+ 6. Mark it done in MAP.md; at a checkpoint from DECISIONS.md, report to the user and wait.`)
160
+ void st
161
+ void yellow
162
+ return 0
163
+ }
164
+
165
+ 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 }