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