ruby-anything 0.1.0 → 0.2.1
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 +1 -1
- package/.claude-plugin/plugin.json +9 -2
- package/README.md +36 -4
- package/action.yml +56 -0
- package/adapters/node/harness.mjs +28 -2
- package/adapters/node/package-lock.json +26 -26
- package/adapters/node/package.json +7 -7
- package/adapters/polyglot/harness.py +350 -350
- package/adapters/polyglot/lang_csharp.py +222 -222
- package/adapters/polyglot/lang_java.py +510 -510
- package/adapters/polyglot/lang_rust.py +430 -430
- package/adapters/polyglot/lang_swift.py +337 -337
- package/adapters/python/harness.py +42 -0
- package/adapters/ruby/harness.rb +134 -0
- package/harness/ruby_replay.rb +11 -0
- package/package.json +8 -7
- package/skills/ruby-anything/SKILL.md +17 -1
- package/skills/ruby-anything/whole-app.md +37 -1
- package/src/adapters.js +60 -60
- package/src/app.js +102 -25
- package/src/cli.js +7 -2
- package/src/cli_app.js +251 -0
- package/src/drift.js +124 -0
- package/src/effects.js +145 -0
- package/src/fromtests.js +105 -0
- package/src/go.js +30 -4
- package/src/units.js +11 -3
package/src/app.js
CHANGED
|
@@ -9,6 +9,15 @@ const {
|
|
|
9
9
|
PKG, IS_WIN, layout, loadState, saveState, readJSON, writeJSON, writeFile, writeIfMissing, parseArgs, parseJSON, plain,
|
|
10
10
|
canon, runSync, which, slug, camel, green, red, yellow, bold, dim, relTo,
|
|
11
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
|
+
}
|
|
12
21
|
|
|
13
22
|
// ------------------------------------------------------------------ processes and ports
|
|
14
23
|
function freePort() {
|
|
@@ -114,6 +123,35 @@ async function send(base, r) {
|
|
|
114
123
|
return out
|
|
115
124
|
}
|
|
116
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
|
+
|
|
117
155
|
// Where two runs of the original disagree, the value becomes a [..] wildcard.
|
|
118
156
|
function mergeNoise(a, b) {
|
|
119
157
|
if (canon(a) === canon(b)) return a
|
|
@@ -150,6 +188,8 @@ function matches(expected, actual) {
|
|
|
150
188
|
|
|
151
189
|
function compareResponse(rec, got, mode) {
|
|
152
190
|
if (rec.status !== got.status) return `status ${rec.status} vs ${got.status}`
|
|
191
|
+
const fxDiff = compareEffects(rec, got)
|
|
192
|
+
if (fxDiff) return fxDiff
|
|
153
193
|
if ((rec.location || '') !== (got.location || '') && !matches(rec.location || '', got.location || '')) return `redirect ${rec.location} vs ${got.location}`
|
|
154
194
|
if (mode === 'status') return null
|
|
155
195
|
if (rec.json !== undefined) {
|
|
@@ -171,6 +211,11 @@ function settings(L) {
|
|
|
171
211
|
return readJSON(L.settings, { mode: 'text', original: null, original_cwd: null, port: null, db_reset: null, inputs: [] })
|
|
172
212
|
}
|
|
173
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
|
+
|
|
174
219
|
function caseFiles(L) {
|
|
175
220
|
const dir = path.join(L.appCases, 'http')
|
|
176
221
|
if (!fs.existsSync(dir)) return []
|
|
@@ -188,8 +233,12 @@ function discoveredRequests(L) {
|
|
|
188
233
|
|
|
189
234
|
// ------------------------------------------------------------------ app record
|
|
190
235
|
async function cmdAppRecord(argv) {
|
|
191
|
-
const a = parseArgs(argv, ['http', 'noDiscover'])
|
|
236
|
+
const a = parseArgs(argv, ['http', 'noDiscover', 'cli', 'ignoreStderr'])
|
|
192
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
|
+
}
|
|
193
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}>')
|
|
194
243
|
const s = settings(L)
|
|
195
244
|
const inputs = a.inputs ? fs.readFileSync(path.resolve(a.inputs), 'utf8').split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l)) : []
|
|
@@ -201,11 +250,16 @@ async function cmdAppRecord(argv) {
|
|
|
201
250
|
})
|
|
202
251
|
let child = null
|
|
203
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 }
|
|
204
258
|
if (!base) {
|
|
205
259
|
const port = a.port ? Number(a.port) : await freePort()
|
|
206
260
|
if (a.dbReset) runSync(a.dbReset, [], { cwd: L.root, shell: true })
|
|
207
261
|
console.error(dim(`starting the original on port ${port}: ${a.rest.join(' ')}`))
|
|
208
|
-
child = startServer(a.rest, { cwd: L.root, port })
|
|
262
|
+
child = startServer(a.rest, { cwd: L.root, port, env: fx.env })
|
|
209
263
|
await waitForPort(port, Number(a.timeout || 60) * 1000, child)
|
|
210
264
|
base = `http://127.0.0.1:${port}`
|
|
211
265
|
s.original = a.rest
|
|
@@ -223,14 +277,14 @@ async function cmdAppRecord(argv) {
|
|
|
223
277
|
const req = { method: (r.method || 'GET').toUpperCase(), path: r.path, headers: r.headers || {}, body: r.body }
|
|
224
278
|
let first
|
|
225
279
|
try {
|
|
226
|
-
first = await
|
|
280
|
+
first = await exchange(base, req, ctx)
|
|
227
281
|
} catch (e) {
|
|
228
282
|
console.log(yellow(` ${req.method} ${req.path}: ${e.message}`))
|
|
229
283
|
continue
|
|
230
284
|
}
|
|
231
285
|
let response = first
|
|
232
286
|
if (req.method === 'GET') {
|
|
233
|
-
const second = await
|
|
287
|
+
const second = await exchange(base, req, ctx)
|
|
234
288
|
const strip = (x) => ({ ...x, ms: 0 })
|
|
235
289
|
response = mergeNoise(strip(first), strip(second))
|
|
236
290
|
response.type = first.type
|
|
@@ -240,10 +294,12 @@ async function cmdAppRecord(argv) {
|
|
|
240
294
|
n++
|
|
241
295
|
const name = `${String(n).padStart(3, '0')}-${slug(r.name || `${req.method} ${req.path}`).slice(0, 50)}`
|
|
242
296
|
writeFile(path.join(dir, `${name}.json`), JSON.stringify({ name, request: req, response: plainKeep(response) }, null, 2) + '\n')
|
|
243
|
-
|
|
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})`) : ''}`)
|
|
244
299
|
}
|
|
245
300
|
} finally {
|
|
246
301
|
stopServer(child)
|
|
302
|
+
fx.stop()
|
|
247
303
|
}
|
|
248
304
|
writeJSON(L.settings, s)
|
|
249
305
|
console.log(`${n} HTTP cases -> ${relTo(L.root, dir)}`)
|
|
@@ -279,19 +335,20 @@ function routeMatches(route, method, p) {
|
|
|
279
335
|
}
|
|
280
336
|
|
|
281
337
|
function fallbackRate(L, cases) {
|
|
338
|
+
if (cases[0] && cases[0].kind === 'cli') return cliApp.fallbackCli(L, cases)
|
|
282
339
|
if (isLifted(L)) return { fallback: 0, total: cases.length, names: [] }
|
|
283
340
|
const wired = wiredRoutes(L)
|
|
284
341
|
const fallback = cases.filter((c) => !wired.some((r) => routeMatches(r, c.request.method, c.request.path)))
|
|
285
342
|
return { fallback: fallback.length, total: cases.length, names: fallback.map((c) => c.name) }
|
|
286
343
|
}
|
|
287
344
|
|
|
288
|
-
async function replayAgainst(L, base, cases, mode, only) {
|
|
345
|
+
async function replayAgainst(L, base, cases, mode, only, ctx = {}) {
|
|
289
346
|
const results = []
|
|
290
347
|
for (const c of cases) {
|
|
291
348
|
if (only && !c.name.includes(only)) continue
|
|
292
349
|
let got
|
|
293
350
|
try {
|
|
294
|
-
got = await
|
|
351
|
+
got = await exchange(base, c.request, ctx)
|
|
295
352
|
} catch (e) {
|
|
296
353
|
results.push({ name: c.name, ok: false, why: e.message })
|
|
297
354
|
continue
|
|
@@ -306,17 +363,22 @@ async function cmdAppReplay(argv) {
|
|
|
306
363
|
const a = parseArgs(argv, ['original', 'json', 'redact', 'noOriginal'])
|
|
307
364
|
const L = layout(a._[0])
|
|
308
365
|
const s = settings(L)
|
|
309
|
-
const cases =
|
|
366
|
+
const cases = loadCases(L)
|
|
310
367
|
if (!cases.length) throw new Error(`no app cases: ruby-anything app record ${L.root} --http -- <command>`)
|
|
311
368
|
const mode = a.mode || s.mode || 'text'
|
|
369
|
+
const isCli = s.kind === 'cli'
|
|
312
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 }
|
|
313
373
|
let base = a.url
|
|
314
374
|
try {
|
|
315
|
-
if (
|
|
375
|
+
if (isCli) {
|
|
376
|
+
// CLI cases run one invocation at a time; no servers
|
|
377
|
+
} else if (!base && a.original) {
|
|
316
378
|
if (!s.original) throw new Error('the original command is unknown: record again')
|
|
317
379
|
const port = await freePort()
|
|
318
380
|
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 })
|
|
381
|
+
const p = startServer(s.original, { cwd: path.join(L.root, s.original_cwd || '.'), port, env: fx.env })
|
|
320
382
|
procs.push(p)
|
|
321
383
|
await waitForPort(port, 60000, p)
|
|
322
384
|
base = `http://127.0.0.1:${port}`
|
|
@@ -327,7 +389,7 @@ async function cmdAppReplay(argv) {
|
|
|
327
389
|
if (fr.fallback && s.original && !a.noOriginal && !isLifted(L)) {
|
|
328
390
|
const op = await freePort()
|
|
329
391
|
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 })
|
|
392
|
+
const p = startServer(s.original, { cwd: path.join(L.root, s.original_cwd || '.'), port: op, env: fx.env })
|
|
331
393
|
procs.push(p)
|
|
332
394
|
await waitForPort(op, 60000, p)
|
|
333
395
|
env.RUBY_ANYTHING_ORIGINAL_URL = `http://127.0.0.1:${op}`
|
|
@@ -335,12 +397,13 @@ async function cmdAppReplay(argv) {
|
|
|
335
397
|
const port = await freePort()
|
|
336
398
|
const cmd = a.build ? String(a.build).split(' ') : ['bundle', 'exec', 'rails', 'server', '-b', '127.0.0.1', '-p', '{port}']
|
|
337
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] || '.'}`)
|
|
338
|
-
const p = startServer(cmd, { cwd: L.rails, port, env })
|
|
400
|
+
const p = startServer(cmd, { cwd: L.rails, port, env: { ...fx.env, ...env } })
|
|
339
401
|
procs.push(p)
|
|
340
402
|
await waitForPort(port, 120000, p)
|
|
341
403
|
base = `http://127.0.0.1:${port}`
|
|
342
404
|
}
|
|
343
|
-
|
|
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)
|
|
344
407
|
const ok = results.filter((r) => r.ok).length
|
|
345
408
|
const fr = fallbackRate(L, cases)
|
|
346
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) }
|
|
@@ -368,6 +431,7 @@ async function cmdAppReplay(argv) {
|
|
|
368
431
|
return ok === results.length ? 0 : 1
|
|
369
432
|
} finally {
|
|
370
433
|
procs.reverse().forEach(stopServer)
|
|
434
|
+
fx.stop()
|
|
371
435
|
}
|
|
372
436
|
}
|
|
373
437
|
|
|
@@ -466,6 +530,7 @@ wired: []
|
|
|
466
530
|
`
|
|
467
531
|
|
|
468
532
|
function isLifted(L) {
|
|
533
|
+
if (settings(L).kind === 'cli') return !!(cliApp && readJSON(path.join(L.rails, 'config', 'ruby_anything.yml'), {}).lifted)
|
|
469
534
|
return !fs.existsSync(path.join(L.rails, 'lib', 'ruby_anything', 'front_door.rb')) && fs.existsSync(path.join(L.rails, 'Gemfile'))
|
|
470
535
|
}
|
|
471
536
|
|
|
@@ -503,9 +568,12 @@ async function cmdAppFrontDoor(argv) {
|
|
|
503
568
|
console.log(yellow(`daisyUI not downloaded (${e.message}); add app/assets/tailwind/daisyui.mjs by hand, see the skill's frontend.md`))
|
|
504
569
|
}
|
|
505
570
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
+
}
|
|
509
577
|
for (const [f, t] of [
|
|
510
578
|
[L.decisions, '# Decisions\n\nOne ADR per decision, numbered in order, never renumbered.\n'],
|
|
511
579
|
[L.glossary, '# Glossary\n\n| Original term | Meaning | Ruby name |\n|---|---|---|\n'],
|
|
@@ -514,8 +582,8 @@ async function cmdAppFrontDoor(argv) {
|
|
|
514
582
|
const st = loadState(L)
|
|
515
583
|
st.app = { ...(st.app || {}), front_door: true }
|
|
516
584
|
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
|
|
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)`)
|
|
519
587
|
return 0
|
|
520
588
|
}
|
|
521
589
|
|
|
@@ -525,6 +593,14 @@ function cmdAppWire(argv) {
|
|
|
525
593
|
const L = layout(a._[0])
|
|
526
594
|
const unit = a._[1]
|
|
527
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
|
+
}
|
|
528
604
|
if (!unit || !route) throw new Error('usage: ruby-anything app wire <repo> <unit-name> --route "GET /users/:id" (--remove to unwire)')
|
|
529
605
|
const m = String(route).match(/^(GET|POST|PUT|PATCH|DELETE|ANY|\*)\s+(\/\S*|\*)$/i)
|
|
530
606
|
if (!m) throw new Error('route looks like "GET /users/:id", "ANY /admin/*" or "* *"')
|
|
@@ -539,7 +615,7 @@ function cmdAppWire(argv) {
|
|
|
539
615
|
text = text.replace(/\n*$/, '\n') + entry
|
|
540
616
|
}
|
|
541
617
|
fs.writeFileSync(f, text)
|
|
542
|
-
const cases =
|
|
618
|
+
const cases = loadCases(L)
|
|
543
619
|
const fr = fallbackRate(L, cases)
|
|
544
620
|
console.log(`${a.remove ? 'unwired' : 'wired'} ${m[1].toUpperCase()} ${m[2]} (${slug(unit)}). Fallback rate: ${fr.fallback}/${fr.total}.`)
|
|
545
621
|
console.log(`kill switch: RUBY_ANYTHING_UNIT_${slug(unit).toUpperCase()}=original\nnext: ruby-anything app replay ${a._[0] || '.'}`)
|
|
@@ -551,7 +627,7 @@ function cmdAppStatus(argv) {
|
|
|
551
627
|
const a = parseArgs(argv, ['json', 'write'])
|
|
552
628
|
const L = layout(a._[0])
|
|
553
629
|
const st = loadState(L)
|
|
554
|
-
const cases =
|
|
630
|
+
const cases = loadCases(L)
|
|
555
631
|
const fr = fallbackRate(L, cases)
|
|
556
632
|
const wired = wiredRoutes(L)
|
|
557
633
|
const plan = readJSON(L.planJson, { units: [], routes: [], templates: [] })
|
|
@@ -605,7 +681,7 @@ async function appGate(L, a) {
|
|
|
605
681
|
const checks = []
|
|
606
682
|
const add = (name, ok, fix) => checks.push({ name, ok, fix: ok ? undefined : fix })
|
|
607
683
|
const repo = path.relative(process.cwd(), L.root) || '.'
|
|
608
|
-
const cases =
|
|
684
|
+
const cases = loadCases(L)
|
|
609
685
|
add('app recorded', cases.length > 0, `ruby-anything app record ${repo} --http -- <command>`)
|
|
610
686
|
const st = loadState(L)
|
|
611
687
|
const pending = Object.entries(st.units || {}).filter(([, u]) => u.status !== 'done')
|
|
@@ -655,7 +731,7 @@ async function cmdAppGate(argv) {
|
|
|
655
731
|
async function cmdAppLift(argv) {
|
|
656
732
|
const a = parseArgs(argv, ['force'])
|
|
657
733
|
const L = layout(a._[0])
|
|
658
|
-
const cases =
|
|
734
|
+
const cases = loadCases(L)
|
|
659
735
|
const fr = fallbackRate(L, cases)
|
|
660
736
|
const blockers = []
|
|
661
737
|
if (!cases.length) blockers.push('no app cases recorded')
|
|
@@ -674,7 +750,8 @@ async function cmdAppLift(argv) {
|
|
|
674
750
|
console.log(red('lift refused: Rails alone does not match every case (report above)'))
|
|
675
751
|
return 1
|
|
676
752
|
}
|
|
677
|
-
|
|
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 })
|
|
678
755
|
try {
|
|
679
756
|
fs.rmdirSync(path.join(L.rails, 'lib', 'ruby_anything'))
|
|
680
757
|
} catch {}
|
|
@@ -689,9 +766,9 @@ async function cmdAppLift(argv) {
|
|
|
689
766
|
async function cmdApp(argv) {
|
|
690
767
|
const sub = argv[0]
|
|
691
768
|
const rest = argv.slice(1)
|
|
692
|
-
const table = { record: cmdAppRecord, replay: cmdAppReplay, 'front-door': cmdAppFrontDoor, wire: cmdAppWire, status: cmdAppStatus, lift: cmdAppLift, gate: cmdAppGate }
|
|
769
|
+
const table = { drift: (r) => require('./drift').cmdDrift(r), record: cmdAppRecord, replay: cmdAppReplay, 'front-door': cmdAppFrontDoor, wire: cmdAppWire, status: cmdAppStatus, lift: cmdAppLift, gate: cmdAppGate }
|
|
693
770
|
if (!table[sub]) throw new Error(`usage: ruby-anything app <${Object.keys(table).join('|')}> <repo> ...`)
|
|
694
771
|
return table[sub](rest)
|
|
695
772
|
}
|
|
696
773
|
|
|
697
|
-
module.exports = { cmdApp, cmdAppRecord, cmdAppReplay, cmdAppFrontDoor, cmdAppWire, cmdAppStatus, cmdAppLift, cmdAppGate, appGate, htmlText, compareResponse, mergeNoise, matches, caseFiles, fallbackRate, isLifted, settings }
|
|
774
|
+
module.exports = { loadCases, cmdApp, cmdAppRecord, cmdAppReplay, cmdAppFrontDoor, cmdAppWire, cmdAppStatus, cmdAppLift, cmdAppGate, appGate, htmlText, compareResponse, mergeNoise, matches, caseFiles, fallbackRate, isLifted, settings }
|
package/src/cli.js
CHANGED
|
@@ -12,13 +12,16 @@ Plan
|
|
|
12
12
|
|
|
13
13
|
One unit (a function)
|
|
14
14
|
bridge <repo> <unit> Ruby skeleton in rails/app/services + TASK.md
|
|
15
|
-
record <repo> <unit> [--inputs f] [--count N]
|
|
15
|
+
record <repo> <unit> [--inputs f] [--count N] [--pin-clock] [--from-tests -- <test cmd>]
|
|
16
|
+
the original's behavior -> rails/port/cases
|
|
16
17
|
diff <repo> <unit> [--json] replay the cases against the Ruby port (must be N/N)
|
|
17
18
|
gate <repo> <unit>|--all|--app done means gate passes
|
|
18
19
|
rules <repo> [--add "<rule>"] behavior the user corrected; every unit keeps it
|
|
20
|
+
drift <repo> has the original changed since recording? (units + app)
|
|
19
21
|
|
|
20
22
|
Whole app
|
|
21
|
-
app record <repo> --http [--inputs f] [--db-reset cmd] --
|
|
23
|
+
app record <repo> --http [--inputs f] [--db-reset cmd] [--db-dump cmd]
|
|
24
|
+
[--effect-env NAME=http|smtp|smtp_host|smtp_port,...] -- <start command>
|
|
22
25
|
app front-door <repo> Rails 8 app that proxies routes not ported yet to the original
|
|
23
26
|
app wire <repo> <unit> --route "GET /path/:id"
|
|
24
27
|
app replay <repo> [--original] [--case name] [--mode text|status|exact]
|
|
@@ -63,6 +66,8 @@ async function main(argv) {
|
|
|
63
66
|
return require('./units').cmdRules(rest)
|
|
64
67
|
case 'app':
|
|
65
68
|
return require('./app').cmdApp(rest)
|
|
69
|
+
case 'drift':
|
|
70
|
+
return require('./drift').cmdDrift(rest)
|
|
66
71
|
case 'map':
|
|
67
72
|
return require('./app').cmdAppStatus([...rest, '--write'])
|
|
68
73
|
case 'mcp':
|
package/src/cli_app.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
// Whole CLI apps: record what each invocation does (exit code, stdout, stderr, files written),
|
|
3
|
+
// put a Ruby front door in front of the original (rails/bin/<name>: ported commands run in Rails,
|
|
4
|
+
// the rest exec the original), wire commands one at a time, replay, lift.
|
|
5
|
+
//
|
|
6
|
+
// ruby-anything app record <repo> --cli --inputs cli.jsonl -- python tool.py
|
|
7
|
+
// cli.jsonl: {"name": "...", "args": ["export", "--csv"], "stdin": "...", "env": {"K": "v"}}
|
|
8
|
+
const fs = require('node:fs')
|
|
9
|
+
const os = require('node:os')
|
|
10
|
+
const path = require('node:path')
|
|
11
|
+
const crypto = require('node:crypto')
|
|
12
|
+
const { spawnSync } = require('node:child_process')
|
|
13
|
+
const { IS_WIN, readJSON, writeJSON, writeFile, slug, camel, canon, relTo, green, red, yellow, bold, dim } = require('./util')
|
|
14
|
+
|
|
15
|
+
const HEAVY = new Set(['node_modules', 'vendor', '.venv', 'venv', '.git', 'target', '.gradle', 'bin', 'obj'])
|
|
16
|
+
const SKIP = new Set(['rails', '.ra-runs'])
|
|
17
|
+
|
|
18
|
+
// A throwaway copy of the repo to run one invocation in. Heavy folders are linked, not copied.
|
|
19
|
+
function sandboxCopy(root) {
|
|
20
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ra-cli-'))
|
|
21
|
+
for (const e of fs.readdirSync(root, { withFileTypes: true })) {
|
|
22
|
+
if (SKIP.has(e.name)) continue
|
|
23
|
+
const from = path.join(root, e.name)
|
|
24
|
+
const to = path.join(dir, e.name)
|
|
25
|
+
if (e.isDirectory() && HEAVY.has(e.name)) {
|
|
26
|
+
try {
|
|
27
|
+
fs.symlinkSync(from, to, IS_WIN ? 'junction' : 'dir')
|
|
28
|
+
} catch {
|
|
29
|
+
fs.cpSync(from, to, { recursive: true })
|
|
30
|
+
}
|
|
31
|
+
} else fs.cpSync(from, to, { recursive: true })
|
|
32
|
+
}
|
|
33
|
+
return dir
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function snapshot(dir) {
|
|
37
|
+
const out = {}
|
|
38
|
+
const walk = (d, rel) => {
|
|
39
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
40
|
+
if (HEAVY.has(e.name) || SKIP.has(e.name) || e.name === '__pycache__') continue
|
|
41
|
+
const p = path.join(d, e.name)
|
|
42
|
+
const r = rel ? `${rel}/${e.name}` : e.name
|
|
43
|
+
if (e.isDirectory()) walk(p, r)
|
|
44
|
+
else if (e.isFile()) out[r] = crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex')
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
walk(dir, '')
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function fileChanges(dir, before) {
|
|
52
|
+
const after = snapshot(dir)
|
|
53
|
+
const out = []
|
|
54
|
+
for (const [p, sha] of Object.entries(after)) {
|
|
55
|
+
if (before[p] === sha) continue
|
|
56
|
+
const buf = fs.readFileSync(path.join(dir, p))
|
|
57
|
+
const text = buf.length <= 65536 && !buf.includes(0) ? buf.toString('utf8').replace(/\r\n/g, '\n').split('\n') : null
|
|
58
|
+
out.push({ path: p, status: before[p] ? 'changed' : 'added', ...(text ? { text } : { sha256: sha }) })
|
|
59
|
+
}
|
|
60
|
+
for (const p of Object.keys(before)) if (!(p in after)) out.push({ path: p, status: 'deleted' })
|
|
61
|
+
return out.sort((x, y) => (x.path < y.path ? -1 : 1))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const lines = (s) => String(s || '').replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n').filter((l, i, a) => a.length > 1 || l !== '')
|
|
65
|
+
|
|
66
|
+
// Runs `command + input.args` in a fresh copy of the repo.
|
|
67
|
+
function invoke(root, command, input, extraEnv = {}) {
|
|
68
|
+
const dir = sandboxCopy(root)
|
|
69
|
+
try {
|
|
70
|
+
const before = snapshot(dir)
|
|
71
|
+
const argv = [...command, ...(input.args || [])]
|
|
72
|
+
const r = spawnSync(argv[0], argv.slice(1), {
|
|
73
|
+
cwd: dir,
|
|
74
|
+
input: input.stdin || '',
|
|
75
|
+
encoding: 'utf8',
|
|
76
|
+
env: { ...process.env, ...extraEnv, ...(input.env || {}) },
|
|
77
|
+
shell: IS_WIN,
|
|
78
|
+
timeout: 120000,
|
|
79
|
+
maxBuffer: 64 << 20,
|
|
80
|
+
})
|
|
81
|
+
if (r.error && r.error.code === 'ETIMEDOUT') return { code: null, stdout: [], stderr: ['timed out after 120s'], files: [] }
|
|
82
|
+
return { code: r.status, stdout: lines(r.stdout), stderr: lines(r.stderr), files: fileChanges(dir, before) }
|
|
83
|
+
} finally {
|
|
84
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function cliDir(L) {
|
|
89
|
+
return path.join(L.appCases, 'cli')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function cliCases(L) {
|
|
93
|
+
const d = cliDir(L)
|
|
94
|
+
return fs.existsSync(d) ? fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort().map((f) => readJSON(path.join(d, f))) : []
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ------------------------------------------------------------------ record
|
|
98
|
+
function recordCli(L, a, s, mergeNoise) {
|
|
99
|
+
if (!a.inputs) throw new Error('usage: ruby-anything app record <repo> --cli --inputs cli.jsonl -- <command that runs the original>\n cli.jsonl: {"name", "args": [...], "stdin", "env"} per line')
|
|
100
|
+
const inputs = fs.readFileSync(path.resolve(a.inputs), 'utf8').split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l))
|
|
101
|
+
const dir = cliDir(L)
|
|
102
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
103
|
+
const noisy = []
|
|
104
|
+
inputs.forEach((input, i) => {
|
|
105
|
+
const first = invoke(L.root, a.rest, input)
|
|
106
|
+
const second = invoke(L.root, a.rest, input)
|
|
107
|
+
const output = mergeNoise(first, second)
|
|
108
|
+
if (canon(first) !== canon(second)) noisy.push(input.name || (input.args || []).join(' '))
|
|
109
|
+
const name = `${String(i + 1).padStart(3, '0')}-${slug(input.name || (input.args || []).join(' ') || 'no-args').slice(0, 50)}`
|
|
110
|
+
writeFile(path.join(dir, `${name}.json`), JSON.stringify({ name, kind: 'cli', input: { args: input.args || [], stdin: input.stdin || '', env: input.env || {} }, output }, null, 2) + '\n')
|
|
111
|
+
console.log(` ${[...a.rest, ...(input.args || [])].join(' ')} -> exit ${first.code}${first.files.length ? dim(` (${first.files.length} files written)`) : ''}`)
|
|
112
|
+
})
|
|
113
|
+
s.kind = 'cli'
|
|
114
|
+
s.original = a.rest
|
|
115
|
+
s.cli_name = s.cli_name || a.name || slug(path.basename(L.root)) || 'app'
|
|
116
|
+
if (a.ignoreStderr) s.ignore_stderr = true
|
|
117
|
+
writeJSON(L.settings, s)
|
|
118
|
+
console.log(`${inputs.length} CLI cases -> ${relTo(L.root, dir)}`)
|
|
119
|
+
if (noisy.length) console.log(yellow(`${noisy.length} invocations changed between two runs: [..] wildcards were added (${noisy.slice(0, 5).join(', ')})`))
|
|
120
|
+
console.log(`next: ruby-anything app replay ${relTo(process.cwd(), L.root) || '.'} --original (the original must pass 100%)`)
|
|
121
|
+
return 0
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ------------------------------------------------------------------ compare / replay
|
|
125
|
+
function compareCli(rec, got, matches, s) {
|
|
126
|
+
if (rec.code !== got.code) return `exit code ${rec.code} vs ${got.code}`
|
|
127
|
+
if (!matches(rec.stdout, got.stdout)) {
|
|
128
|
+
const i = rec.stdout.findIndex((l, k) => !matches(l, got.stdout[k] ?? null))
|
|
129
|
+
return `stdout line ${i + 1}: ${JSON.stringify(rec.stdout[i] ?? '(end)').slice(0, 80)} vs ${JSON.stringify(got.stdout[i] ?? '(end)').slice(0, 80)}`
|
|
130
|
+
}
|
|
131
|
+
if (!s.ignore_stderr && !matches(rec.stderr, got.stderr)) return `stderr differs: ${JSON.stringify(got.stderr.slice(0, 2)).slice(0, 120)}`
|
|
132
|
+
if (!matches(rec.files, got.files)) {
|
|
133
|
+
const want = rec.files.map((f) => `${f.status} ${f.path}`)
|
|
134
|
+
const have = got.files.map((f) => `${f.status} ${f.path}`)
|
|
135
|
+
return canon(want) !== canon(have) ? `files written: expected [${want.join(', ')}], got [${have.join(', ')}]` : `contents of ${rec.files.find((f, k) => !matches(f, got.files[k])).path} differ`
|
|
136
|
+
}
|
|
137
|
+
return null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function config(L) {
|
|
141
|
+
return readJSON(path.join(L.rails, 'config', 'ruby_anything.yml'), null)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function wiredCommand(cfg, args) {
|
|
145
|
+
if (!cfg) return null
|
|
146
|
+
const cmd = args[0]
|
|
147
|
+
const cmds = cfg.commands || []
|
|
148
|
+
return cmds.find((w) => w.command === cmd) || (cmds.find((w) => w.command === '*') && !cmds.some((w) => w.command === cmd) ? cmds.find((w) => w.command === '*') : null)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function fallbackCli(L, cases) {
|
|
152
|
+
const cfg = config(L)
|
|
153
|
+
if (cfg && cfg.lifted) return { fallback: 0, total: cases.length, names: [] }
|
|
154
|
+
const fb = cases.filter((c) => !wiredCommand(cfg, c.input.args))
|
|
155
|
+
return { fallback: fb.length, total: cases.length, names: fb.map((c) => c.name) }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function replayCli(L, a, s, cases, matches) {
|
|
159
|
+
let command
|
|
160
|
+
if (a.original) command = s.original
|
|
161
|
+
else if (a.build) command = String(a.build).split(' ')
|
|
162
|
+
else {
|
|
163
|
+
const script = path.join(L.rails, 'bin', s.cli_name)
|
|
164
|
+
if (!fs.existsSync(script)) throw new Error(`no CLI front door: ruby-anything app front-door ${relTo(process.cwd(), L.root) || '.'}`)
|
|
165
|
+
command = ['ruby', script]
|
|
166
|
+
}
|
|
167
|
+
const env = a.noOriginal ? { RUBY_ANYTHING_NO_FALLBACK: '1' } : {}
|
|
168
|
+
return cases
|
|
169
|
+
.filter((c) => !a.case || c.name.includes(a.case))
|
|
170
|
+
.map((c) => {
|
|
171
|
+
const got = invoke(L.root, command, c.input, env)
|
|
172
|
+
const why = compareCli(c.output, got, matches, s)
|
|
173
|
+
return { name: c.name, ok: !why, why, request: [s.cli_name, ...c.input.args].join(' ') }
|
|
174
|
+
})
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ------------------------------------------------------------------ front door
|
|
178
|
+
const CLI_FRONT_DOOR = (name) => `#!/usr/bin/env ruby
|
|
179
|
+
# frozen_string_literal: true
|
|
180
|
+
|
|
181
|
+
# ruby-anything front door for the ${name} CLI. Commands listed in config/ruby_anything.yml run
|
|
182
|
+
# here, in Ruby (app/cli/<unit>.rb, Cli::<Unit>.call(argv) returning the exit code); every other
|
|
183
|
+
# invocation execs the original. Kill switch: RUBY_ANYTHING_UNIT_<NAME>=original.
|
|
184
|
+
# \`ruby-anything app lift\` sets lifted: true once nothing falls back.
|
|
185
|
+
require "json"
|
|
186
|
+
|
|
187
|
+
ROOT = File.expand_path("..", __dir__)
|
|
188
|
+
cfg = JSON.parse(File.read(File.join(ROOT, "config", "ruby_anything.yml"))) rescue {}
|
|
189
|
+
commands = Array(cfg["commands"])
|
|
190
|
+
entry = commands.find { |c| c["command"] == ARGV.first } ||
|
|
191
|
+
(commands.find { |c| c["command"] == "*" } unless commands.any? { |c| c["command"] == ARGV.first })
|
|
192
|
+
entry = nil if entry && ENV["RUBY_ANYTHING_UNIT_#{entry['unit'].upcase.gsub(/[^A-Z0-9]/, '_')}"] == "original"
|
|
193
|
+
|
|
194
|
+
if entry
|
|
195
|
+
ENV["RAILS_ENV"] ||= "development"
|
|
196
|
+
require File.join(ROOT, "config", "environment")
|
|
197
|
+
unit = entry["unit"].split("_").map(&:capitalize).join
|
|
198
|
+
status = Object.const_get("Cli::#{unit}").call(ARGV.dup)
|
|
199
|
+
$stdout.flush
|
|
200
|
+
exit(status.is_a?(Integer) ? status : 0)
|
|
201
|
+
elsif cfg["lifted"] || ENV["RUBY_ANYTHING_NO_FALLBACK"]
|
|
202
|
+
warn "${name}: unknown command #{ARGV.first.inspect}"
|
|
203
|
+
exit 64
|
|
204
|
+
else
|
|
205
|
+
exec(*Array(cfg["original"]), *ARGV)
|
|
206
|
+
end
|
|
207
|
+
`
|
|
208
|
+
|
|
209
|
+
function frontDoorCli(L, s) {
|
|
210
|
+
const name = s.cli_name || 'app'
|
|
211
|
+
const script = path.join(L.rails, 'bin', name)
|
|
212
|
+
writeFile(script, CLI_FRONT_DOOR(name))
|
|
213
|
+
try {
|
|
214
|
+
fs.chmodSync(script, 0o755)
|
|
215
|
+
} catch {}
|
|
216
|
+
const cfgFile = path.join(L.rails, 'config', 'ruby_anything.yml')
|
|
217
|
+
const cfg = readJSON(cfgFile, null) || { commands: [] }
|
|
218
|
+
cfg.original = s.original
|
|
219
|
+
writeJSON(cfgFile, cfg) // JSON is valid YAML
|
|
220
|
+
writeFile(
|
|
221
|
+
path.join(L.rails, 'app', 'cli', '.keep'),
|
|
222
|
+
'',
|
|
223
|
+
)
|
|
224
|
+
console.log(`CLI front door: ${relTo(process.cwd(), script)} runs wired commands in Ruby and execs the original for the rest.`)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function wireCommand(L, unit, command, remove) {
|
|
228
|
+
const cfgFile = path.join(L.rails, 'config', 'ruby_anything.yml')
|
|
229
|
+
const cfg = readJSON(cfgFile, null)
|
|
230
|
+
if (!cfg) throw new Error(`no CLI front door: ruby-anything app front-door ${relTo(process.cwd(), L.root) || '.'}`)
|
|
231
|
+
cfg.commands = (cfg.commands || []).filter((c) => c.command !== command)
|
|
232
|
+
if (!remove) cfg.commands.push({ command, unit: slug(unit) })
|
|
233
|
+
writeJSON(cfgFile, cfg)
|
|
234
|
+
const klass = camel(slug(unit))
|
|
235
|
+
const file = path.join(L.rails, 'app', 'cli', `${slug(unit)}.rb`)
|
|
236
|
+
if (!remove && !fs.existsSync(file)) {
|
|
237
|
+
writeFile(file, `# frozen_string_literal: true\n\n# \`${command === '*' ? '(default command)' : command}\` of the original CLI. Return the exit code.\nmodule Cli\n class ${klass}\n def self.call(argv)\n raise NotImplementedError, "port the ${command} command"\n end\n end\nend\n`)
|
|
238
|
+
console.log(`created ${relTo(L.root, file)}: Cli::${klass}.call(argv)`)
|
|
239
|
+
}
|
|
240
|
+
return cfg
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function liftCli(L) {
|
|
244
|
+
const cfgFile = path.join(L.rails, 'config', 'ruby_anything.yml')
|
|
245
|
+
const cfg = readJSON(cfgFile, {})
|
|
246
|
+
cfg.lifted = true
|
|
247
|
+
delete cfg.original
|
|
248
|
+
writeJSON(cfgFile, cfg)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
module.exports = { recordCli, replayCli, frontDoorCli, wireCommand, fallbackCli, liftCli, cliCases, compareCli, invoke }
|