ruby-anything 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) 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 +100 -2
  6. package/action.yml +56 -0
  7. package/adapters/node/harness.mjs +348 -0
  8. package/adapters/node/package-lock.json +26 -0
  9. package/adapters/node/package.json +7 -0
  10. package/adapters/polyglot/harness.py +350 -0
  11. package/adapters/polyglot/lang_csharp.py +222 -0
  12. package/adapters/polyglot/lang_go.py +283 -0
  13. package/adapters/polyglot/lang_java.py +510 -0
  14. package/adapters/polyglot/lang_kotlin.py +133 -0
  15. package/adapters/polyglot/lang_php.py +156 -0
  16. package/adapters/polyglot/lang_ruby.py +148 -0
  17. package/adapters/polyglot/lang_rust.py +430 -0
  18. package/adapters/polyglot/lang_swift.py +337 -0
  19. package/adapters/python/harness.py +459 -0
  20. package/bin/ruby-anything.js +10 -0
  21. package/docs/assets/how-it-works-dark.svg +51 -0
  22. package/docs/assets/how-it-works-light.svg +51 -0
  23. package/harness/ruby_replay.rb +155 -0
  24. package/package.json +52 -4
  25. package/skills/ruby-anything/SKILL.md +146 -0
  26. package/skills/ruby-anything/frontend.md +64 -0
  27. package/skills/ruby-anything/languages/csharp.md +43 -0
  28. package/skills/ruby-anything/languages/go.md +36 -0
  29. package/skills/ruby-anything/languages/java.md +54 -0
  30. package/skills/ruby-anything/languages/javascript.md +50 -0
  31. package/skills/ruby-anything/languages/kotlin.md +27 -0
  32. package/skills/ruby-anything/languages/php.md +47 -0
  33. package/skills/ruby-anything/languages/python.md +49 -0
  34. package/skills/ruby-anything/languages/rust.md +31 -0
  35. package/skills/ruby-anything/languages/swift.md +27 -0
  36. package/skills/ruby-anything/whole-app.md +204 -0
  37. package/src/adapters.js +63 -0
  38. package/src/analyze.js +183 -0
  39. package/src/app.js +774 -0
  40. package/src/cli.js +80 -0
  41. package/src/cli_app.js +251 -0
  42. package/src/detect.js +266 -0
  43. package/src/drift.js +124 -0
  44. package/src/effects.js +145 -0
  45. package/src/fromtests.js +105 -0
  46. package/src/go.js +165 -0
  47. package/src/mcp.js +89 -0
  48. package/src/setup.js +106 -0
  49. package/src/units.js +452 -0
  50. package/src/util.js +312 -0
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "ruby-anything",
3
+ "owner": { "name": "PortPilot" },
4
+ "description": "ruby-anything: migrate any app to Ruby on Rails one piece at a time, and prove it still behaves the same.",
5
+ "plugins": [
6
+ {
7
+ "name": "ruby-anything",
8
+ "source": "./",
9
+ "description": "Migrate any app to Rails + Hotwire + Tailwind + daisyUI, checked against the original's recorded behavior. Needs the ruby-anything CLI on PATH (npm i -g ruby-anything)."
10
+ }
11
+ ]
12
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "ruby-anything",
3
+ "version": "0.2.0",
4
+ "description": "Migrate any app to Ruby on Rails 8 with Hotwire, Tailwind and daisyUI, one piece at a time, checked against the original's recorded behavior at every step. Needs the ruby-anything CLI on PATH (npm i -g ruby-anything).",
5
+ "license": "MIT",
6
+ "keywords": ["ruby", "rails", "hotwire", "daisyui", "migration", "mcp"]
7
+ }
package/.mcp.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "ruby-anything": {
4
+ "command": "ruby-anything",
5
+ "args": ["mcp"]
6
+ }
7
+ }
8
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Akshay
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">Ruby Anything</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/ruby-anything"><img src="https://img.shields.io/npm/v/ruby-anything?style=flat&colorA=111111&colorB=a51c1c&label=npm" alt="npm version"></a>
5
+ <a href="https://www.npmjs.com/package/ruby-anything"><img src="https://img.shields.io/npm/d18m/ruby-anything?style=flat&colorA=111111&colorB=a51c1c&label=npm%20downloads" alt="npm downloads"></a>
6
+ <a href="#license"><img src="https://img.shields.io/badge/license-MIT-111111?style=flat&colorA=111111&colorB=a51c1c" alt="MIT license"></a>
7
+ </p>
8
+
9
+ <p align="center">
10
+ Migrate your app to Ruby on Rails, and prove it still behaves the same.
11
+ </p>
12
+
13
+ <p align="center">
14
+ Rails 8 · Hotwire (Turbo + Stimulus) · Tailwind CSS · daisyUI<br>
15
+ from TypeScript, JavaScript, Python, Go, Java/Spring Boot, Kotlin, C#, PHP, Rust and Swift
16
+ </p>
17
+
18
+ ## Quick start
19
+
20
+ Paste this into your coding agent:
21
+
22
+ ```text
23
+ Install Ruby Anything with npm i -g ruby-anything, then run ruby-anything setup. Run ruby-anything go -- <command that starts this app> and finish the port until ruby-anything gate --app passes.
24
+ ```
25
+
26
+ Or install it yourself:
27
+
28
+ ```sh
29
+ npm install -g ruby-anything
30
+ ruby-anything setup # adds it to Claude Code, Codex, Cursor, Gemini CLI and OpenCode
31
+ ruby-anything doctor # checks Ruby, Rails and the runtimes your original needs
32
+ ```
33
+
34
+ > [!WARNING]
35
+ > Recording runs the original's real code. Work on a copy, with a test database (`--db-reset "<command>"`).
36
+
37
+ ## How it works
38
+
39
+ <p align="center">
40
+ <picture>
41
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/how-it-works-dark.svg">
42
+ <img src="docs/assets/how-it-works-light.svg" width="880" alt="analyze plans the migration; the user settles the decisions; app record captures the original's HTTP behavior; the front door puts Rails in front of the original and proxies what is not ported yet; each route is bridged, recorded, ported by your agent, diffed and gated until nothing falls back; lift leaves a pure Rails app">
43
+ </picture>
44
+ </p>
45
+
46
+ **What counts as done.** Behavior, not your tests. `record` runs the original on generated and given inputs and saves what each call returns, raises and prints; `app record` saves what each HTTP request answers (status, redirects, JSON, page text), running every request twice so changing values become wildcards. A piece is done when `gate` passes: every recorded case matches, and the checks for edited recordings, stubs, recorded answers pasted into the port, unrecorded error paths, fewer tests than before, rubocop and brakeman all pass. Your own `bin/rails test` runs too.
47
+
48
+ **Your tests become cases.** `record --from-tests -- pytest` (or `npx jest`, `node --test`) runs the original's own suite with the function instrumented, and every call it makes becomes a recorded case. The source is restored byte for byte afterwards. `--pin-clock` freezes time at 2026-01-01 for the original and the Ruby port alike, so date-dependent code can match.
49
+
50
+ **Side effects count.** A port that forgets to charge the card or send the receipt must fail. `app record --effect-env PAYMENT_API_URL=http,SMTP_HOST=smtp_host,SMTP_PORT=smtp_port --db-dump "<cmd>"` points the app at local stand-ins that record every outgoing HTTP call and email, and dumps the database after every write; replay checks the Rails app makes the same calls, sends the same mail and leaves the same rows.
51
+
52
+ **Web apps and CLI tools.** `app record --http` records a server; `app record --cli --inputs cli.jsonl` records a command-line tool (exit code, stdout, stderr, files written, stdin), each run in a throwaway copy of the repo. A CLI's front door is `rails/bin/<name>`: ported commands run in Rails, the rest exec the original.
53
+
54
+ **The app keeps running.** `app front-door` runs `rails new` with Tailwind and importmap, adds daisyUI, and puts a small Rack middleware in front that proxies every route Rails does not own yet to the original. Routes move over one at a time with `app wire`, each with a kill switch (`RUBY_ANYTHING_UNIT_<NAME>=original`). `app replay` must stay at 100% while the fallback rate drops to zero; then `app lift` removes the proxy.
55
+
56
+ **The original keeps changing?** `ruby-anything drift` re-runs the original on every recorded case and lists what now answers differently, plus routes no case records. CI runs the tests on Linux, Windows and macOS, and the bundled GitHub Action runs `gate` on every pull request.
57
+
58
+ **A new frontend, the same pages.** Pages are rebuilt as ERB views with Turbo Frames and Streams, Stimulus controllers and daisyUI components. Replay compares them by visible text, so the markup is new but every heading, label, price and empty state must still be there. JSON responses must match exactly.
59
+
60
+ **Report or migrate, you pick.** `analyze` only reports: languages, frameworks, routes, templates and functions in waves (models, logic, routes, views, jobs), every dependency with its Rails equivalent, and the decisions to settle with you. It is a plain command, so the report costs no tokens. `go` migrates: each run moves to the next stage and writes the next task to `rails/port/TASK.md` for your agent.
61
+
62
+ **Your agent writes the Ruby; you make the calls.** The agent skill grills you on the decisions (database, auth, equivalence bar, cut-over) and writes them down as ADRs, stops at the checkpoints you choose, and stops to ask when three attempts gain no matching case. Corrections you make become rules every later piece keeps (`ruby-anything rules --add`).
63
+
64
+ **Agents.** `ruby-anything setup` adds the skill and the MCP server to Claude Code, Codex, Cursor, Gemini CLI and OpenCode. Any other MCP client can run `ruby-anything mcp`. As a Claude Code plugin: `claude plugin marketplace add <this repo>`, then `claude plugin install ruby-anything@ruby-anything`.
65
+
66
+ Everything it writes lives in `<repo>/rails/`: the Rails app, and `rails/port/` with the plan, decisions, glossary, rules, recorded cases and the port map.
67
+
68
+ ## Commands
69
+
70
+ | Command | What it does |
71
+ |---|---|
72
+ | `ruby-anything go [-- <start command>]` | Move the migration to its next stage and write `rails/port/TASK.md` |
73
+ | `ruby-anything analyze <repo>` | Plan: routes, templates, functions in waves, dependencies, decisions |
74
+ | `ruby-anything bridge <repo> <unit>` | Ruby skeleton for one function in `app/services` |
75
+ | `ruby-anything record <repo> <unit>` | Record the original function on edge cases, `--inputs`, `--from-tests -- <test cmd>`, `--pin-clock` |
76
+ | `ruby-anything diff <repo> <unit>` | Replay the cases against the Ruby port (must be N/N) |
77
+ | `ruby-anything gate <repo> <unit> \| --all \| --app` | Done means gate passes |
78
+ | `ruby-anything rules <repo> [--add "<rule>"]` | Behavior you corrected, kept by every later piece |
79
+ | `ruby-anything drift <repo>` | Has the original changed since it was recorded? |
80
+ | `ruby-anything app record <repo> --http -- <start command>` | Record the whole original over HTTP (`--effect-env`, `--db-dump` for side effects) |
81
+ | `ruby-anything app record <repo> --cli --inputs cli.jsonl -- <command>` | Record a CLI tool |
82
+ | `ruby-anything app front-door <repo>` | Rails app that proxies routes not ported yet |
83
+ | `ruby-anything app wire <repo> <unit> --route "GET /path/:id"` | Hand a route to Rails (`--command <name>` for a CLI) |
84
+ | `ruby-anything app replay <repo>` | Replay every HTTP case through Rails (`--original`, `--case`) |
85
+ | `ruby-anything app status <repo>` | Fallback rate, wired routes, units done |
86
+ | `ruby-anything app lift <repo>` | Remove the proxy once nothing falls back |
87
+ | `ruby-anything setup \| doctor \| mcp` | Install for agents, check runtimes, MCP server |
88
+
89
+ ## In CI
90
+
91
+ ```yaml
92
+ - uses: akkisavi/ruby-anything/packages/ruby-anything@master
93
+ with:
94
+ app: "true" # also bin/rails test, rubocop, brakeman and the full replay
95
+ ```
96
+
97
+ ## License
98
+
99
+ Licensed under [MIT](./LICENSE). Ports and generated code in your repository are yours.
100
+
101
+ Inspired by [rust-anything](https://github.com/erkamyaman/rust-anything) by Erkam Yaman, which does the same for Rust. The recorders are PortPilot's language adapters.
package/action.yml ADDED
@@ -0,0 +1,56 @@
1
+ name: ruby-anything gate
2
+ description: Fail the pull request unless every ruby-anything port still matches the original's recorded behavior.
3
+ branding:
4
+ icon: check-circle
5
+ color: red
6
+
7
+ inputs:
8
+ path:
9
+ description: Repository being migrated (the folder that contains rails/).
10
+ default: "."
11
+ units:
12
+ description: Unit ids to gate, one per line. Empty gates every bridged unit (gate --all).
13
+ default: ""
14
+ app:
15
+ description: Also run the whole-app gate (bin/rails test, rubocop, brakeman, HTTP replay).
16
+ default: "false"
17
+ version:
18
+ description: ruby-anything version from npm.
19
+ default: latest
20
+ no-lint:
21
+ description: Skip rubocop in the unit gate.
22
+ default: "false"
23
+
24
+ runs:
25
+ using: composite
26
+ steps:
27
+ - name: Install ruby-anything
28
+ shell: bash
29
+ run: npm install -g "ruby-anything@${{ inputs.version }}"
30
+ - name: Check runtimes
31
+ shell: bash
32
+ run: ruby-anything doctor || true
33
+ - name: Gate units
34
+ shell: bash
35
+ working-directory: ${{ inputs.path }}
36
+ env:
37
+ UNITS: ${{ inputs.units }}
38
+ NO_LINT: ${{ inputs.no-lint }}
39
+ run: |
40
+ flags=()
41
+ [ "$NO_LINT" = "true" ] && flags+=(--no-lint)
42
+ if [ -z "$UNITS" ]; then
43
+ ruby-anything gate . --all "${flags[@]}"
44
+ else
45
+ status=0
46
+ while IFS= read -r unit; do
47
+ [ -z "$unit" ] && continue
48
+ ruby-anything gate . "$unit" "${flags[@]}" || status=1
49
+ done <<< "$UNITS"
50
+ exit $status
51
+ fi
52
+ - name: Gate the app
53
+ if: inputs.app == 'true'
54
+ shell: bash
55
+ working-directory: ${{ inputs.path }}
56
+ run: ruby-anything gate . --app
@@ -0,0 +1,348 @@
1
+ // PortPilot JavaScript/TypeScript adapter (Node >= 22, TypeScript via built-in type stripping).
2
+ //
3
+ // Runs INSIDE the sandbox only. One JSON request on stdin, JSON lines on stdout:
4
+ // analyze - imports each module (top-level code runs here, inside the sandbox) and inspects
5
+ // its exported functions: params, source, throw sites, calls, side-effect hints
6
+ // record - calls an exported function per case (twice), captures behaviour
7
+ // bench - times each case over N iterations inside this process
8
+ // Protocol: docs/ADDING_A_LANGUAGE.md. Values use the shared tagged encoding.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import crypto from 'node:crypto';
13
+ import { pathToFileURL } from 'node:url';
14
+
15
+ const SRC = process.env.PORTPILOT_SRC || '/work/src';
16
+ const realWrite = process.stdout.write.bind(process.stdout);
17
+ const emit = (event, data = {}) => realWrite(JSON.stringify({ ...data, event }) + '\n');
18
+
19
+ // ------------------------------------------------------------------ value codec
20
+ function encode(v) {
21
+ if (v === null || v === undefined) return null;
22
+ if (typeof v === 'boolean' || typeof v === 'string') return v;
23
+ if (typeof v === 'bigint') return Number.isSafeInteger(Number(v)) ? Number(v) : { $repr: v.toString() + 'n' };
24
+ if (typeof v === 'number') {
25
+ if (Number.isNaN(v)) return { $float: 'nan' };
26
+ if (v === Infinity) return { $float: 'inf' };
27
+ if (v === -Infinity) return { $float: '-inf' };
28
+ if (Object.is(v, -0)) return { $float: '-0.0' };
29
+ if (Number.isInteger(v) && !Number.isSafeInteger(v)) return { $float: String(v) }; // a double, not an exact integer
30
+ return v; // JS has one number type: integral values encode as ints, others as floats
31
+ }
32
+ if (Array.isArray(v)) return v.map(encode);
33
+ if (v instanceof Set) return { $set: [...v].map(encode).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) };
34
+ if (v instanceof Map) return Object.fromEntries([...v].map(([k, x]) => [String(k), encode(x)]));
35
+ if (v instanceof Date) return { $repr: 'Date(' + v.toISOString() + ')' };
36
+ if (Buffer.isBuffer(v) || v instanceof Uint8Array) return { $bytes: Buffer.from(v).toString('base64') };
37
+ if (typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, encode(x)]));
38
+ return { $repr: String(v).slice(0, 200) };
39
+ }
40
+ function decode(v) {
41
+ if (Array.isArray(v)) return v.map(decode);
42
+ if (v && typeof v === 'object') {
43
+ if ('$float' in v) return { nan: NaN, inf: Infinity, '-inf': -Infinity, '-0.0': -0 }[v.$float] ?? Number(v.$float);
44
+ if ('$bytes' in v) return Buffer.from(v.$bytes, 'base64');
45
+ if ('$set' in v) return new Set(v.$set.map(decode));
46
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, decode(x)]));
47
+ }
48
+ return v;
49
+ }
50
+
51
+ // ------------------------------------------------------------------ module loading
52
+ const EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts']);
53
+ const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'out', 'coverage', '.next', 'vendor']);
54
+ function walk(dir, out = []) {
55
+ for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
56
+ if (e.isSymbolicLink()) continue;
57
+ const full = path.join(dir, e.name);
58
+ if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(full, out); }
59
+ else if (EXTS.has(path.extname(e.name)) && !/\.(test|spec|d)\.[cm]?[jt]s$/.test(e.name)) out.push(full);
60
+ }
61
+ return out;
62
+ }
63
+ function insideSrc(file) {
64
+ const real = fs.realpathSync(path.resolve(SRC, file));
65
+ if (!real.startsWith(fs.realpathSync(SRC) + path.sep)) throw new Error('module_file escapes the source root');
66
+ return real;
67
+ }
68
+ // TypeScript: transpile the whole source tree once into a /tmp mirror (types removed, inline
69
+ // source maps so stack traces and throw lines point at the original .ts lines), then import from there.
70
+ let tsMirror = null;
71
+ async function mirrorFor(file) {
72
+ if (!/\.m?ts$/.test(file)) return file;
73
+ if (!tsMirror) {
74
+ const ts = (await import('./node_modules/typescript/lib/typescript.js')).default;
75
+ tsMirror = fs.mkdtempSync(path.join(os.tmpdir(), 'pp-ts-'));
76
+ fs.writeFileSync(path.join(tsMirror, 'package.json'), '{"type":"module"}');
77
+ for (const src of walk(SRC)) {
78
+ const rel = path.relative(SRC, src);
79
+ const out = path.join(tsMirror, rel.replace(/\.m?ts$/, '.js'));
80
+ fs.mkdirSync(path.dirname(out), { recursive: true });
81
+ const code = fs.readFileSync(src, 'utf8');
82
+ const js = /\.m?ts$/.test(src)
83
+ ? ts.transpileModule(code, { fileName: src, compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, inlineSourceMap: true, inlineSources: true, rewriteRelativeImportExtensions: true } }).outputText
84
+ : code;
85
+ fs.writeFileSync(out, js);
86
+ }
87
+ }
88
+ return path.join(tsMirror, path.relative(SRC, file).replace(/\.m?ts$/, '.js'));
89
+ }
90
+ async function loadModule(file) {
91
+ file = await mirrorFor(file);
92
+ const silent = () => true;
93
+ const restore = { log: console.log, warn: console.warn, error: console.error, info: console.info, w: process.stdout.write };
94
+ console.log = console.warn = console.error = console.info = () => {}; process.stdout.write = silent;
95
+ try {
96
+ const mod = await import(pathToFileURL(file).href);
97
+ const ns = {};
98
+ if (mod.default && typeof mod.default === 'object') Object.assign(ns, mod.default); // CommonJS module.exports
99
+ for (const [k, v] of Object.entries(mod)) if (k !== 'default') ns[k] = v;
100
+ if (typeof mod.default === 'function' && !ns[mod.default.name || 'default']) ns[mod.default.name || 'default'] = mod.default;
101
+ return ns;
102
+ } finally {
103
+ Object.assign(console, { log: restore.log, warn: restore.warn, error: restore.error, info: restore.info });
104
+ process.stdout.write = restore.w;
105
+ }
106
+ }
107
+
108
+ // ------------------------------------------------------------------ analyze
109
+ const EFFECTS = [
110
+ ['filesystem', /\bfs\.|\bwriteFile|\breadFile|\bmkdir|\bunlink\(/],
111
+ ['network', /\bfetch\(|\bhttps?\.(request|get)\(|\baxios\b|\bnew WebSocket\(|\bnet\.connect/],
112
+ ['database', /\b(prisma|knex|sequelize|mongoose|pg|mysql2?)\./],
113
+ ['process', /\bchild_process\b|\bexecSync\(|\bspawn\(|\bexec\(/],
114
+ ['stdout', /\bconsole\.(log|info|warn|error)\(|process\.stdout\.write/],
115
+ ['nondeterminism', /\bDate\.now\(|\bnew Date\(\)|\bMath\.random\(|\bcrypto\.random/],
116
+ ['environment', /\bprocess\.env\b/],
117
+ ];
118
+ function paramsOf(fnSource) {
119
+ const m = fnSource.match(/^[^(]*\(([^)]*)\)/s) || fnSource.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/);
120
+ if (!m) return [];
121
+ const list = m[1].split(',').map(p => p.trim()).filter(Boolean);
122
+ return list.map(p => {
123
+ const rest = p.startsWith('...');
124
+ const [left, def] = p.replace(/^\.\.\./, '').split('=').map(s => s.trim());
125
+ const [name, ann] = left.split(':').map(s => s && s.trim());
126
+ return { name: name.replace(/\?$/, ''), annotation: ann || null, default: def ?? null, kind: rest ? 'varargs' : 'positional' };
127
+ });
128
+ }
129
+ function analyze() {
130
+ const files = walk(SRC);
131
+ emit('log', { message: `found ${files.length} JS/TS files` });
132
+ return (async () => {
133
+ for (const full of files) {
134
+ const rel = path.relative(SRC, full).split(path.sep).join('/');
135
+ const raw = fs.readFileSync(full, 'utf8');
136
+ const isTs = /\.m?ts$/.test(full);
137
+ const imports = [...raw.matchAll(/(?:import\s[^'"]*from\s*|require\()\s*['"]([^'"]+)['"]/g)].map(m => m[1]);
138
+ const external = [...new Set(imports.filter(i => !i.startsWith('.') && !i.startsWith('node:')).map(i => i.startsWith('@') ? i.split('/').slice(0, 2).join('/') : i.split('/')[0]))];
139
+ emit('file', { path: rel, module: rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.'), loc: raw.split('\n').length, imports: [...new Set(imports)], external, classes: [], digest: 'sha256:' + crypto.createHash('sha256').update(raw).digest('hex') });
140
+ let ns;
141
+ try { ns = await loadModule(full); } catch (e) { emit('log', { message: `${rel}: could not import (${e.name}: ${e.message})` }); continue; }
142
+ const names = Object.keys(ns).filter(k => typeof ns[k] === 'function' && !/^class\s/.test(Function.prototype.toString.call(ns[k])));
143
+ for (const name of names) {
144
+ const compiled = Function.prototype.toString.call(ns[name]);
145
+ // Prefer the original (typed) text from the file; fall back to the compiled function text.
146
+ const head = compiled.slice(0, compiled.indexOf('{') > 0 ? compiled.indexOf('{') : 40).split('(')[0].trim();
147
+ const startIdx = locate(raw, name, isTs);
148
+ const original = startIdx >= 0 ? sliceFunction(raw, startIdx) : compiled;
149
+ const lineStart = startIdx >= 0 ? raw.slice(0, startIdx).split('\n').length : null;
150
+ const lineEnd = lineStart ? lineStart + original.split('\n').length - 1 : null;
151
+ const body = original;
152
+ const calls = [...new Set([...body.matchAll(/([A-Za-z_$][\w$.]*)\s*\(/g)].map(m => m[1]).filter(c => !['if', 'for', 'while', 'switch', 'catch', 'function', 'return', name].includes(c)))].sort();
153
+ const effects = EFFECTS.filter(([, re]) => re.test(body)).map(([k]) => k);
154
+ const throwLines = [];
155
+ if (lineStart) body.split('\n').forEach((l, i) => { if (/\bthrow\b/.test(l)) throwLines.push(lineStart + i); });
156
+ const complexity = 1 + (body.match(/\b(if|for|while|case|catch)\b|\?\s|&&|\|\|/g) || []).length;
157
+ const depth = (body.match(/\b(for|while)\b[^{]*\{[^}]*\b(for|while)\b/s) ? 2 : 1);
158
+ emit('unit', {
159
+ file: rel, module: rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.'), name, owner: null,
160
+ qualified_name: `${rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.')}.${name}`, kind: 'function',
161
+ is_async: /^async\b/.test(head) || /^\s*export\s+async/.test(original), line_start: lineStart, line_end: lineEnd,
162
+ params: paramsOf(original.replace(/^\s*export\s+(default\s+)?/, '').replace(/^(async\s+)?function\s*\*?\s*[\w$]*/, '')),
163
+ returns: (original.match(/\)\s*:\s*([^{=]+?)\s*(\{|=>)/) || [])[1] || null, docstring: docComment(raw, startIdx),
164
+ source: original, digest: 'sha256:' + crypto.createHash('sha256').update(original).digest('hex'),
165
+ calls, internal_deps: calls.filter(c => names.includes(c) && c !== name), side_effects: effects,
166
+ complexity, loop_depth: depth, perf_hints: depth >= 2 ? [`nested loops (depth ${depth}): possible O(n^${depth}) path - static hint, not measured`] : [],
167
+ raise_lines: throwLines, loc: original.split('\n').length,
168
+ });
169
+ }
170
+ }
171
+ emit('done');
172
+ })();
173
+ }
174
+ function locate(raw, name, isTs) {
175
+ const pats = [new RegExp(`(^|\\n)[ \\t]*(export\\s+)?(async\\s+)?function\\s*\\*?\\s*${name}\\s*[(<]`), new RegExp(`(^|\\n)[ \\t]*(export\\s+)?(const|let|var)\\s+${name}\\s*(:[^=]+)?=`),
176
+ new RegExp(`(^|\\n)[ \\t]*(exports|module\\.exports)\\.${name}\\s*=`)];
177
+ for (const p of pats) { const m = p.exec(raw); if (m) return m.index + (m[1] ? m[1].length : 0); }
178
+ return -1;
179
+ }
180
+ function sliceFunction(raw, start) {
181
+ const open = raw.indexOf('{', start); const arrow = raw.indexOf('=>', start);
182
+ // Arrow with an expression body (no block right after =>): the function ends at the line end.
183
+ if (open < 0 || (arrow >= 0 && arrow < open && raw.slice(arrow + 2, open).trim() !== '')) {
184
+ const end = raw.indexOf('\n', arrow >= 0 ? arrow : start);
185
+ return raw.slice(start, end < 0 ? raw.length : end).trimEnd();
186
+ }
187
+ let depth = 0; let i = open; let q = null;
188
+ for (; i < raw.length; i++) {
189
+ const c = raw[i];
190
+ if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
191
+ if (c === '"' || c === "'" || c === '`') q = c;
192
+ else if (c === '{') depth++;
193
+ else if (c === '}' && --depth === 0) break;
194
+ }
195
+ return raw.slice(start, i + 1);
196
+ }
197
+ function docComment(raw, start) {
198
+ if (start <= 0) return null;
199
+ const before = raw.slice(0, start);
200
+ const open = before.lastIndexOf('/**');
201
+ const close = before.lastIndexOf('*/');
202
+ if (open < 0 || close < open || before.slice(close + 2).trim() !== '') return null;
203
+ return before.slice(open + 3, close).replace(/^\s*\* ?/gm, '').trim();
204
+ }
205
+
206
+ // ------------------------------------------------------------------ input generation
207
+ const POOLS = {
208
+ string: ['', ' ', 'a', 'Hello World', ' multiple spaces ', 'UPPER lower', 'ünïcödé café', 'emoji 😀 here', '-0', '42', 'x'.repeat(300), '!!!'],
209
+ number: [0, 1, -1, 2, 7, 0.5, -2.25, 255, 2 ** 31 - 1, -(2 ** 31), Number.MAX_SAFE_INTEGER, { $float: 'nan' }, { $float: 'inf' }, { $float: '-0.0' }],
210
+ boolean: [true, false],
211
+ array: [[], [1], [1, 2, 3], [-1.5, 2.5], ['apple', 'avocado', 'banana']],
212
+ matrix: [[], [[1, 250]], [[2, 1999], [1, 5]], [[0, 100]], [[-1, 5]], [[3, 0.5]], [[1, 1], [2, 2], [3, 3]]],
213
+ any: ['', 'a', 0, 1, -1, null, [], [1, 2], { a: 1 }, true],
214
+ };
215
+ const poolFor = ann => !ann ? POOLS.any : /\[\]\[\]/.test(ann) ? POOLS.matrix : /\[\]|Array/.test(ann) ? POOLS.array : /string/.test(ann) ? POOLS.string : /number|bigint/.test(ann) ? POOLS.number : /boolean/.test(ann) ? POOLS.boolean : POOLS.any;
216
+ function rng(seed) { let s = (seed >>> 0) || 1; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
217
+ function randomValue(r, ann) {
218
+ const k = !ann ? ['string', 'number', 'any'][Math.floor(r() * 3)] : /\[\]\[\]/.test(ann) ? 'matrix' : /\[\]|Array/.test(ann) ? 'array' : /string/.test(ann) ? 'string' : /number/.test(ann) ? 'number' : /boolean/.test(ann) ? 'boolean' : /\[\]|Array/.test(ann) ? 'array' : 'any';
219
+ if (k === 'string') { const a = 'abcXYZ019 -_.,!é😀\t'; const ch = [...a]; return Array.from({ length: Math.floor(r() * 24) }, () => ch[Math.floor(r() * ch.length)]).join(''); }
220
+ if (k === 'number') return r() < 0.5 ? Math.floor(r() * 21) - 10 : Math.round((r() * 2e6 - 1e6) * 100) / 100;
221
+ if (k === 'boolean') return r() < 0.5;
222
+ if (k === 'matrix') return Array.from({ length: Math.floor(r() * 4) }, () => [Math.floor(r() * 7) - 1, Math.floor(r() * 5000)]);
223
+ if (k === 'array') return Array.from({ length: Math.floor(r() * 6) }, () => Math.floor(r() * 101) - 50);
224
+ return [null, 1, 's'][Math.floor(r() * 3)];
225
+ }
226
+ function generate(params, count, seed, mode) {
227
+ const r = rng(seed); const seen = new Set(); const out = [];
228
+ const req = params.filter(p => p.kind === 'positional');
229
+ for (let n = 0; out.length < count && n < count * 20; n++) {
230
+ const args = [];
231
+ for (const [i, p] of req.entries()) {
232
+ if (p.default !== null && r() < 0.5) break;
233
+ if (mode === 'fuzz') args.push(randomValue(r, p.annotation));
234
+ else { const pool = poolFor(p.annotation); args.push(i === 0 && out.length < pool.length ? pool[out.length % pool.length] : pool[Math.floor(r() * pool.length)]); }
235
+ }
236
+ const key = JSON.stringify(args);
237
+ if (seen.has(key)) continue;
238
+ seen.add(key); out.push({ args: encode(decode(args)), kwargs: {}, origin: mode === 'fuzz' ? 'fuzz' : 'generated' });
239
+ }
240
+ return out;
241
+ }
242
+
243
+ // ------------------------------------------------------------------ record / bench
244
+ function snapshot(root) {
245
+ const out = [];
246
+ (function rec(d) {
247
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
248
+ const f = path.join(d, e.name);
249
+ if (e.isDirectory()) rec(f);
250
+ else if (e.isFile()) { const data = fs.readFileSync(f); out.push({ path: path.relative(root, f).split(path.sep).join('/'), size: data.length, sha256: crypto.createHash('sha256').update(data).digest('hex') }); }
251
+ }
252
+ })(root);
253
+ return out.sort((a, b) => a.path.localeCompare(b.path));
254
+ }
255
+ function throwLine(err, file) {
256
+ const lines = String(err && err.stack || '').split('\n');
257
+ for (const l of lines) { const m = l.match(/\((?:file:\/\/)?(.*?):(\d+):\d+\)$/) || l.match(/at (?:file:\/\/)?(.*?):(\d+):\d+$/); if (m && m[1].endsWith(path.basename(file))) return Number(m[2]); }
258
+ return null;
259
+ }
260
+ async function runCase(fn, file, c) {
261
+ const args = decode(c.args || []);
262
+ let out = '', err = '';
263
+ const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error, ow: process.stdout.write, ew: process.stderr.write };
264
+ console.log = console.info = (...a) => { out += a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\n'; };
265
+ console.warn = console.error = (...a) => { err += a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\n'; };
266
+ process.stdout.write = s => { out += s; return true; }; process.stderr.write = s => { err += s; return true; };
267
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'pp-case-')); const cwd = process.cwd(); process.chdir(scratch);
268
+ const t0 = process.hrtime.bigint(); let outcome;
269
+ try { outcome = { kind: 'return', value: encode(await fn(...args)) }; }
270
+ catch (e) {
271
+ outcome = { kind: 'raise', type: (e && e.constructor && e.constructor.name) || typeof e, message: String(e && e.message !== undefined ? e.message : e) };
272
+ const line = throwLine(e, file); if (line) outcome.raise_line = line;
273
+ } finally {
274
+ Object.assign(console, { log: saved.log, info: saved.info, warn: saved.warn, error: saved.error });
275
+ process.stdout.write = saved.ow; process.stderr.write = saved.ew;
276
+ }
277
+ const duration_us = Number((process.hrtime.bigint() - t0) / 1000n);
278
+ const effects = snapshot(scratch); process.chdir(cwd); fs.rmSync(scratch, { recursive: true, force: true });
279
+ return { outcome, stdout: out, stderr: err, effects, duration_us };
280
+ }
281
+ async function target(req) {
282
+ const file = insideSrc(req.module_file);
283
+ const ns = await loadModule(file);
284
+ const fn = ns[req.function];
285
+ if (typeof fn !== 'function') { emit('fatal', { message: `${req.function} is not an exported function of ${req.module_file}` }); process.exit(2); }
286
+ return { fn, file };
287
+ }
288
+ // Opt-in (req.pin_clock): the clock reads 2026-01-01T00:00:00Z and Math.random restarts from seed 0
289
+ // before every run, so time- and random-dependent results are reproducible.
290
+ const PIN_MS = 1767225600000;
291
+ let rngState = 0;
292
+ function reseed() { rngState = 0; }
293
+ function pinClock() {
294
+ const RealDate = Date;
295
+ class PinnedDate extends RealDate {
296
+ constructor(...a) { if (a.length === 0) super(PIN_MS); else super(...a); }
297
+ static now() { return PIN_MS; }
298
+ }
299
+ globalThis.Date = PinnedDate;
300
+ Math.random = () => { // mulberry32
301
+ rngState = (rngState + 0x6D2B79F5) | 0;
302
+ let t = Math.imul(rngState ^ (rngState >>> 15), 1 | rngState);
303
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
304
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
305
+ };
306
+ }
307
+ async function record(req) {
308
+ const pinned = !!req.pin_clock;
309
+ if (pinned) pinClock();
310
+ const { fn, file } = await target(req);
311
+ const raw = fs.readFileSync(file, 'utf8'); const start = locate(raw, req.function, /ts$/.test(file));
312
+ const params = paramsOf((start >= 0 ? sliceFunction(raw, start) : Function.prototype.toString.call(fn)).replace(/^\s*export\s+(default\s+)?/, '').replace(/^(async\s+)?function\s*\*?\s*[\w$]*/, ''));
313
+ const cases = [...(req.cases || [])];
314
+ const g = req.generate || {};
315
+ if (g.count) cases.push(...generate(params, Number(g.count), Number(g.seed || 0), g.mode || 'edge'));
316
+ emit('log', { message: `recording ${cases.length} cases for ${req.function} (node ${process.versions.node})` });
317
+ emit('plan', { total: cases.length, runtime: `node ${process.versions.node}` });
318
+ const obs = r => JSON.stringify([r.outcome, r.stdout, r.stderr, r.effects]);
319
+ for (const [index, c] of cases.entries()) {
320
+ if (pinned) reseed();
321
+ const first = await runCase(fn, file, c);
322
+ if (pinned) reseed();
323
+ const second = await runCase(fn, file, c);
324
+ emit('case', { index, ref: c.ref ?? null, origin: c.origin || 'manual', args: c.args || [], kwargs: c.kwargs || {}, stable: obs(first) === obs(second), ...first });
325
+ }
326
+ emit('done');
327
+ }
328
+ async function bench(req) {
329
+ const { fn } = await target(req);
330
+ const iterations = Math.max(1, Math.min(Number(req.iterations || 30), 10000));
331
+ emit('plan', { total: req.cases.length, runtime: `node ${process.versions.node}` });
332
+ const saved = console.log; console.log = () => {};
333
+ for (const c of req.cases) {
334
+ const args = decode(c.args || []); const samples = [];
335
+ for (let i = 0; i < iterations; i++) { const t0 = process.hrtime.bigint(); try { await fn(...args); } catch { /* timed too */ } samples.push(Number(process.hrtime.bigint() - t0)); }
336
+ emit('case', { ref: c.ref ?? null, samples_ns: samples, peak_memory_bytes: null });
337
+ }
338
+ console.log = saved;
339
+ emit('done');
340
+ }
341
+
342
+ let input = '';
343
+ process.stdin.setEncoding('utf8');
344
+ for await (const chunk of process.stdin) input += chunk;
345
+ const req = JSON.parse(input || '{}');
346
+ const handlers = { analyze, record, bench };
347
+ if (!handlers[req.command]) { emit('fatal', { message: `unknown command ${req.command}` }); process.exit(2); }
348
+ await handlers[req.command](req);
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "portpilot-node-adapter",
3
+ "lockfileVersion": 3,
4
+ "requires": true,
5
+ "packages": {
6
+ "": {
7
+ "name": "portpilot-node-adapter",
8
+ "dependencies": {
9
+ "typescript": "5.9.3"
10
+ }
11
+ },
12
+ "node_modules/typescript": {
13
+ "version": "5.9.3",
14
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
15
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
16
+ "license": "Apache-2.0",
17
+ "bin": {
18
+ "tsc": "bin/tsc",
19
+ "tsserver": "bin/tsserver"
20
+ },
21
+ "engines": {
22
+ "node": ">=14.17"
23
+ }
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "portpilot-node-adapter",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "Sandbox-side JS/TS adapter. TypeScript is transpiled with the official compiler before import.",
6
+ "dependencies": { "typescript": "5.9.3" }
7
+ }