ruby-anything 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +12 -0
- package/.claude-plugin/plugin.json +7 -0
- package/.mcp.json +8 -0
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/action.yml +56 -0
- package/adapters/node/harness.mjs +348 -0
- package/adapters/node/package-lock.json +26 -0
- package/adapters/node/package.json +7 -0
- package/adapters/polyglot/harness.py +350 -0
- package/adapters/polyglot/lang_csharp.py +222 -0
- package/adapters/polyglot/lang_go.py +283 -0
- package/adapters/polyglot/lang_java.py +510 -0
- package/adapters/polyglot/lang_kotlin.py +133 -0
- package/adapters/polyglot/lang_php.py +156 -0
- package/adapters/polyglot/lang_ruby.py +148 -0
- package/adapters/polyglot/lang_rust.py +430 -0
- package/adapters/polyglot/lang_swift.py +337 -0
- package/adapters/python/harness.py +459 -0
- package/bin/ruby-anything.js +10 -0
- package/docs/assets/how-it-works-dark.svg +51 -0
- package/docs/assets/how-it-works-light.svg +51 -0
- package/harness/ruby_replay.rb +155 -0
- package/package.json +52 -4
- package/skills/ruby-anything/SKILL.md +146 -0
- package/skills/ruby-anything/frontend.md +64 -0
- package/skills/ruby-anything/languages/csharp.md +43 -0
- package/skills/ruby-anything/languages/go.md +36 -0
- package/skills/ruby-anything/languages/java.md +54 -0
- package/skills/ruby-anything/languages/javascript.md +50 -0
- package/skills/ruby-anything/languages/kotlin.md +27 -0
- package/skills/ruby-anything/languages/php.md +47 -0
- package/skills/ruby-anything/languages/python.md +49 -0
- package/skills/ruby-anything/languages/rust.md +31 -0
- package/skills/ruby-anything/languages/swift.md +27 -0
- package/skills/ruby-anything/whole-app.md +204 -0
- package/src/adapters.js +63 -0
- package/src/analyze.js +183 -0
- package/src/app.js +774 -0
- package/src/cli.js +80 -0
- package/src/cli_app.js +251 -0
- package/src/detect.js +266 -0
- package/src/drift.js +124 -0
- package/src/effects.js +145 -0
- package/src/fromtests.js +105 -0
- package/src/go.js +165 -0
- package/src/mcp.js +89 -0
- package/src/setup.js +106 -0
- package/src/units.js +452 -0
- package/src/util.js +312 -0
package/src/setup.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
// setup: copy the skill into each agent's skills folder and register the MCP server.
|
|
3
|
+
// setup --remove undoes both. doctor: check every runtime and print the fix.
|
|
4
|
+
const fs = require('node:fs')
|
|
5
|
+
const os = require('node:os')
|
|
6
|
+
const path = require('node:path')
|
|
7
|
+
const { PKG, IS_WIN, parseArgs, readJSON, writeJSON, runSync, which, python, green, red, yellow, bold, dim } = require('./util')
|
|
8
|
+
|
|
9
|
+
const HOME = os.homedir()
|
|
10
|
+
const SKILL_SRC = path.join(PKG, 'skills', 'ruby-anything')
|
|
11
|
+
const SKILL_DIRS = [
|
|
12
|
+
['Claude Code', path.join(HOME, '.claude', 'skills', 'ruby-anything'), path.join(HOME, '.claude')],
|
|
13
|
+
['Codex', path.join(HOME, '.codex', 'skills', 'ruby-anything'), path.join(HOME, '.codex')],
|
|
14
|
+
['OpenCode', path.join(HOME, '.config', 'opencode', 'skills', 'ruby-anything'), path.join(HOME, '.config', 'opencode')],
|
|
15
|
+
]
|
|
16
|
+
const MCP_ENTRY = { command: 'ruby-anything', args: ['mcp'] }
|
|
17
|
+
|
|
18
|
+
function setupSkills(remove) {
|
|
19
|
+
for (const [agent, dir, home] of SKILL_DIRS) {
|
|
20
|
+
if (!fs.existsSync(home)) continue
|
|
21
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
22
|
+
if (!remove) fs.cpSync(SKILL_SRC, dir, { recursive: true })
|
|
23
|
+
console.log(`${remove ? 'removed' : 'installed'} skill for ${agent}: ${dir}`)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function setupMcp(remove) {
|
|
28
|
+
// Claude Code and Codex through their own CLIs; Cursor and Gemini through their JSON configs.
|
|
29
|
+
if (which('claude')) {
|
|
30
|
+
runSync('claude', ['mcp', 'remove', '--scope', 'user', 'ruby-anything'])
|
|
31
|
+
if (!remove) {
|
|
32
|
+
const r = runSync('claude', ['mcp', 'add', '--scope', 'user', 'ruby-anything', '--', 'ruby-anything', 'mcp'])
|
|
33
|
+
console.log(r.code === 0 ? 'registered MCP server with Claude Code' : yellow(`Claude Code: ${r.stderr.trim() || r.stdout.trim()}`))
|
|
34
|
+
} else console.log('removed MCP server from Claude Code')
|
|
35
|
+
} else if (!remove) console.log(dim('Claude Code CLI not found: add the server with claude mcp add --scope user ruby-anything -- ruby-anything mcp'))
|
|
36
|
+
if (which('codex')) {
|
|
37
|
+
runSync('codex', ['mcp', 'remove', 'ruby-anything'])
|
|
38
|
+
if (!remove) {
|
|
39
|
+
const r = runSync('codex', ['mcp', 'add', 'ruby-anything', '--', 'ruby-anything', 'mcp'])
|
|
40
|
+
console.log(r.code === 0 ? 'registered MCP server with Codex' : yellow(`Codex: ${r.stderr.trim()}`))
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
for (const [agent, file] of [['Cursor', path.join(HOME, '.cursor', 'mcp.json')], ['Gemini CLI', path.join(HOME, '.gemini', 'settings.json')]]) {
|
|
44
|
+
if (!fs.existsSync(path.dirname(file))) continue
|
|
45
|
+
const cfg = readJSON(file, {})
|
|
46
|
+
cfg.mcpServers = cfg.mcpServers || {}
|
|
47
|
+
if (remove) delete cfg.mcpServers['ruby-anything']
|
|
48
|
+
else cfg.mcpServers['ruby-anything'] = MCP_ENTRY
|
|
49
|
+
writeJSON(file, cfg)
|
|
50
|
+
console.log(`${remove ? 'removed MCP server from' : 'registered MCP server with'} ${agent}: ${file}`)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function cmdSetup(argv) {
|
|
55
|
+
const a = parseArgs(argv, ['remove'])
|
|
56
|
+
setupSkills(a.remove)
|
|
57
|
+
setupMcp(a.remove)
|
|
58
|
+
if (!a.remove) {
|
|
59
|
+
console.log(`\n${bold('Ready.')} Restart your agent, then ask it:`)
|
|
60
|
+
console.log(' "Run ruby-anything go -- <command that starts this app> and finish the port until ruby-anything gate --app passes."')
|
|
61
|
+
console.log(dim('Run ruby-anything doctor to check the runtimes the original app needs.'))
|
|
62
|
+
}
|
|
63
|
+
return 0
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const CHECKS = [
|
|
67
|
+
['node', ['node', '--version'], 'always (runs ruby-anything)', null],
|
|
68
|
+
['ruby', ['ruby', '--version'], 'always (the target)', 'https://www.ruby-lang.org/en/documentation/installation/ (Ruby 3.2+)'],
|
|
69
|
+
['bundler', ['bundle', '--version'], 'always', 'gem install bundler'],
|
|
70
|
+
['rails', ['rails', '--version'], 'front door (rails new)', 'gem install rails'],
|
|
71
|
+
['python3', null, 'recording Python, and driving Go/Java/Kotlin/C#/PHP/Rust/Swift recorders', 'https://www.python.org/downloads/'],
|
|
72
|
+
['go', ['go', 'version'], 'recording Go', 'https://go.dev/dl/'],
|
|
73
|
+
['javac', ['javac', '-version'], 'recording Java / Spring Boot', 'a JDK 17+ (e.g. Temurin)'],
|
|
74
|
+
['kotlinc', ['kotlinc', '-version'], 'recording Kotlin', 'https://kotlinlang.org/docs/command-line.html'],
|
|
75
|
+
['dotnet', ['dotnet', '--version'], 'recording C#', 'https://dotnet.microsoft.com/download'],
|
|
76
|
+
['php', ['php', '--version'], 'recording PHP', 'https://www.php.net/downloads'],
|
|
77
|
+
['rustc', ['rustc', '--version'], 'recording Rust', 'https://rustup.rs'],
|
|
78
|
+
['swiftc', ['swiftc', '--version'], 'recording Swift', 'https://www.swift.org/install/'],
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
function cmdDoctor(argv) {
|
|
82
|
+
const a = parseArgs(argv, ['json'])
|
|
83
|
+
const rows = []
|
|
84
|
+
for (const [name, cmd, need, fix] of CHECKS) {
|
|
85
|
+
let version = null
|
|
86
|
+
if (name === 'python3') {
|
|
87
|
+
const py = python()
|
|
88
|
+
if (py) version = runSync(py, ['--version']).stdout.trim() || runSync(py, ['--version']).stderr.trim()
|
|
89
|
+
} else if (which(cmd[0])) {
|
|
90
|
+
const r = runSync(cmd[0], cmd.slice(1))
|
|
91
|
+
version = (r.stdout || r.stderr).trim().split('\n')[0] || 'installed'
|
|
92
|
+
}
|
|
93
|
+
rows.push({ name, ok: !!version, version, need, fix })
|
|
94
|
+
}
|
|
95
|
+
const skills = SKILL_DIRS.filter(([, dir]) => fs.existsSync(path.join(dir, 'SKILL.md'))).map(([agent]) => agent)
|
|
96
|
+
if (a.json) {
|
|
97
|
+
process.stdout.write(JSON.stringify({ runtimes: rows, skills }, null, 2) + '\n')
|
|
98
|
+
return 0
|
|
99
|
+
}
|
|
100
|
+
for (const r of rows) console.log(`${r.ok ? green('ok ') : r.need.startsWith('always') ? red('miss') : yellow('miss')} ${r.name.padEnd(8)} ${r.ok ? dim(r.version) : `${r.need}: ${r.fix}`}`)
|
|
101
|
+
console.log(skills.length ? `${green('ok ')} skill installed for ${skills.join(', ')}` : `${yellow('miss')} skill run ruby-anything setup`)
|
|
102
|
+
if (IS_WIN) console.log(dim('Windows: Rails runs natively; for production parity consider WSL.'))
|
|
103
|
+
return rows.filter((r) => r.need.startsWith('always')).every((r) => r.ok) ? 0 : 1
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = { cmdSetup, cmdDoctor }
|
package/src/units.js
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
// One unit at a time: bridge (Ruby skeleton), record (original's behavior), diff (port vs recording),
|
|
3
|
+
// gate (done means gate passes), rules (behavior the user corrected).
|
|
4
|
+
const fs = require('node:fs')
|
|
5
|
+
const path = require('node:path')
|
|
6
|
+
const adapters = require('./adapters')
|
|
7
|
+
const {
|
|
8
|
+
PKG, layout, loadState, saveState, readJSON, writeFile, readLines, sha256, slug, snake, camel, parseArgs,
|
|
9
|
+
runHarness, runSync, which, canon, readCases, plain, green, red, yellow, bold, dim, relTo,
|
|
10
|
+
} = require('./util')
|
|
11
|
+
|
|
12
|
+
// ------------------------------------------------------------------ plan lookup
|
|
13
|
+
function loadPlan(L) {
|
|
14
|
+
const p = readJSON(L.planJson)
|
|
15
|
+
if (!p) throw new Error(`no plan: run ruby-anything analyze ${L.root} first`)
|
|
16
|
+
return p
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function findUnit(L, id) {
|
|
20
|
+
const p = loadPlan(L)
|
|
21
|
+
let u = p.units.find((x) => x.id === id)
|
|
22
|
+
if (!u) {
|
|
23
|
+
const hits = p.units.filter((x) => x.id.endsWith(':' + id) || x.name === id || x.qualified_name === id)
|
|
24
|
+
if (hits.length === 1) u = hits[0]
|
|
25
|
+
else if (hits.length > 1) throw new Error(`"${id}" is ambiguous: ${hits.map((h) => h.id).join(', ')}`)
|
|
26
|
+
}
|
|
27
|
+
if (!u) throw new Error(`unit "${id}" not in the plan; see rails/port/plan.json`)
|
|
28
|
+
return u
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Where a unit's Ruby port lives and how it is called.
|
|
32
|
+
function portTarget(L, u) {
|
|
33
|
+
const base = path.basename(u.file).replace(/\.[^.]+$/, '').replace(/\.(blade)$/, '')
|
|
34
|
+
const mod = camel(u.owner || base) || 'Ported'
|
|
35
|
+
return {
|
|
36
|
+
file: path.join(L.rails, 'app', 'services', `${snake(mod)}.rb`),
|
|
37
|
+
receiver: mod,
|
|
38
|
+
method: snake(u.name),
|
|
39
|
+
instance: !!u.instance,
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function casesFile(L, u) {
|
|
44
|
+
return path.join(L.cases, `${slug(u.id)}.jsonl`)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ------------------------------------------------------------------ bridge
|
|
48
|
+
function rubyParams(u) {
|
|
49
|
+
return (u.params || [])
|
|
50
|
+
.filter((p) => !['self', 'cls'].includes(p.name))
|
|
51
|
+
.map((p) => {
|
|
52
|
+
const d = rubyDefault(p.default)
|
|
53
|
+
return d === undefined ? snake(p.name) : `${snake(p.name)} = ${d}`
|
|
54
|
+
})
|
|
55
|
+
.join(', ')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Simple literal defaults carry over; anything else is left for the agent.
|
|
59
|
+
function rubyDefault(src) {
|
|
60
|
+
if (src === null || src === undefined || src === '') return undefined
|
|
61
|
+
const t = String(src).trim()
|
|
62
|
+
if (/^-?\d+(\.\d+)?$/.test(t)) return t
|
|
63
|
+
if (/^(None|null|nil|undefined)$/.test(t)) return 'nil'
|
|
64
|
+
if (/^(True|true)$/.test(t)) return 'true'
|
|
65
|
+
if (/^(False|false)$/.test(t)) return 'false'
|
|
66
|
+
const q = t.match(/^(['"])(.*)\1$/s)
|
|
67
|
+
if (q) return JSON.stringify(q[2])
|
|
68
|
+
if (/^\[\s*\]$/.test(t)) return '[]'
|
|
69
|
+
if (/^\{\s*\}$/.test(t)) return '{}'
|
|
70
|
+
return undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function cmdBridge(argv) {
|
|
74
|
+
const a = parseArgs(argv)
|
|
75
|
+
const L = layout(a._[0])
|
|
76
|
+
const u = findUnit(L, a._[1])
|
|
77
|
+
const t = portTarget(L, u)
|
|
78
|
+
const endState = a.endState || 'replace'
|
|
79
|
+
if (!['replace', 'scaffold', 'keep'].includes(endState)) throw new Error('--end-state is replace, scaffold or keep')
|
|
80
|
+
const params = rubyParams(u)
|
|
81
|
+
const sig = `${t.instance ? '' : 'self.'}${t.method}${params ? `(${params})` : ''}`
|
|
82
|
+
const stub = [
|
|
83
|
+
` # Port of ${u.id} (${u.lang}, lines ${u.line_start}-${u.line_end}).`,
|
|
84
|
+
` # Keep the original's behavior, bugs included; raise where it raises.`,
|
|
85
|
+
` def ${sig}`,
|
|
86
|
+
` raise NotImplementedError, "port ${u.id}"`,
|
|
87
|
+
' end',
|
|
88
|
+
].join('\n')
|
|
89
|
+
let text
|
|
90
|
+
let created = false
|
|
91
|
+
if (fs.existsSync(t.file)) {
|
|
92
|
+
text = fs.readFileSync(t.file, 'utf8')
|
|
93
|
+
if (new RegExp(`def\\s+${t.instance ? '' : 'self\\.'}${t.method}\\b`).test(text)) {
|
|
94
|
+
console.log(`${relTo(L.root, t.file)} already defines ${t.method}; not changed`)
|
|
95
|
+
} else {
|
|
96
|
+
const i = text.lastIndexOf('\nend')
|
|
97
|
+
text = text.slice(0, i) + '\n\n' + stub + text.slice(i)
|
|
98
|
+
writeFile(t.file, text)
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
created = true
|
|
102
|
+
text = `# frozen_string_literal: true\n\n# Ported from ${u.file} by ruby-anything.\n${t.instance ? 'class' : 'module'} ${t.receiver}\n${stub}\nend\n`
|
|
103
|
+
writeFile(t.file, text)
|
|
104
|
+
}
|
|
105
|
+
const s = loadState(L)
|
|
106
|
+
s.units[u.id] = { ...(s.units[u.id] || {}), port_file: relTo(L.root, t.file), receiver: t.receiver, method: t.method, instance: t.instance, end_state: endState, status: s.units[u.id]?.status || 'bridged' }
|
|
107
|
+
saveState(L, s)
|
|
108
|
+
writeTask(L, u, t)
|
|
109
|
+
console.log(`${created ? 'created' : 'updated'} ${relTo(L.root, t.file)}: ${t.receiver}${t.instance ? '#' : '.'}${t.method}`)
|
|
110
|
+
console.log(`task: ${relTo(L.root, L.task)}\nnext: ruby-anything record ${a._[0] || '.'} ${u.id}`)
|
|
111
|
+
return 0
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function writeTask(L, u, t) {
|
|
115
|
+
const repo = path.relative(process.cwd(), L.root) || '.'
|
|
116
|
+
writeFile(
|
|
117
|
+
L.task,
|
|
118
|
+
`# Task: port ${u.id}
|
|
119
|
+
|
|
120
|
+
Source: \`${u.file}\` lines ${u.line_start}-${u.line_end} (${u.lang}).
|
|
121
|
+
Ruby port: \`${relTo(L.root, t.file)}\`, \`${t.receiver}${t.instance ? '#' : '.'}${t.method}\`.
|
|
122
|
+
|
|
123
|
+
1. Read \`rails/port/RULES.md\` (\`ruby-anything rules ${repo}\`) and the language notes in the skill
|
|
124
|
+
(\`languages/${u.lang === 'typescript' ? 'javascript' : u.lang}.md\`).
|
|
125
|
+
2. Record the original if not done yet: \`ruby-anything record ${repo} "${u.id}"\`.
|
|
126
|
+
3. Write the port. Keep behavior, bugs included. Raise where the original raises, with the mapped
|
|
127
|
+
Ruby error class. Compute every result; never copy recorded answers into the code.
|
|
128
|
+
4. \`ruby-anything diff ${repo} "${u.id}"\` until it reports N/N.
|
|
129
|
+
5. \`ruby-anything gate ${repo} "${u.id}"\` must pass. Then report to the user and wait.
|
|
130
|
+
${u.risks && u.risks.length ? `\nRisks: ${u.risks.join('; ')}\n` : ''}`,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ------------------------------------------------------------------ record
|
|
135
|
+
async function cmdRecord(argv) {
|
|
136
|
+
const a = parseArgs(argv, ['fromTests', 'pinClock', 'noGenerate'])
|
|
137
|
+
const L = layout(a._[0])
|
|
138
|
+
const u = findUnit(L, a._[1])
|
|
139
|
+
if (!u.recordable) throw new Error(`${u.id} is a ${u.kind} and cannot be recorded alone; check it through app record/replay`)
|
|
140
|
+
const extra = a.inputs ? readLines(path.resolve(a.inputs)).filter((c) => !c.fn || c.fn === u.name).map((c) => ({ args: c.args || [], kwargs: c.kwargs || {}, origin: 'input' })) : []
|
|
141
|
+
if (a.fromTests) {
|
|
142
|
+
const t = require('./fromtests').captureFromTests(L.root, u, a.rest, { log: (m) => console.error(dim(m)) })
|
|
143
|
+
console.error(dim(`the test suite made ${t.calls.length} distinct calls to ${u.name}${t.status ? ` (tests exited with ${t.status})` : ''}`))
|
|
144
|
+
if (!t.calls.length && t.status) console.error(t.output.trim().split('\n').slice(-15).join('\n'))
|
|
145
|
+
extra.push(...t.calls)
|
|
146
|
+
}
|
|
147
|
+
console.error(dim(`recording ${u.id} (runs the original code)`))
|
|
148
|
+
const r = await adapters.record(L.root, u.lang, {
|
|
149
|
+
moduleFile: u.file,
|
|
150
|
+
fn: u.name,
|
|
151
|
+
cases: extra,
|
|
152
|
+
count: a.noGenerate ? 0 : a.count === undefined ? 40 : Number(a.count),
|
|
153
|
+
pinClock: !!a.pinClock,
|
|
154
|
+
seed: Number(a.seed || 1),
|
|
155
|
+
mode: a.fuzz ? 'fuzz' : 'edge',
|
|
156
|
+
})
|
|
157
|
+
const file = casesFile(L, u)
|
|
158
|
+
const text = r.cases.map((c, i) => `{"ref":"c${i + 1}","origin":${JSON.stringify(c.origin || 'generated')},"args":${canon(c.args)},"kwargs":${canon(c.kwargs || {})},"stable":${!!c.stable},"outcome":${canon(c.outcome)},"stdout":${JSON.stringify(c.stdout || '')},"stderr":${JSON.stringify(c.stderr || '')}}`).join('\n') + '\n'
|
|
159
|
+
writeFile(file, text)
|
|
160
|
+
const s = loadState(L)
|
|
161
|
+
s.units[u.id] = { ...(s.units[u.id] || {}), cases_file: relTo(L.root, file), cases_sha: sha256(text), recorded_at: new Date().toISOString(), runtime: r.runtime, pin_clock: !!a.pinClock, source_sha: sha256(fs.readFileSync(path.join(L.root, u.file))) }
|
|
162
|
+
saveState(L, s)
|
|
163
|
+
const raises = r.cases.filter((c) => c.outcome.kind === 'raise').length
|
|
164
|
+
const unstable = r.cases.filter((c) => c.stable === false).length
|
|
165
|
+
console.log(`${r.cases.length} cases (${raises} raise) from ${r.runtime} -> ${relTo(L.root, file)}`)
|
|
166
|
+
if (unstable) console.log(yellow(`${unstable} cases differ between two runs of the original (clock, random, order): pin them or ask the user`))
|
|
167
|
+
const covered = new Set(r.cases.map((c) => plain(c.outcome).raise_line).filter(Boolean))
|
|
168
|
+
const missing = (u.raise_lines || []).filter((l) => !covered.has(l))
|
|
169
|
+
if (missing.length) console.log(yellow(`raise at line ${missing.join(', ')} not reached: add inputs with --inputs`))
|
|
170
|
+
return 0
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ------------------------------------------------------------------ compare
|
|
174
|
+
const ERROR_EQUIV = [
|
|
175
|
+
['ValueError', 'ArgumentError', 'IllegalArgumentException', 'ArgumentException', 'InvalidArgumentException', 'RangeError', 'NumberFormatException', 'FormatException', 'DomainError'],
|
|
176
|
+
['TypeError', 'TypeError', 'ClassCastException', 'InvalidCastException'],
|
|
177
|
+
['KeyError', 'KeyError', 'NoSuchElementException', 'KeyNotFoundException'],
|
|
178
|
+
['IndexError', 'IndexError', 'IndexOutOfBoundsException', 'ArrayIndexOutOfBoundsException', 'StringIndexOutOfBoundsException', 'IndexOutOfRangeException', 'OutOfRangeException'],
|
|
179
|
+
['ZeroDivisionError', 'ZeroDivisionError', 'ArithmeticException', 'DivideByZeroException', 'DivisionByZeroError'],
|
|
180
|
+
['NotImplementedError', 'NotImplementedError', 'UnsupportedOperationException', 'NotImplementedException', 'NotSupportedException'],
|
|
181
|
+
['RuntimeError', 'RuntimeError', 'Error', 'Exception', 'RuntimeException', 'IllegalStateException', 'InvalidOperationException', 'StandardError'],
|
|
182
|
+
['NullPointerException', 'NoMethodError', 'NullReferenceException', 'AttributeError'],
|
|
183
|
+
]
|
|
184
|
+
const simpleName = (t) => String(t || '').split(/::|\./).pop()
|
|
185
|
+
function sameError(a, b) {
|
|
186
|
+
const x = simpleName(a)
|
|
187
|
+
const y = simpleName(b)
|
|
188
|
+
if (x === y) return true
|
|
189
|
+
return ERROR_EQUIV.some((g) => g.includes(x) && g.includes(y))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function compareCase(rec, got, opts = {}) {
|
|
193
|
+
const ro = plain(rec.outcome)
|
|
194
|
+
const go = got.outcome
|
|
195
|
+
if (ro.kind !== go.kind) return { ok: false, at: 'outcome', detail: `original ${ro.kind === 'raise' ? `raised ${ro.type}` : 'returned'}, port ${go.kind === 'raise' ? `raised ${go.type}: ${go.message}` : 'returned'}` }
|
|
196
|
+
if (ro.kind === 'raise') {
|
|
197
|
+
if (!sameError(ro.type, go.type)) return { ok: false, at: 'error type', detail: `${ro.type} vs ${go.type}` }
|
|
198
|
+
if (opts.messages && ro.message !== go.message) return { ok: false, at: 'error message', detail: `${JSON.stringify(ro.message)} vs ${JSON.stringify(go.message)}` }
|
|
199
|
+
} else {
|
|
200
|
+
const a = canon(rec.outcome.value)
|
|
201
|
+
const b = canon(got.outcome.value)
|
|
202
|
+
if (a !== b) return { ok: false, at: firstDiff(rec.outcome.value, got.outcome.value), detail: `${a.slice(0, 160)} vs ${b.slice(0, 160)}` }
|
|
203
|
+
}
|
|
204
|
+
const norm = (s) => String(s || '').replace(/\r\n/g, '\n')
|
|
205
|
+
if (norm(rec.stdout) !== norm(got.stdout)) return { ok: false, at: 'stdout', detail: `${JSON.stringify(rec.stdout).slice(0, 120)} vs ${JSON.stringify(got.stdout).slice(0, 120)}` }
|
|
206
|
+
return { ok: true }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function firstDiff(a, b, p = '$') {
|
|
210
|
+
if (canon(a) === canon(b)) return null
|
|
211
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
212
|
+
if (a.length !== b.length) return `${p} length`
|
|
213
|
+
for (let i = 0; i < a.length; i++) if (canon(a[i]) !== canon(b[i])) return firstDiff(a[i], b[i], `${p}[${i}]`)
|
|
214
|
+
}
|
|
215
|
+
if (a && b && typeof a === 'object' && typeof b === 'object' && !('$n' in a) && !('$n' in b)) {
|
|
216
|
+
for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) if (canon(a[k]) !== canon(b[k])) return firstDiff(a[k], b[k], `${p}.${k}`)
|
|
217
|
+
}
|
|
218
|
+
const kind = (v) => (v && typeof v === 'object' && '$n' in v ? (/[.eE]/.test(v.$n) ? 'float' : 'int') : Array.isArray(v) ? 'array' : v === null ? 'null' : typeof v)
|
|
219
|
+
return kind(a) !== kind(b) ? `${p} (${kind(a)} vs ${kind(b)})` : p
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ------------------------------------------------------------------ diff
|
|
223
|
+
async function replay(L, u, entry, cases, command = 'replay') {
|
|
224
|
+
if (!which('ruby')) throw new Error('ruby is not installed; run ruby-anything doctor')
|
|
225
|
+
const req = {
|
|
226
|
+
command,
|
|
227
|
+
code_file: path.join(L.root, entry.port_file),
|
|
228
|
+
receiver: entry.receiver,
|
|
229
|
+
method: entry.method,
|
|
230
|
+
instance: !!entry.instance,
|
|
231
|
+
pin_clock: !!entry.pin_clock,
|
|
232
|
+
cases: cases.map((c) => ({ ref: c.ref, args: c.args, kwargs: c.kwargs })),
|
|
233
|
+
iterations: 30,
|
|
234
|
+
}
|
|
235
|
+
if (entry.boot_rails) req.rails_root = L.rails
|
|
236
|
+
const casesRaw = '[' + cases.map((c) => `{"ref":${JSON.stringify(c.ref)},"args":${canon(c.args || [])},"kwargs":${canon(c.kwargs || {})}}`).join(',') + ']'
|
|
237
|
+
const raw = JSON.stringify({ ...req, cases: '__CASES__' }).replace('"__CASES__"', casesRaw)
|
|
238
|
+
const cwd = fs.existsSync(L.rails) ? L.rails : L.root
|
|
239
|
+
const { events } = await runHarness(['ruby', path.join(PKG, 'harness', 'ruby_replay.rb')], raw, { cwd })
|
|
240
|
+
return events.filter((e) => e.event === 'case')
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function diffUnit(L, u, opts = {}) {
|
|
244
|
+
const s = loadState(L)
|
|
245
|
+
const entry = s.units[u.id]
|
|
246
|
+
if (!entry || !entry.port_file) throw new Error(`${u.id} has no port yet: ruby-anything bridge ${L.root} "${u.id}"`)
|
|
247
|
+
const cases = readCases(casesFile(L, u))
|
|
248
|
+
if (!cases.length) throw new Error(`no recorded cases: ruby-anything record ${L.root} "${u.id}"`)
|
|
249
|
+
const known = readLines(path.join(L.port, 'known-diffs.jsonl')).filter((k) => k.unit === u.id)
|
|
250
|
+
const got = await replay(L, u, entry, cases)
|
|
251
|
+
const byRef = Object.fromEntries(got.map((g) => [g.ref, g]))
|
|
252
|
+
const results = cases.map((c) => {
|
|
253
|
+
const g = byRef[c.ref]
|
|
254
|
+
if (!g) return { ref: c.ref, ok: false, at: 'missing', detail: 'no result' }
|
|
255
|
+
const kd = known.find((k) => canon(k.args) === canon(c.args))
|
|
256
|
+
if (kd) return { ref: c.ref, ok: canon(kd.actual) === canon(plain(g.outcome)), at: 'known diff', detail: kd.reason, known: true }
|
|
257
|
+
return { ref: c.ref, args: c.args, ...compareCase(c, g, opts) }
|
|
258
|
+
})
|
|
259
|
+
const matched = results.filter((r) => r.ok).length
|
|
260
|
+
// trend: three port changes in a row with no new matching case means stalled
|
|
261
|
+
const portSha = sha256(fs.readFileSync(path.join(L.root, entry.port_file)))
|
|
262
|
+
const hist = entry.trend || []
|
|
263
|
+
if (!hist.length || hist[hist.length - 1].sha !== portSha) hist.push({ sha: portSha, matched })
|
|
264
|
+
else hist[hist.length - 1].matched = matched
|
|
265
|
+
entry.trend = hist.slice(-10)
|
|
266
|
+
const last = entry.trend.slice(-4)
|
|
267
|
+
const stalled = matched < cases.length && last.length === 4 && last.slice(1).every((h) => h.matched <= last[0].matched)
|
|
268
|
+
entry.last_diff = { matched, total: cases.length, at: new Date().toISOString() }
|
|
269
|
+
s.units[u.id] = entry
|
|
270
|
+
saveState(L, s)
|
|
271
|
+
const groups = {}
|
|
272
|
+
for (const r of results.filter((x) => !x.ok)) (groups[r.at] = groups[r.at] || []).push(r)
|
|
273
|
+
return { matched, total: cases.length, results, groups, stalled }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Ruby harness emits plain JSON numbers; wrap them like parseJSON does so int/float kinds compare.
|
|
277
|
+
function rawOutcome(o) {
|
|
278
|
+
const wrap = (v) => {
|
|
279
|
+
if (typeof v === 'number') return { $n: Number.isInteger(v) && !Object.is(v, -0) ? String(v) : String(v).includes('.') || String(v).includes('e') ? String(v) : v.toFixed(1) }
|
|
280
|
+
if (Array.isArray(v)) return v.map(wrap)
|
|
281
|
+
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, wrap(x)]))
|
|
282
|
+
return v
|
|
283
|
+
}
|
|
284
|
+
return o.kind === 'return' ? { ...o, value: wrap(o.value) } : o
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async function cmdDiff(argv) {
|
|
288
|
+
const a = parseArgs(argv, ['json', 'messages', 'redact'])
|
|
289
|
+
const L = layout(a._[0])
|
|
290
|
+
const u = findUnit(L, a._[1])
|
|
291
|
+
const d = await diffUnit(L, u, { messages: a.messages })
|
|
292
|
+
if (a.json) {
|
|
293
|
+
process.stdout.write(JSON.stringify({ unit: u.id, matched: d.matched, total: d.total, stalled: d.stalled, mismatches: d.results.filter((r) => !r.ok).map((r) => (a.redact ? { ref: r.ref, at: r.at } : r)) }, null, 2) + '\n')
|
|
294
|
+
return d.matched === d.total ? 0 : 1
|
|
295
|
+
}
|
|
296
|
+
const tag = d.matched === d.total ? green : red
|
|
297
|
+
console.log(tag(`${d.matched}/${d.total} cases match`) + ` for ${u.id}`)
|
|
298
|
+
const sorted = Object.entries(d.groups).sort((x, y) => y[1].length - x[1].length)
|
|
299
|
+
for (const [at, rs] of sorted) {
|
|
300
|
+
console.log(` ${rs.length} differ at ${bold(at)}, e.g. ${rs[0].ref} args=${a.redact ? '<redacted>' : JSON.stringify(plain(rs[0].args || [])).slice(0, 100)}: ${a.redact ? '' : rs[0].detail}`)
|
|
301
|
+
}
|
|
302
|
+
if (d.stalled) console.log(yellow('stalled: three changes to the port gained no matching case. Stop and show the user the remaining mismatches.'))
|
|
303
|
+
return d.matched === d.total ? 0 : 1
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ------------------------------------------------------------------ rules
|
|
307
|
+
function cmdRules(argv) {
|
|
308
|
+
const a = parseArgs(argv)
|
|
309
|
+
const L = layout(a._[0])
|
|
310
|
+
let text = fs.existsSync(L.rules) ? fs.readFileSync(L.rules, 'utf8') : '# Port rules\n\nBehavior the user corrected. Every unit keeps every rule.\n\n'
|
|
311
|
+
if (a.add) {
|
|
312
|
+
text += `- ${String(a.add).trim()} (${new Date().toISOString().slice(0, 10)})\n`
|
|
313
|
+
writeFile(L.rules, text)
|
|
314
|
+
console.log(`added to ${relTo(L.root, L.rules)}`)
|
|
315
|
+
return 0
|
|
316
|
+
}
|
|
317
|
+
const rules = text.split('\n').filter((l) => l.startsWith('- '))
|
|
318
|
+
console.log(rules.length ? rules.join('\n') : 'no rules yet')
|
|
319
|
+
return 0
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ------------------------------------------------------------------ gate
|
|
323
|
+
function countTests(L) {
|
|
324
|
+
let n = 0
|
|
325
|
+
const walk = (d) => {
|
|
326
|
+
if (!fs.existsSync(d)) return
|
|
327
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
328
|
+
const p = path.join(d, e.name)
|
|
329
|
+
if (e.isDirectory()) walk(p)
|
|
330
|
+
else if (/_test\.rb$|_spec\.rb$/.test(e.name)) {
|
|
331
|
+
const t = fs.readFileSync(p, 'utf8')
|
|
332
|
+
n += (t.match(/^\s*(def test_|test\s+["']|it\s+["'])/gm) || []).length
|
|
333
|
+
n += (t.match(/\bassert(_\w+)?\b|\bexpect\(/g) || []).length
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
walk(path.join(L.rails, 'test'))
|
|
338
|
+
walk(path.join(L.rails, 'spec'))
|
|
339
|
+
return n
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function gateUnit(L, u, opts = {}) {
|
|
343
|
+
const checks = []
|
|
344
|
+
const add = (name, ok, fix) => checks.push({ name, ok, fix: ok ? undefined : fix })
|
|
345
|
+
const s = loadState(L)
|
|
346
|
+
const entry = s.units[u.id] || {}
|
|
347
|
+
const repo = path.relative(process.cwd(), L.root) || '.'
|
|
348
|
+
if (!entry.port_file) {
|
|
349
|
+
add('bridged', false, `ruby-anything bridge ${repo} "${u.id}"`)
|
|
350
|
+
return { ok: false, checks }
|
|
351
|
+
}
|
|
352
|
+
const portPath = path.join(L.root, entry.port_file)
|
|
353
|
+
const port = fs.readFileSync(portPath, 'utf8')
|
|
354
|
+
const cf = casesFile(L, u)
|
|
355
|
+
const casesText = fs.existsSync(cf) ? fs.readFileSync(cf, 'utf8') : ''
|
|
356
|
+
add('recorded', !!casesText, `ruby-anything record ${repo} "${u.id}"`)
|
|
357
|
+
add('recording untouched', !casesText || sha256(casesText) === entry.cases_sha, 'cases.jsonl was edited: record again, never edit the recording')
|
|
358
|
+
const src = path.join(L.root, u.file)
|
|
359
|
+
add('recording fresh', !fs.existsSync(src) || !entry.source_sha || sha256(fs.readFileSync(src)) === entry.source_sha, `the original changed: ruby-anything record ${repo} "${u.id}"`)
|
|
360
|
+
|
|
361
|
+
const syntax = runSync('ruby', ['-c', portPath], { noShell: true })
|
|
362
|
+
add('ruby syntax', syntax.code === 0, syntax.stderr.trim().split('\n')[0])
|
|
363
|
+
|
|
364
|
+
// the method's own body, for the content checks
|
|
365
|
+
const m = new RegExp(`def\\s+${entry.instance ? '' : 'self\\.'}${entry.method}\\b`).exec(port)
|
|
366
|
+
add('method defined', !!m, `define ${entry.receiver}${entry.instance ? '#' : '.'}${entry.method} in ${entry.port_file}`)
|
|
367
|
+
add('no stubs', !/NotImplementedError|\bTODO\b|\bFIXME\b|raise\s+["']not implemented/i.test(port), 'remove NotImplementedError / TODO stubs')
|
|
368
|
+
add('no debugging', !/\bbinding\.(pry|irb)\b|\bdebugger\b|\bbyebug\b/.test(port), 'remove binding.irb / debugger calls')
|
|
369
|
+
|
|
370
|
+
// no copied answers: long recorded string results or distinctive numbers written into the port
|
|
371
|
+
const cases = readCases(cf)
|
|
372
|
+
const literals = new Set()
|
|
373
|
+
for (const c of cases) {
|
|
374
|
+
const v = plain(c.outcome)
|
|
375
|
+
if (v.kind !== 'return') continue
|
|
376
|
+
const visit = (x) => {
|
|
377
|
+
if (typeof x === 'string' && x.length >= 8 && !/^\s*$/.test(x)) literals.add(x)
|
|
378
|
+
else if (typeof x === 'number' && Math.abs(x) >= 10000 && !Number.isInteger(Math.log10(Math.abs(x)))) literals.add(String(x))
|
|
379
|
+
else if (Array.isArray(x)) x.forEach(visit)
|
|
380
|
+
else if (x && typeof x === 'object') Object.values(x).forEach(visit)
|
|
381
|
+
}
|
|
382
|
+
visit(v.value)
|
|
383
|
+
}
|
|
384
|
+
const srcText = fs.existsSync(src) ? fs.readFileSync(src, 'utf8') : ''
|
|
385
|
+
const copied = [...literals].filter((l) => port.includes(l) && !srcText.includes(l))
|
|
386
|
+
add('computes its results', copied.length === 0, `recorded results written into the port: ${copied.slice(0, 3).map((x) => JSON.stringify(x)).join(', ')}`)
|
|
387
|
+
|
|
388
|
+
// size: at most 3x the original + 50
|
|
389
|
+
const origLines = (u.line_end || 0) - (u.line_start || 0) + 1
|
|
390
|
+
const portLines = port.split('\n').filter((l) => l.trim() && !l.trim().startsWith('#')).length
|
|
391
|
+
add('size', !origLines || portLines <= origLines * 3 + 50 || opts.fileLevel, `port is ${portLines} lines for a ${origLines}-line original: fold repeated code, use Ruby/ActiveSupport`)
|
|
392
|
+
|
|
393
|
+
// error paths reached
|
|
394
|
+
const covered = new Set(cases.map((c) => plain(c.outcome).raise_line).filter(Boolean))
|
|
395
|
+
const missing = (u.raise_lines || []).filter((l) => !covered.has(l))
|
|
396
|
+
add('error paths recorded', missing.length === 0, `no recorded case reaches the raise at ${u.file}:${missing.join(',')}: add one with record --inputs`)
|
|
397
|
+
|
|
398
|
+
// tests never shrink
|
|
399
|
+
const tests = countTests(L)
|
|
400
|
+
const prev = s.gates?.tests || 0
|
|
401
|
+
add('tests kept', tests >= prev, `tests/assertions went from ${prev} to ${tests}: never weaken a test`)
|
|
402
|
+
|
|
403
|
+
// diff
|
|
404
|
+
let d = null
|
|
405
|
+
if (casesText && m) {
|
|
406
|
+
try {
|
|
407
|
+
d = await diffUnit(L, u)
|
|
408
|
+
add(`cases match (${d.matched}/${d.total})`, d.matched === d.total, `ruby-anything diff ${repo} "${u.id}"`)
|
|
409
|
+
} catch (e) {
|
|
410
|
+
add('cases match', false, e.message.split('\n')[0])
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// rubocop when the Rails app has it
|
|
415
|
+
if (fs.existsSync(path.join(L.rails, 'Gemfile')) && /rubocop/.test(fs.readFileSync(path.join(L.rails, 'Gemfile'), 'utf8')) && !opts.noLint) {
|
|
416
|
+
const r = runSync('bundle', ['exec', 'rubocop', '--format', 'simple', entry.port_file.replace(/^rails\//, '')], { cwd: L.rails })
|
|
417
|
+
add('rubocop', r.code === 0, (r.stdout.split('\n').find((l) => /^[A-Z]:/.test(l.trim())) || 'run bundle exec rubocop -a').trim())
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const ok = checks.every((c) => c.ok)
|
|
421
|
+
const s2 = loadState(L)
|
|
422
|
+
if (ok) {
|
|
423
|
+
s2.units[u.id] = { ...s2.units[u.id], status: 'done', gated_at: new Date().toISOString() }
|
|
424
|
+
s2.gates = { ...(s2.gates || {}), tests: Math.max(tests, prev) }
|
|
425
|
+
} else if (s2.units[u.id]) s2.units[u.id].status = 'in progress'
|
|
426
|
+
saveState(L, s2)
|
|
427
|
+
return { ok, checks, diff: d }
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function cmdGate(argv) {
|
|
431
|
+
const a = parseArgs(argv, ['json', 'all', 'noLint', 'app'])
|
|
432
|
+
const L = layout(a._[0])
|
|
433
|
+
if (a.app) return require('./app').cmdAppGate(argv)
|
|
434
|
+
const ids = a.all ? Object.keys(loadState(L).units) : [a._[1]]
|
|
435
|
+
if (!ids[0]) throw new Error('usage: ruby-anything gate <repo> <unit-id> | --all | --app')
|
|
436
|
+
let allOk = true
|
|
437
|
+
const out = []
|
|
438
|
+
for (const id of ids) {
|
|
439
|
+
const u = findUnit(L, id)
|
|
440
|
+
const g = await gateUnit(L, u, { noLint: a.noLint })
|
|
441
|
+
allOk = allOk && g.ok
|
|
442
|
+
out.push({ unit: u.id, ok: g.ok, checks: g.checks })
|
|
443
|
+
if (!a.json) {
|
|
444
|
+
console.log(`${g.ok ? green('PASS') : red('FAIL')} ${u.id}`)
|
|
445
|
+
for (const c of g.checks) console.log(` ${c.ok ? green('ok ') : red('fail')} ${c.name}${c.ok ? '' : dim(` -> ${c.fix}`)}`)
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (a.json) process.stdout.write(JSON.stringify(out, null, 2) + '\n')
|
|
449
|
+
return allOk ? 0 : 1
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
module.exports = { cmdBridge, cmdRecord, cmdDiff, cmdGate, cmdRules, findUnit, loadPlan, portTarget, gateUnit, diffUnit, compareCase, sameError }
|