ruby-anything 0.0.0-stage → 0.1.0

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