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/app.js
ADDED
|
@@ -0,0 +1,774 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
// Whole app: record the original over HTTP (or as a CLI), put a Rails front door in front of it
|
|
3
|
+
// that proxies every route not ported yet, wire routes one at a time, replay, and lift.
|
|
4
|
+
const fs = require('node:fs')
|
|
5
|
+
const path = require('node:path')
|
|
6
|
+
const net = require('node:net')
|
|
7
|
+
const { spawn } = require('node:child_process')
|
|
8
|
+
const {
|
|
9
|
+
PKG, IS_WIN, layout, loadState, saveState, readJSON, writeJSON, writeFile, writeIfMissing, parseArgs, parseJSON, plain,
|
|
10
|
+
canon, runSync, which, slug, camel, green, red, yellow, bold, dim, relTo,
|
|
11
|
+
} = require('./util')
|
|
12
|
+
const { startEffects, dbDump, sleep } = require('./effects')
|
|
13
|
+
const cliApp = require('./cli_app')
|
|
14
|
+
|
|
15
|
+
// Canned answers for outgoing HTTP calls: rails/port/app-cases/effect-replies.json
|
|
16
|
+
// [{"method", "path", "status", "body"}], or --effect-replies <file>.
|
|
17
|
+
function replies(L, s) {
|
|
18
|
+
const f = s.effect_replies ? path.resolve(L.root, s.effect_replies) : path.join(L.appCases, 'effect-replies.json')
|
|
19
|
+
return readJSON(f, [])
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ------------------------------------------------------------------ processes and ports
|
|
23
|
+
function freePort() {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
const s = net.createServer()
|
|
26
|
+
s.unref()
|
|
27
|
+
s.on('error', reject)
|
|
28
|
+
s.listen(0, '127.0.0.1', () => {
|
|
29
|
+
const { port } = s.address()
|
|
30
|
+
s.close(() => resolve(port))
|
|
31
|
+
})
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function waitForPort(port, ms, child) {
|
|
36
|
+
const until = Date.now() + ms
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
const tick = () => {
|
|
39
|
+
if (child && child.exitCode !== null) return reject(new Error(`the server exited with ${child.exitCode} before listening on ${port}:\n${child._log.slice(-1500)}`))
|
|
40
|
+
const sock = net.connect(port, '127.0.0.1')
|
|
41
|
+
sock.once('connect', () => {
|
|
42
|
+
sock.destroy()
|
|
43
|
+
resolve()
|
|
44
|
+
})
|
|
45
|
+
sock.once('error', () => {
|
|
46
|
+
sock.destroy()
|
|
47
|
+
if (Date.now() > until) reject(new Error(`nothing listening on port ${port} after ${ms / 1000}s:\n${child ? child._log.slice(-1500) : ''}`))
|
|
48
|
+
else setTimeout(tick, 300)
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
tick()
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function startServer(command, { cwd, port, env = {} }) {
|
|
56
|
+
const cmd = command.map((x) => x.replace(/\{port\}/g, String(port)))
|
|
57
|
+
const child = spawn(cmd[0], cmd.slice(1), {
|
|
58
|
+
cwd,
|
|
59
|
+
env: { ...process.env, PORT: String(port), ...env },
|
|
60
|
+
shell: IS_WIN,
|
|
61
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
62
|
+
detached: !IS_WIN,
|
|
63
|
+
})
|
|
64
|
+
child._log = ''
|
|
65
|
+
child.stdout.on('data', (d) => (child._log = (child._log + d).slice(-20000)))
|
|
66
|
+
child.stderr.on('data', (d) => (child._log = (child._log + d).slice(-20000)))
|
|
67
|
+
return child
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function stopServer(child) {
|
|
71
|
+
if (!child || child.exitCode !== null) return
|
|
72
|
+
try {
|
|
73
|
+
if (IS_WIN) runSync('taskkill', ['/pid', String(child.pid), '/T', '/F'])
|
|
74
|
+
else process.kill(-child.pid, 'SIGTERM')
|
|
75
|
+
} catch {
|
|
76
|
+
child.kill()
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ------------------------------------------------------------------ responses
|
|
81
|
+
const BLOCK = /<\/?(p|div|section|article|header|footer|nav|main|aside|h[1-6]|li|ul|ol|tr|td|th|table|form|label|button|br|hr|title|option|dt|dd|blockquote|pre|figcaption)\b[^>]*>/gi
|
|
82
|
+
function htmlText(html) {
|
|
83
|
+
const s = html
|
|
84
|
+
.replace(/<!--[\s\S]*?-->/g, ' ')
|
|
85
|
+
.replace(/<(script|style|noscript|template|svg)\b[\s\S]*?<\/\1>/gi, ' ')
|
|
86
|
+
.replace(/<input\b[^>]*\bvalue=["']([^"']*)["'][^>]*>/gi, '\n$1\n')
|
|
87
|
+
.replace(BLOCK, '\n')
|
|
88
|
+
.replace(/<[^>]+>/g, ' ')
|
|
89
|
+
.replace(/ /g, ' ')
|
|
90
|
+
.replace(/&/g, '&')
|
|
91
|
+
.replace(/</g, '<')
|
|
92
|
+
.replace(/>/g, '>')
|
|
93
|
+
.replace(/"/g, '"')
|
|
94
|
+
.replace(/'|'/g, "'")
|
|
95
|
+
return s
|
|
96
|
+
.split('\n')
|
|
97
|
+
.map((l) => l.replace(/\s+/g, ' ').trim())
|
|
98
|
+
.filter(Boolean)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function send(base, r) {
|
|
102
|
+
const headers = { ...(r.headers || {}) }
|
|
103
|
+
let body = r.body
|
|
104
|
+
if (body !== undefined && body !== null && typeof body !== 'string') {
|
|
105
|
+
body = JSON.stringify(body)
|
|
106
|
+
headers['content-type'] = headers['content-type'] || 'application/json'
|
|
107
|
+
}
|
|
108
|
+
const started = Date.now()
|
|
109
|
+
const res = await fetch(base + r.path, { method: r.method || 'GET', headers, body, redirect: 'manual' })
|
|
110
|
+
const text = await res.text()
|
|
111
|
+
const type = (res.headers.get('content-type') || '').split(';')[0].trim()
|
|
112
|
+
const out = { status: res.status, type, ms: Date.now() - started }
|
|
113
|
+
const loc = res.headers.get('location')
|
|
114
|
+
if (loc) out.location = loc.replace(/^https?:\/\/[^/]+/, '')
|
|
115
|
+
if (/json/.test(type)) {
|
|
116
|
+
try {
|
|
117
|
+
out.json = parseJSON(text)
|
|
118
|
+
} catch {
|
|
119
|
+
out.text = [text]
|
|
120
|
+
}
|
|
121
|
+
} else if (/html/.test(type)) out.text = htmlText(text)
|
|
122
|
+
else out.text = text ? text.split('\n').map((l) => l.trimEnd()) : []
|
|
123
|
+
return out
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// One request plus what it caused: outgoing HTTP calls and emails (fx sinks) and, after a write,
|
|
127
|
+
// the database dump.
|
|
128
|
+
async function exchange(base, req, ctx = {}) {
|
|
129
|
+
const { fx, dbDumpCmd, cwd } = ctx
|
|
130
|
+
if (fx) fx.take()
|
|
131
|
+
const out = await send(base, req)
|
|
132
|
+
if (fx && fx.active) {
|
|
133
|
+
await sleep(300) // async mailers and webhooks
|
|
134
|
+
const effects = fx.take().sort((x, y) => (canon([x.kind, x.method || '', x.path || '', x.to || '']) < canon([y.kind, y.method || '', y.path || '', y.to || '']) ? -1 : 1))
|
|
135
|
+
if (effects.length) out.effects = effects
|
|
136
|
+
}
|
|
137
|
+
if (dbDumpCmd && req.method !== 'GET') out.db = dbDump(dbDumpCmd, cwd)
|
|
138
|
+
return out
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function compareEffects(rec, got) {
|
|
142
|
+
const a = rec.effects || []
|
|
143
|
+
const b = got.effects || []
|
|
144
|
+
if (a.length !== b.length) return `${a.length} side effects expected (${a.map((e) => e.kind + ' ' + (e.path || e.subject || '')).join(', ') || 'none'}), got ${b.length}`
|
|
145
|
+
for (let i = 0; i < a.length; i++) {
|
|
146
|
+
if (!matches(a[i], b[i])) return `side effect ${i + 1} (${a[i].kind} ${a[i].method || ''} ${a[i].path || a[i].subject || ''}) differs: ${canon(b[i]).slice(0, 140)}`
|
|
147
|
+
}
|
|
148
|
+
if (rec.db && !matches(rec.db, got.db || [])) {
|
|
149
|
+
const missing = rec.db.find((l) => !(got.db || []).some((g) => matches(l, g)))
|
|
150
|
+
return `database differs after the request${missing ? `, first missing row: ${String(missing).slice(0, 100)}` : ''}`
|
|
151
|
+
}
|
|
152
|
+
return null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Where two runs of the original disagree, the value becomes a [..] wildcard.
|
|
156
|
+
function mergeNoise(a, b) {
|
|
157
|
+
if (canon(a) === canon(b)) return a
|
|
158
|
+
if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) return a.map((x, i) => mergeNoise(x, b[i]))
|
|
159
|
+
if (a && b && typeof a === 'object' && typeof b === 'object' && !('$n' in a) && !Array.isArray(a)) {
|
|
160
|
+
const o = {}
|
|
161
|
+
for (const k of Object.keys(a)) o[k] = k in b ? mergeNoise(a[k], b[k]) : a[k]
|
|
162
|
+
return o
|
|
163
|
+
}
|
|
164
|
+
if (typeof a === 'string' && typeof b === 'string') {
|
|
165
|
+
const tok = (s) => s.split(/(\s+)/)
|
|
166
|
+
const ta = tok(a)
|
|
167
|
+
const tb = tok(b)
|
|
168
|
+
if (ta.length === tb.length) return ta.map((t, i) => (t === tb[i] ? t : '[..]')).join('')
|
|
169
|
+
}
|
|
170
|
+
return '[..]'
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function matches(expected, actual) {
|
|
174
|
+
if (expected === '[..]') return true
|
|
175
|
+
if (typeof expected === 'string' && expected.includes('[..]') && typeof actual === 'string') {
|
|
176
|
+
const re = new RegExp('^' + expected.split('[..]').map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*?') + '$', 's')
|
|
177
|
+
return re.test(actual)
|
|
178
|
+
}
|
|
179
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && expected.length === actual.length && expected.every((x, i) => matches(x, actual[i]))
|
|
180
|
+
if (expected && typeof expected === 'object' && !('$n' in expected)) {
|
|
181
|
+
if (!actual || typeof actual !== 'object' || Array.isArray(actual)) return false
|
|
182
|
+
const ka = Object.keys(expected).sort()
|
|
183
|
+
const kb = Object.keys(actual).sort()
|
|
184
|
+
return canon(ka) === canon(kb) && ka.every((k) => matches(expected[k], actual[k]))
|
|
185
|
+
}
|
|
186
|
+
return canon(expected) === canon(actual)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function compareResponse(rec, got, mode) {
|
|
190
|
+
if (rec.status !== got.status) return `status ${rec.status} vs ${got.status}`
|
|
191
|
+
const fxDiff = compareEffects(rec, got)
|
|
192
|
+
if (fxDiff) return fxDiff
|
|
193
|
+
if ((rec.location || '') !== (got.location || '') && !matches(rec.location || '', got.location || '')) return `redirect ${rec.location} vs ${got.location}`
|
|
194
|
+
if (mode === 'status') return null
|
|
195
|
+
if (rec.json !== undefined) {
|
|
196
|
+
if (got.json === undefined) return `JSON expected, got ${got.type || 'no content type'}`
|
|
197
|
+
return matches(rec.json, got.json) ? null : `JSON body differs: ${canon(rec.json).slice(0, 120)} vs ${canon(got.json).slice(0, 120)}`
|
|
198
|
+
}
|
|
199
|
+
if (rec.text && /html/.test(rec.type) && mode !== 'exact') {
|
|
200
|
+
// Rebuilt views may add markup and chrome; every line of the original's text must still be there.
|
|
201
|
+
const have = (got.text || []).join('\n')
|
|
202
|
+
const missing = rec.text.filter((line) => !(line.includes('[..]') ? matches(line, (got.text || []).find((g) => matches(line, g)) || '') : have.includes(line)))
|
|
203
|
+
return missing.length ? `${missing.length} text lines missing, first: ${JSON.stringify(missing[0]).slice(0, 100)}` : null
|
|
204
|
+
}
|
|
205
|
+
if (rec.text && !matches(rec.text, got.text || [])) return `body differs`
|
|
206
|
+
return null
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ------------------------------------------------------------------ settings and cases
|
|
210
|
+
function settings(L) {
|
|
211
|
+
return readJSON(L.settings, { mode: 'text', original: null, original_cwd: null, port: null, db_reset: null, inputs: [] })
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// HTTP or CLI cases, whichever this app was recorded as.
|
|
215
|
+
function loadCases(L) {
|
|
216
|
+
return settings(L).kind === 'cli' ? cliApp.cliCases(L) : caseFiles(L).map((f) => readJSON(f))
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function caseFiles(L) {
|
|
220
|
+
const dir = path.join(L.appCases, 'http')
|
|
221
|
+
if (!fs.existsSync(dir)) return []
|
|
222
|
+
return fs.readdirSync(dir).filter((f) => f.endsWith('.json')).sort().map((f) => path.join(dir, f))
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function discoveredRequests(L) {
|
|
226
|
+
const plan = readJSON(L.planJson, { routes: [] })
|
|
227
|
+
const reqs = [{ name: 'root', method: 'GET', path: '/' }]
|
|
228
|
+
for (const r of plan.routes || []) {
|
|
229
|
+
if ((r.method === 'GET' || r.method === 'ANY') && !r.path.includes(':') && !r.path.includes('*') && r.path !== '/') reqs.push({ name: slug(r.path), method: 'GET', path: r.path })
|
|
230
|
+
}
|
|
231
|
+
return reqs
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ------------------------------------------------------------------ app record
|
|
235
|
+
async function cmdAppRecord(argv) {
|
|
236
|
+
const a = parseArgs(argv, ['http', 'noDiscover', 'cli', 'ignoreStderr'])
|
|
237
|
+
const L = layout(a._[0])
|
|
238
|
+
if (a.cli) {
|
|
239
|
+
if (!a.rest.length) throw new Error('usage: ruby-anything app record <repo> --cli --inputs cli.jsonl -- <command that runs the original>')
|
|
240
|
+
return cliApp.recordCli(L, a, settings(L), mergeNoise)
|
|
241
|
+
}
|
|
242
|
+
if (!a.rest.length && !a.url) throw new Error('usage: ruby-anything app record <repo> --http [--inputs requests.jsonl] -- <command that starts the original, reading PORT or {port}>')
|
|
243
|
+
const s = settings(L)
|
|
244
|
+
const inputs = a.inputs ? fs.readFileSync(path.resolve(a.inputs), 'utf8').split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l)) : []
|
|
245
|
+
const requests = [...(a.noDiscover ? [] : discoveredRequests(L)), ...inputs]
|
|
246
|
+
const seen = new Set()
|
|
247
|
+
const uniq = requests.filter((r) => {
|
|
248
|
+
const k = `${r.method || 'GET'} ${r.path} ${canon(r.body ?? null)}`
|
|
249
|
+
return seen.has(k) ? false : (seen.add(k), true)
|
|
250
|
+
})
|
|
251
|
+
let child = null
|
|
252
|
+
let base = a.url
|
|
253
|
+
if (a.effectEnv !== undefined) s.effect_env = a.effectEnv || null
|
|
254
|
+
if (a.dbDump !== undefined) s.db_dump = a.dbDump || null
|
|
255
|
+
if (a.effectReplies) s.effect_replies = a.effectReplies
|
|
256
|
+
const fx = await startEffects(s.effect_env, { replies: replies(L, s) })
|
|
257
|
+
const ctx = { fx, dbDumpCmd: s.db_dump, cwd: L.root }
|
|
258
|
+
if (!base) {
|
|
259
|
+
const port = a.port ? Number(a.port) : await freePort()
|
|
260
|
+
if (a.dbReset) runSync(a.dbReset, [], { cwd: L.root, shell: true })
|
|
261
|
+
console.error(dim(`starting the original on port ${port}: ${a.rest.join(' ')}`))
|
|
262
|
+
child = startServer(a.rest, { cwd: L.root, port, env: fx.env })
|
|
263
|
+
await waitForPort(port, Number(a.timeout || 60) * 1000, child)
|
|
264
|
+
base = `http://127.0.0.1:${port}`
|
|
265
|
+
s.original = a.rest
|
|
266
|
+
s.original_cwd = '.'
|
|
267
|
+
s.port = a.port ? Number(a.port) : null
|
|
268
|
+
}
|
|
269
|
+
if (a.dbReset) s.db_reset = a.dbReset
|
|
270
|
+
if (a.mode) s.mode = a.mode
|
|
271
|
+
const dir = path.join(L.appCases, 'http')
|
|
272
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
273
|
+
let n = 0
|
|
274
|
+
const noisy = []
|
|
275
|
+
try {
|
|
276
|
+
for (const r of uniq) {
|
|
277
|
+
const req = { method: (r.method || 'GET').toUpperCase(), path: r.path, headers: r.headers || {}, body: r.body }
|
|
278
|
+
let first
|
|
279
|
+
try {
|
|
280
|
+
first = await exchange(base, req, ctx)
|
|
281
|
+
} catch (e) {
|
|
282
|
+
console.log(yellow(` ${req.method} ${req.path}: ${e.message}`))
|
|
283
|
+
continue
|
|
284
|
+
}
|
|
285
|
+
let response = first
|
|
286
|
+
if (req.method === 'GET') {
|
|
287
|
+
const second = await exchange(base, req, ctx)
|
|
288
|
+
const strip = (x) => ({ ...x, ms: 0 })
|
|
289
|
+
response = mergeNoise(strip(first), strip(second))
|
|
290
|
+
response.type = first.type
|
|
291
|
+
if (canon(strip(first)) !== canon(strip(second))) noisy.push(req.path)
|
|
292
|
+
}
|
|
293
|
+
delete response.ms
|
|
294
|
+
n++
|
|
295
|
+
const name = `${String(n).padStart(3, '0')}-${slug(r.name || `${req.method} ${req.path}`).slice(0, 50)}`
|
|
296
|
+
writeFile(path.join(dir, `${name}.json`), JSON.stringify({ name, request: req, response: plainKeep(response) }, null, 2) + '\n')
|
|
297
|
+
const fxNote = [first.effects ? `${first.effects.length} side effects` : '', first.db ? 'db dumped' : ''].filter(Boolean).join(', ')
|
|
298
|
+
console.log(` ${req.method} ${req.path} -> ${first.status} ${first.type}${fxNote ? dim(` (${fxNote})`) : ''}`)
|
|
299
|
+
}
|
|
300
|
+
} finally {
|
|
301
|
+
stopServer(child)
|
|
302
|
+
fx.stop()
|
|
303
|
+
}
|
|
304
|
+
writeJSON(L.settings, s)
|
|
305
|
+
console.log(`${n} HTTP cases -> ${relTo(L.root, dir)}`)
|
|
306
|
+
if (noisy.length) console.log(yellow(`${noisy.length} pages changed between two runs (timestamps, ids, order): [..] wildcards were added. Ask the user whether order is part of the contract: ${noisy.slice(0, 5).join(', ')}`))
|
|
307
|
+
console.log(`next: ruby-anything app replay ${a._[0] || '.'} --original (the original must pass 100%)`)
|
|
308
|
+
return 0
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// keep {$n} numbers exact on disk by writing them as plain numbers with their lexeme
|
|
312
|
+
function plainKeep(v) {
|
|
313
|
+
return JSON.parse(canon(v))
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ------------------------------------------------------------------ app replay
|
|
317
|
+
function wiredRoutes(L) {
|
|
318
|
+
const f = path.join(L.rails, 'config', 'ruby_anything.yml')
|
|
319
|
+
if (!fs.existsSync(f)) return []
|
|
320
|
+
const out = []
|
|
321
|
+
for (const line of fs.readFileSync(f, 'utf8').split('\n')) {
|
|
322
|
+
const m = line.match(/^\s*-\s*route:\s*["']?([A-Z*]+)\s+([^"'\s]+)["']?\s*(?:#.*)?$/)
|
|
323
|
+
if (m) out.push({ method: m[1], path: m[2] })
|
|
324
|
+
const u = line.match(/^\s*unit:\s*["']?([^"'\s]+)/)
|
|
325
|
+
if (u && out.length) out[out.length - 1].unit = u[1]
|
|
326
|
+
}
|
|
327
|
+
return out
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function routeMatches(route, method, p) {
|
|
331
|
+
if (route.path === '*') return true
|
|
332
|
+
if (route.method !== '*' && route.method !== 'ANY' && route.method !== method) return false
|
|
333
|
+
const re = new RegExp('^' + route.path.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\\\*$/, '.*').replace(/:\w+/g, '[^/]+') + '/?$')
|
|
334
|
+
return re.test(p.split('?')[0])
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function fallbackRate(L, cases) {
|
|
338
|
+
if (cases[0] && cases[0].kind === 'cli') return cliApp.fallbackCli(L, cases)
|
|
339
|
+
if (isLifted(L)) return { fallback: 0, total: cases.length, names: [] }
|
|
340
|
+
const wired = wiredRoutes(L)
|
|
341
|
+
const fallback = cases.filter((c) => !wired.some((r) => routeMatches(r, c.request.method, c.request.path)))
|
|
342
|
+
return { fallback: fallback.length, total: cases.length, names: fallback.map((c) => c.name) }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async function replayAgainst(L, base, cases, mode, only, ctx = {}) {
|
|
346
|
+
const results = []
|
|
347
|
+
for (const c of cases) {
|
|
348
|
+
if (only && !c.name.includes(only)) continue
|
|
349
|
+
let got
|
|
350
|
+
try {
|
|
351
|
+
got = await exchange(base, c.request, ctx)
|
|
352
|
+
} catch (e) {
|
|
353
|
+
results.push({ name: c.name, ok: false, why: e.message })
|
|
354
|
+
continue
|
|
355
|
+
}
|
|
356
|
+
const why = compareResponse(c.response, got, mode)
|
|
357
|
+
results.push({ name: c.name, ok: !why, why, request: `${c.request.method} ${c.request.path}` })
|
|
358
|
+
}
|
|
359
|
+
return results
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function cmdAppReplay(argv) {
|
|
363
|
+
const a = parseArgs(argv, ['original', 'json', 'redact', 'noOriginal'])
|
|
364
|
+
const L = layout(a._[0])
|
|
365
|
+
const s = settings(L)
|
|
366
|
+
const cases = loadCases(L)
|
|
367
|
+
if (!cases.length) throw new Error(`no app cases: ruby-anything app record ${L.root} --http -- <command>`)
|
|
368
|
+
const mode = a.mode || s.mode || 'text'
|
|
369
|
+
const isCli = s.kind === 'cli'
|
|
370
|
+
const procs = []
|
|
371
|
+
const fx = await startEffects(s.effect_env, { replies: replies(L, s) })
|
|
372
|
+
const ctx = { fx, dbDumpCmd: s.db_dump, cwd: L.root }
|
|
373
|
+
let base = a.url
|
|
374
|
+
try {
|
|
375
|
+
if (isCli) {
|
|
376
|
+
// CLI cases run one invocation at a time; no servers
|
|
377
|
+
} else if (!base && a.original) {
|
|
378
|
+
if (!s.original) throw new Error('the original command is unknown: record again')
|
|
379
|
+
const port = await freePort()
|
|
380
|
+
if (s.db_reset) runSync(s.db_reset, [], { cwd: L.root, shell: true })
|
|
381
|
+
const p = startServer(s.original, { cwd: path.join(L.root, s.original_cwd || '.'), port, env: fx.env })
|
|
382
|
+
procs.push(p)
|
|
383
|
+
await waitForPort(port, 60000, p)
|
|
384
|
+
base = `http://127.0.0.1:${port}`
|
|
385
|
+
} else if (!base) {
|
|
386
|
+
// the Rails app, with the original behind it for routes not wired yet
|
|
387
|
+
const env = { RAILS_ENV: a.env || 'development' }
|
|
388
|
+
const fr = fallbackRate(L, cases)
|
|
389
|
+
if (fr.fallback && s.original && !a.noOriginal && !isLifted(L)) {
|
|
390
|
+
const op = await freePort()
|
|
391
|
+
if (s.db_reset) runSync(s.db_reset, [], { cwd: L.root, shell: true })
|
|
392
|
+
const p = startServer(s.original, { cwd: path.join(L.root, s.original_cwd || '.'), port: op, env: fx.env })
|
|
393
|
+
procs.push(p)
|
|
394
|
+
await waitForPort(op, 60000, p)
|
|
395
|
+
env.RUBY_ANYTHING_ORIGINAL_URL = `http://127.0.0.1:${op}`
|
|
396
|
+
}
|
|
397
|
+
const port = await freePort()
|
|
398
|
+
const cmd = a.build ? String(a.build).split(' ') : ['bundle', 'exec', 'rails', 'server', '-b', '127.0.0.1', '-p', '{port}']
|
|
399
|
+
if (!fs.existsSync(path.join(L.rails, 'Gemfile')) && !a.build) throw new Error(`no Rails app yet: ruby-anything app front-door ${a._[0] || '.'}`)
|
|
400
|
+
const p = startServer(cmd, { cwd: L.rails, port, env: { ...fx.env, ...env } })
|
|
401
|
+
procs.push(p)
|
|
402
|
+
await waitForPort(port, 120000, p)
|
|
403
|
+
base = `http://127.0.0.1:${port}`
|
|
404
|
+
}
|
|
405
|
+
if (!isCli && s.db_reset && !a.original) runSync(s.db_reset, [], { cwd: L.root, shell: true })
|
|
406
|
+
const results = isCli ? cliApp.replayCli(L, a, s, cases, matches) : await replayAgainst(L, base, cases, mode, a.case, ctx)
|
|
407
|
+
const ok = results.filter((r) => r.ok).length
|
|
408
|
+
const fr = fallbackRate(L, cases)
|
|
409
|
+
const report = { target: a.original ? 'original' : a.url || 'rails', matched: ok, total: results.length, fallback: fr.fallback, cases: results.length, mode, failures: results.filter((r) => !r.ok) }
|
|
410
|
+
writeJSON(path.join(L.reports, 'last-replay.json'), report)
|
|
411
|
+
if (!a.original && !a.case) {
|
|
412
|
+
const st = loadState(L)
|
|
413
|
+
st.app = { ...(st.app || {}), last_replay: { matched: ok, total: results.length, fallback: fr.fallback, at: new Date().toISOString() } }
|
|
414
|
+
saveState(L, st)
|
|
415
|
+
}
|
|
416
|
+
if (a.json) {
|
|
417
|
+
process.stdout.write(JSON.stringify(report, null, 2) + '\n')
|
|
418
|
+
} else {
|
|
419
|
+
console.log(`${ok === results.length ? green(`${ok}/${results.length} match`) : red(`${ok}/${results.length} match`)} against ${report.target} (mode: ${mode})`)
|
|
420
|
+
if (!a.original) console.log(`fallback rate: ${fr.fallback}/${fr.total} cases still answered by the original`)
|
|
421
|
+
const groups = {}
|
|
422
|
+
for (const f of report.failures) {
|
|
423
|
+
const key = (f.why || '').replace(/".*$/, '').replace(/\d+ text lines/, 'N text lines')
|
|
424
|
+
;(groups[key] = groups[key] || []).push(f)
|
|
425
|
+
}
|
|
426
|
+
for (const [k, fs2] of Object.entries(groups).sort((x, y) => y[1].length - x[1].length)) {
|
|
427
|
+
console.log(` ${fs2.length} x ${bold(k)} e.g. ${fs2[0].request || fs2[0].name}${a.redact ? '' : dim(' ' + (fs2[0].why || ''))}`)
|
|
428
|
+
}
|
|
429
|
+
if (report.failures.length) console.log(`rerun one case: ruby-anything app replay ${a._[0] || '.'} --case ${report.failures[0].name}`)
|
|
430
|
+
}
|
|
431
|
+
return ok === results.length ? 0 : 1
|
|
432
|
+
} finally {
|
|
433
|
+
procs.reverse().forEach(stopServer)
|
|
434
|
+
fx.stop()
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ------------------------------------------------------------------ front door
|
|
439
|
+
const FRONT_DOOR_RB = `# frozen_string_literal: true
|
|
440
|
+
|
|
441
|
+
require "net/http"
|
|
442
|
+
require "yaml"
|
|
443
|
+
|
|
444
|
+
# ruby-anything front door: every request Rails does not own yet is proxied to the original app
|
|
445
|
+
# (RUBY_ANYTHING_ORIGINAL_URL). Wired routes live in config/ruby_anything.yml. Kill switch per unit:
|
|
446
|
+
# RUBY_ANYTHING_UNIT_<NAME>=original sends that unit's routes back to the original.
|
|
447
|
+
# \`ruby-anything app lift\` deletes this file once nothing falls back.
|
|
448
|
+
module RubyAnything
|
|
449
|
+
class FrontDoor
|
|
450
|
+
RAILS_PATHS = %r{\\A/(assets|rails|cable|up|icon|favicon|robots)(/|\\.|\\z)}
|
|
451
|
+
HOP = %w[connection keep-alive proxy-authenticate proxy-authorization te trailer transfer-encoding upgrade host content-length].freeze
|
|
452
|
+
|
|
453
|
+
def initialize(app)
|
|
454
|
+
@app = app
|
|
455
|
+
@original = URI(ENV.fetch("RUBY_ANYTHING_ORIGINAL_URL"))
|
|
456
|
+
@config = Rails.root.join("config", "ruby_anything.yml")
|
|
457
|
+
end
|
|
458
|
+
|
|
459
|
+
def call(env)
|
|
460
|
+
req = Rack::Request.new(env)
|
|
461
|
+
return @app.call(env) if req.path.match?(RAILS_PATHS) || owned?(req)
|
|
462
|
+
|
|
463
|
+
proxy(req)
|
|
464
|
+
end
|
|
465
|
+
|
|
466
|
+
private
|
|
467
|
+
|
|
468
|
+
def routes
|
|
469
|
+
mtime = File.mtime(@config) rescue nil
|
|
470
|
+
return @routes if @routes && mtime == @mtime
|
|
471
|
+
|
|
472
|
+
@mtime = mtime
|
|
473
|
+
@routes = (mtime ? Array(YAML.safe_load_file(@config)&.fetch("wired", nil)) : []).filter_map do |w|
|
|
474
|
+
method, path = w["route"].to_s.split(" ", 2)
|
|
475
|
+
next unless path
|
|
476
|
+
|
|
477
|
+
pattern = path == "*" ? /./ : Regexp.new("\\\\A" + Regexp.escape(path).gsub(/:\\w+/, "[^/]+").sub(/\\\\\\*\\z/, ".*") + "/?\\\\z")
|
|
478
|
+
{ method: method, pattern: pattern, unit: w["unit"].to_s }
|
|
479
|
+
end
|
|
480
|
+
end
|
|
481
|
+
|
|
482
|
+
def owned?(req)
|
|
483
|
+
routes.any? do |r|
|
|
484
|
+
(r[:method] == "*" || r[:method] == "ANY" || r[:method] == req.request_method) && r[:pattern].match?(req.path) &&
|
|
485
|
+
ENV["RUBY_ANYTHING_UNIT_#{r[:unit].upcase.gsub(/[^A-Z0-9]/, '_')}"] != "original"
|
|
486
|
+
end
|
|
487
|
+
end
|
|
488
|
+
|
|
489
|
+
def proxy(req)
|
|
490
|
+
http = Net::HTTP.new(@original.host, @original.port)
|
|
491
|
+
http.read_timeout = 60
|
|
492
|
+
klass = Net::HTTP.const_get(req.request_method.capitalize)
|
|
493
|
+
out = klass.new(req.fullpath)
|
|
494
|
+
req.each_header do |k, v|
|
|
495
|
+
next unless k.start_with?("HTTP_") || %w[CONTENT_TYPE CONTENT_LENGTH].include?(k)
|
|
496
|
+
|
|
497
|
+
name = k.sub(/\\AHTTP_/, "").downcase.tr("_", "-")
|
|
498
|
+
out[name] = v unless HOP.include?(name)
|
|
499
|
+
end
|
|
500
|
+
if req.body
|
|
501
|
+
out.body = req.body.read
|
|
502
|
+
req.body.rewind
|
|
503
|
+
end
|
|
504
|
+
res = http.request(out)
|
|
505
|
+
headers = {}
|
|
506
|
+
res.each_header { |k, v| headers[k] = v unless HOP.include?(k) || k == "set-cookie" }
|
|
507
|
+
cookies = res.get_fields("set-cookie")
|
|
508
|
+
headers["set-cookie"] = cookies if cookies
|
|
509
|
+
headers["x-ruby-anything"] = "original"
|
|
510
|
+
[ res.code.to_i, headers, [ res.body.to_s ] ]
|
|
511
|
+
rescue Errno::ECONNREFUSED, Net::OpenTimeout => e
|
|
512
|
+
[ 502, { "content-type" => "text/plain" }, [ "ruby-anything front door: original app unreachable (#{e.class})" ] ]
|
|
513
|
+
end
|
|
514
|
+
end
|
|
515
|
+
end
|
|
516
|
+
`
|
|
517
|
+
|
|
518
|
+
const INITIALIZER_RB = `# frozen_string_literal: true
|
|
519
|
+
|
|
520
|
+
# ruby-anything: proxy routes not ported yet to the original app (removed by \`ruby-anything app lift\`).
|
|
521
|
+
if ENV["RUBY_ANYTHING_ORIGINAL_URL"].present?
|
|
522
|
+
require Rails.root.join("lib", "ruby_anything", "front_door").to_s
|
|
523
|
+
Rails.application.config.middleware.insert_before 0, RubyAnything::FrontDoor
|
|
524
|
+
end
|
|
525
|
+
`
|
|
526
|
+
|
|
527
|
+
const CONFIG_YML = `# Routes Rails answers itself. Everything else goes to the original app while it runs behind the
|
|
528
|
+
# front door. Added with: ruby-anything app wire <repo> <unit> --route "GET /path/:id"
|
|
529
|
+
wired: []
|
|
530
|
+
`
|
|
531
|
+
|
|
532
|
+
function isLifted(L) {
|
|
533
|
+
if (settings(L).kind === 'cli') return !!(cliApp && readJSON(path.join(L.rails, 'config', 'ruby_anything.yml'), {}).lifted)
|
|
534
|
+
return !fs.existsSync(path.join(L.rails, 'lib', 'ruby_anything', 'front_door.rb')) && fs.existsSync(path.join(L.rails, 'Gemfile'))
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function downloadTo(url, file) {
|
|
538
|
+
const res = await fetch(url, { redirect: 'follow' })
|
|
539
|
+
if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`)
|
|
540
|
+
writeFile(file, Buffer.from(await res.arrayBuffer()))
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function cmdAppFrontDoor(argv) {
|
|
544
|
+
const a = parseArgs(argv, ['noDaisyui', 'skipNew'])
|
|
545
|
+
const L = layout(a._[0])
|
|
546
|
+
const name = a.name || `${camel(path.basename(L.root)) || 'App'}Rails`
|
|
547
|
+
if (!fs.existsSync(path.join(L.rails, 'Gemfile'))) {
|
|
548
|
+
if (a.skipNew) throw new Error(`no Rails app in ${L.rails}`)
|
|
549
|
+
if (!which('rails')) throw new Error('the rails gem is not installed: gem install rails, then run again (ruby-anything doctor)')
|
|
550
|
+
const args = ['new', 'rails', `--name=${name}`, '--skip-git', '--css=tailwind', '--javascript=importmap', `--database=${a.database || 'sqlite3'}`, '--skip-kamal', '--skip-thruster']
|
|
551
|
+
console.log(dim(`rails ${args.join(' ')}`))
|
|
552
|
+
const r = runSync('rails', args, { cwd: L.root, stdio: 'inherit' })
|
|
553
|
+
if (r.code !== 0) throw new Error('rails new failed (output above)')
|
|
554
|
+
}
|
|
555
|
+
// daisyUI on the Tailwind standalone CLI: the plugin files sit next to application.css
|
|
556
|
+
const tw = path.join(L.rails, 'app', 'assets', 'tailwind')
|
|
557
|
+
const css = path.join(tw, 'application.css')
|
|
558
|
+
if (!a.noDaisyui && fs.existsSync(css) && !fs.readFileSync(css, 'utf8').includes('daisyui')) {
|
|
559
|
+
try {
|
|
560
|
+
const v = a.daisyuiVersion || 'latest'
|
|
561
|
+
const base = v === 'latest' ? 'https://github.com/saadeghi/daisyui/releases/latest/download' : `https://github.com/saadeghi/daisyui/releases/download/v${v}`
|
|
562
|
+
await downloadTo(`${base}/daisyui.mjs`, path.join(tw, 'daisyui.mjs'))
|
|
563
|
+
await downloadTo(`${base}/daisyui-theme.mjs`, path.join(tw, 'daisyui-theme.mjs'))
|
|
564
|
+
const text = fs.readFileSync(css, 'utf8').replace(/(@import\s+["']tailwindcss["'];?)/, `$1\n@plugin "./daisyui.mjs" {\n themes: light --default, dark --prefersdark;\n}`)
|
|
565
|
+
fs.writeFileSync(css, text.includes('daisyui') ? text : `@import "tailwindcss";\n@plugin "./daisyui.mjs";\n` + text)
|
|
566
|
+
console.log('daisyUI added to app/assets/tailwind/application.css')
|
|
567
|
+
} catch (e) {
|
|
568
|
+
console.log(yellow(`daisyUI not downloaded (${e.message}); add app/assets/tailwind/daisyui.mjs by hand, see the skill's frontend.md`))
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (settings(L).kind === 'cli') cliApp.frontDoorCli(L, settings(L))
|
|
572
|
+
else {
|
|
573
|
+
writeFile(path.join(L.rails, 'lib', 'ruby_anything', 'front_door.rb'), FRONT_DOOR_RB)
|
|
574
|
+
writeFile(path.join(L.rails, 'config', 'initializers', 'ruby_anything.rb'), INITIALIZER_RB)
|
|
575
|
+
writeIfMissing(path.join(L.rails, 'config', 'ruby_anything.yml'), CONFIG_YML)
|
|
576
|
+
}
|
|
577
|
+
for (const [f, t] of [
|
|
578
|
+
[L.decisions, '# Decisions\n\nOne ADR per decision, numbered in order, never renumbered.\n'],
|
|
579
|
+
[L.glossary, '# Glossary\n\n| Original term | Meaning | Ruby name |\n|---|---|---|\n'],
|
|
580
|
+
[L.map, '# Port map\n\nGoal: the whole app on Rails 8 + Hotwire + Tailwind + daisyUI.\n\n| Unit | State | Notes |\n|---|---|---|\n'],
|
|
581
|
+
]) writeIfMissing(f, t)
|
|
582
|
+
const st = loadState(L)
|
|
583
|
+
st.app = { ...(st.app || {}), front_door: true }
|
|
584
|
+
saveState(L, st)
|
|
585
|
+
if (settings(L).kind !== 'cli') console.log(`front door ready in ${relTo(process.cwd(), L.rails)}: Rails proxies every route not in config/ruby_anything.yml to the original.`)
|
|
586
|
+
console.log(`next: ruby-anything app replay ${a._[0] || '.'} (must match 100% before anything moves)`)
|
|
587
|
+
return 0
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// ------------------------------------------------------------------ wire
|
|
591
|
+
function cmdAppWire(argv) {
|
|
592
|
+
const a = parseArgs(argv, ['remove'])
|
|
593
|
+
const L = layout(a._[0])
|
|
594
|
+
const unit = a._[1]
|
|
595
|
+
const route = a.route
|
|
596
|
+
if (unit && a.command) {
|
|
597
|
+
cliApp.wireCommand(L, unit, String(a.command), a.remove)
|
|
598
|
+
const fr = fallbackRate(L, loadCases(L))
|
|
599
|
+
console.log(`${a.remove ? 'unwired' : 'wired'} command ${a.command} (${slug(unit)}). Fallback rate: ${fr.fallback}/${fr.total}.`)
|
|
600
|
+
console.log(`kill switch: RUBY_ANYTHING_UNIT_${slug(unit).toUpperCase()}=original
|
|
601
|
+
next: ruby-anything app replay ${a._[0] || '.'}`)
|
|
602
|
+
return 0
|
|
603
|
+
}
|
|
604
|
+
if (!unit || !route) throw new Error('usage: ruby-anything app wire <repo> <unit-name> --route "GET /users/:id" (--remove to unwire)')
|
|
605
|
+
const m = String(route).match(/^(GET|POST|PUT|PATCH|DELETE|ANY|\*)\s+(\/\S*|\*)$/i)
|
|
606
|
+
if (!m) throw new Error('route looks like "GET /users/:id", "ANY /admin/*" or "* *"')
|
|
607
|
+
const f = path.join(L.rails, 'config', 'ruby_anything.yml')
|
|
608
|
+
if (!fs.existsSync(f)) throw new Error(`no front door: ruby-anything app front-door ${a._[0] || '.'}`)
|
|
609
|
+
const entry = ` - route: "${m[1].toUpperCase()} ${m[2]}"\n unit: ${slug(unit)}\n`
|
|
610
|
+
let text = fs.readFileSync(f, 'utf8').replace(/^wired:\s*\[\]\s*$/m, 'wired:')
|
|
611
|
+
if (a.remove) {
|
|
612
|
+
text = text.replace(entry, '')
|
|
613
|
+
if (!/^\s*- route:/m.test(text)) text = text.replace(/^wired:\s*$/m, 'wired: []')
|
|
614
|
+
} else if (!text.includes(`route: "${m[1].toUpperCase()} ${m[2]}"`)) {
|
|
615
|
+
text = text.replace(/\n*$/, '\n') + entry
|
|
616
|
+
}
|
|
617
|
+
fs.writeFileSync(f, text)
|
|
618
|
+
const cases = loadCases(L)
|
|
619
|
+
const fr = fallbackRate(L, cases)
|
|
620
|
+
console.log(`${a.remove ? 'unwired' : 'wired'} ${m[1].toUpperCase()} ${m[2]} (${slug(unit)}). Fallback rate: ${fr.fallback}/${fr.total}.`)
|
|
621
|
+
console.log(`kill switch: RUBY_ANYTHING_UNIT_${slug(unit).toUpperCase()}=original\nnext: ruby-anything app replay ${a._[0] || '.'}`)
|
|
622
|
+
return 0
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// ------------------------------------------------------------------ status / map
|
|
626
|
+
function cmdAppStatus(argv) {
|
|
627
|
+
const a = parseArgs(argv, ['json', 'write'])
|
|
628
|
+
const L = layout(a._[0])
|
|
629
|
+
const st = loadState(L)
|
|
630
|
+
const cases = loadCases(L)
|
|
631
|
+
const fr = fallbackRate(L, cases)
|
|
632
|
+
const wired = wiredRoutes(L)
|
|
633
|
+
const plan = readJSON(L.planJson, { units: [], routes: [], templates: [] })
|
|
634
|
+
const units = Object.entries(st.units || {})
|
|
635
|
+
const done = units.filter(([, u]) => u.status === 'done').length
|
|
636
|
+
const routesLeft = (plan.routes || []).filter((r) => !wired.some((w) => routeMatches(w, r.method === 'ANY' ? 'GET' : r.method, r.path.replace(/:\w+/g, 'x'))))
|
|
637
|
+
const status = {
|
|
638
|
+
plan: !!plan.units.length || !!plan.routes.length,
|
|
639
|
+
app_cases: cases.length,
|
|
640
|
+
front_door: fs.existsSync(path.join(L.rails, 'lib', 'ruby_anything', 'front_door.rb')),
|
|
641
|
+
lifted: isLifted(L),
|
|
642
|
+
fallback: fr,
|
|
643
|
+
wired,
|
|
644
|
+
units: { total: plan.units.length, bridged: units.length, done },
|
|
645
|
+
routes_left: routesLeft.map((r) => r.id),
|
|
646
|
+
last_replay: st.app?.last_replay || null,
|
|
647
|
+
}
|
|
648
|
+
if (a.write || !a.json) {
|
|
649
|
+
const md = [
|
|
650
|
+
'# Measured port state (generated by ruby-anything app status --write; MAP.md is the plan)',
|
|
651
|
+
'',
|
|
652
|
+
`- App cases: ${cases.length}; last replay: ${status.last_replay ? `${status.last_replay.matched}/${status.last_replay.total} (${status.last_replay.at})` : 'never'}`,
|
|
653
|
+
`- Fallback rate: ${fr.fallback}/${fr.total}`,
|
|
654
|
+
`- Front door: ${status.front_door ? 'yes' : status.lifted ? 'lifted' : 'no'}`,
|
|
655
|
+
`- Units: ${done} done of ${units.length} bridged (${plan.units.length} in plan)`,
|
|
656
|
+
'',
|
|
657
|
+
'## Wired routes',
|
|
658
|
+
...wired.map((w) => `- ${w.method} ${w.path} (${w.unit || '?'})`),
|
|
659
|
+
'',
|
|
660
|
+
'## Routes still answered by the original',
|
|
661
|
+
...routesLeft.map((r) => `- ${r.id}`),
|
|
662
|
+
'',
|
|
663
|
+
'## Units',
|
|
664
|
+
...units.map(([id, u]) => `- ${id}: ${u.status}${u.last_diff ? ` (${u.last_diff.matched}/${u.last_diff.total})` : ''}`),
|
|
665
|
+
'',
|
|
666
|
+
].join('\n')
|
|
667
|
+
writeFile(path.join(L.port, 'PORT_MAP.md'), md)
|
|
668
|
+
}
|
|
669
|
+
if (a.json) process.stdout.write(JSON.stringify(status, null, 2) + '\n')
|
|
670
|
+
else {
|
|
671
|
+
console.log(bold('port status'))
|
|
672
|
+
console.log(` app cases ${cases.length}, fallback ${fr.fallback}/${fr.total}, wired routes ${wired.length}, units done ${done}/${units.length}`)
|
|
673
|
+
if (status.last_replay) console.log(` last replay ${status.last_replay.matched}/${status.last_replay.total}`)
|
|
674
|
+
console.log(` ${relTo(process.cwd(), path.join(L.port, 'PORT_MAP.md'))}`)
|
|
675
|
+
}
|
|
676
|
+
return 0
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// ------------------------------------------------------------------ app gate + lift
|
|
680
|
+
async function appGate(L, a) {
|
|
681
|
+
const checks = []
|
|
682
|
+
const add = (name, ok, fix) => checks.push({ name, ok, fix: ok ? undefined : fix })
|
|
683
|
+
const repo = path.relative(process.cwd(), L.root) || '.'
|
|
684
|
+
const cases = loadCases(L)
|
|
685
|
+
add('app recorded', cases.length > 0, `ruby-anything app record ${repo} --http -- <command>`)
|
|
686
|
+
const st = loadState(L)
|
|
687
|
+
const pending = Object.entries(st.units || {}).filter(([, u]) => u.status !== 'done')
|
|
688
|
+
add('every bridged unit gated', pending.length === 0, `gate: ${pending.slice(0, 3).map(([id]) => id).join(', ')}`)
|
|
689
|
+
const tests = runSync('bin/rails', ['test'], { cwd: L.rails })
|
|
690
|
+
add('rails test', tests.code === 0, (tests.stdout + tests.stderr).split('\n').filter((l) => /Error|Failure|failures/.test(l)).slice(0, 2).join(' | ') || 'bin/rails test')
|
|
691
|
+
if (fs.existsSync(path.join(L.rails, 'bin', 'rubocop')) && !a.noLint) {
|
|
692
|
+
const r = runSync('bin/rubocop', ['--format', 'simple'], { cwd: L.rails })
|
|
693
|
+
add('rubocop', r.code === 0, 'bin/rubocop -a, then fix what remains')
|
|
694
|
+
}
|
|
695
|
+
if (fs.existsSync(path.join(L.rails, 'bin', 'brakeman'))) {
|
|
696
|
+
const r = runSync('bin/brakeman', ['--no-pager', '-q', '--no-exit-on-warn'], { cwd: L.rails })
|
|
697
|
+
add('brakeman', !/Security Warnings: [1-9]/.test(r.stdout), 'bin/brakeman: fix the security warnings')
|
|
698
|
+
}
|
|
699
|
+
if (cases.length) {
|
|
700
|
+
const code = await cmdAppReplay([L.root, '--json', ...(a.noOriginal ? ['--no-original'] : [])].concat(a.build ? ['--build', a.build] : [])).catch((e) => (add('replay', false, e.message.split('\n')[0]), null))
|
|
701
|
+
if (code !== null) {
|
|
702
|
+
const rep = readJSON(path.join(L.reports, 'last-replay.json'))
|
|
703
|
+
add(`replay ${rep.matched}/${rep.total}`, rep.matched === rep.total, `ruby-anything app replay ${repo} --case ${rep.failures[0]?.name || ''}`)
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return { ok: checks.every((c) => c.ok), checks }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
async function cmdAppGate(argv) {
|
|
710
|
+
const a = parseArgs(argv, ['json', 'app', 'noLint'])
|
|
711
|
+
const L = layout(a._[0])
|
|
712
|
+
const origLog = console.log
|
|
713
|
+
console.log = () => {}
|
|
714
|
+
const write = process.stdout.write.bind(process.stdout)
|
|
715
|
+
process.stdout.write = () => true
|
|
716
|
+
let g
|
|
717
|
+
try {
|
|
718
|
+
g = await appGate(L, a)
|
|
719
|
+
} finally {
|
|
720
|
+
console.log = origLog
|
|
721
|
+
process.stdout.write = write
|
|
722
|
+
}
|
|
723
|
+
if (a.json) process.stdout.write(JSON.stringify(g, null, 2) + '\n')
|
|
724
|
+
else {
|
|
725
|
+
console.log(`${g.ok ? green('PASS') : red('FAIL')} app`)
|
|
726
|
+
for (const c of g.checks) console.log(` ${c.ok ? green('ok ') : red('fail')} ${c.name}${c.ok ? '' : dim(` -> ${c.fix}`)}`)
|
|
727
|
+
}
|
|
728
|
+
return g.ok ? 0 : 1
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
async function cmdAppLift(argv) {
|
|
732
|
+
const a = parseArgs(argv, ['force'])
|
|
733
|
+
const L = layout(a._[0])
|
|
734
|
+
const cases = loadCases(L)
|
|
735
|
+
const fr = fallbackRate(L, cases)
|
|
736
|
+
const blockers = []
|
|
737
|
+
if (!cases.length) blockers.push('no app cases recorded')
|
|
738
|
+
if (fr.fallback) blockers.push(`${fr.fallback} cases still fall back to the original: ${fr.names.slice(0, 8).join(', ')}`)
|
|
739
|
+
const st = loadState(L)
|
|
740
|
+
const pending = Object.entries(st.units || {}).filter(([, u]) => u.status !== 'done')
|
|
741
|
+
if (pending.length) blockers.push(`units not gated: ${pending.map(([id]) => id).slice(0, 8).join(', ')}`)
|
|
742
|
+
if (blockers.length) {
|
|
743
|
+
console.log(red('lift refused:'))
|
|
744
|
+
blockers.forEach((b) => console.log(` - ${b}`))
|
|
745
|
+
return 1
|
|
746
|
+
}
|
|
747
|
+
// replay with no original behind Rails: everything must be answered by Rails alone
|
|
748
|
+
const code = await cmdAppReplay([L.root, '--no-original'])
|
|
749
|
+
if (code !== 0) {
|
|
750
|
+
console.log(red('lift refused: Rails alone does not match every case (report above)'))
|
|
751
|
+
return 1
|
|
752
|
+
}
|
|
753
|
+
if (settings(L).kind === 'cli') cliApp.liftCli(L)
|
|
754
|
+
else for (const f of [path.join(L.rails, 'lib', 'ruby_anything', 'front_door.rb'), path.join(L.rails, 'config', 'initializers', 'ruby_anything.rb'), path.join(L.rails, 'config', 'ruby_anything.yml')]) fs.rmSync(f, { force: true })
|
|
755
|
+
try {
|
|
756
|
+
fs.rmdirSync(path.join(L.rails, 'lib', 'ruby_anything'))
|
|
757
|
+
} catch {}
|
|
758
|
+
writeFile(path.join(L.reports, 'LIFT.md'), `# Lifted ${new Date().toISOString()}\n\nThe front door and kill switches are gone; Rails answers all ${cases.length} recorded cases alone.\nRun \`ruby-anything app replay ${relTo(process.cwd(), L.root) || '.'}\` in CI to keep it that way.\n`)
|
|
759
|
+
st.app = { ...(st.app || {}), lifted: new Date().toISOString(), front_door: false }
|
|
760
|
+
saveState(L, st)
|
|
761
|
+
console.log(green(`lifted: the app runs on Rails alone (${cases.length}/${cases.length} cases).`))
|
|
762
|
+
console.log('The original stays in place as reference until the user retires it.')
|
|
763
|
+
return 0
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
async function cmdApp(argv) {
|
|
767
|
+
const sub = argv[0]
|
|
768
|
+
const rest = argv.slice(1)
|
|
769
|
+
const table = { drift: (r) => require('./drift').cmdDrift(r), record: cmdAppRecord, replay: cmdAppReplay, 'front-door': cmdAppFrontDoor, wire: cmdAppWire, status: cmdAppStatus, lift: cmdAppLift, gate: cmdAppGate }
|
|
770
|
+
if (!table[sub]) throw new Error(`usage: ruby-anything app <${Object.keys(table).join('|')}> <repo> ...`)
|
|
771
|
+
return table[sub](rest)
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
module.exports = { loadCases, cmdApp, cmdAppRecord, cmdAppReplay, cmdAppFrontDoor, cmdAppWire, cmdAppStatus, cmdAppLift, cmdAppGate, appGate, htmlText, compareResponse, mergeNoise, matches, caseFiles, fallbackRate, isLifted, settings }
|