ruby-anything 0.2.1 → 0.2.3
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 +3 -2
- package/README.md +27 -2
- package/adapters/node/harness.mjs +350 -350
- 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_go.py +283 -283
- package/adapters/polyglot/lang_java.py +510 -510
- package/adapters/polyglot/lang_kotlin.py +133 -133
- package/adapters/polyglot/lang_php.py +156 -156
- package/adapters/polyglot/lang_ruby.py +148 -148
- package/adapters/polyglot/lang_rust.py +430 -430
- package/adapters/polyglot/lang_swift.py +337 -337
- package/adapters/python/harness.py +459 -459
- package/docs/assets/logo.png +0 -0
- package/docs/test-results.md +102 -0
- package/package.json +6 -3
- package/skills/ruby-anything/SKILL.md +74 -1
- package/src/adapters.js +63 -60
- package/src/cli.js +3 -0
- package/src/mcp.js +2 -1
- package/src/setup.js +32 -7
- package/src/status.js +77 -0
- package/adapters/ruby/harness.rb +0 -134
|
@@ -1,350 +1,350 @@
|
|
|
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
|
-
import { createRequire } from 'node:module';
|
|
15
|
-
|
|
16
|
-
const SRC = process.env.PORTPILOT_SRC || '/work/src';
|
|
17
|
-
const realWrite = process.stdout.write.bind(process.stdout);
|
|
18
|
-
const emit = (event, data = {}) => realWrite(JSON.stringify({ ...data, event }) + '\n');
|
|
19
|
-
|
|
20
|
-
// ------------------------------------------------------------------ value codec
|
|
21
|
-
function encode(v) {
|
|
22
|
-
if (v === null || v === undefined) return null;
|
|
23
|
-
if (typeof v === 'boolean' || typeof v === 'string') return v;
|
|
24
|
-
if (typeof v === 'bigint') return Number.isSafeInteger(Number(v)) ? Number(v) : { $repr: v.toString() + 'n' };
|
|
25
|
-
if (typeof v === 'number') {
|
|
26
|
-
if (Number.isNaN(v)) return { $float: 'nan' };
|
|
27
|
-
if (v === Infinity) return { $float: 'inf' };
|
|
28
|
-
if (v === -Infinity) return { $float: '-inf' };
|
|
29
|
-
if (Object.is(v, -0)) return { $float: '-0.0' };
|
|
30
|
-
if (Number.isInteger(v) && !Number.isSafeInteger(v)) return { $float: String(v) }; // a double, not an exact integer
|
|
31
|
-
return v; // JS has one number type: integral values encode as ints, others as floats
|
|
32
|
-
}
|
|
33
|
-
if (Array.isArray(v)) return v.map(encode);
|
|
34
|
-
if (v instanceof Set) return { $set: [...v].map(encode).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) };
|
|
35
|
-
if (v instanceof Map) return Object.fromEntries([...v].map(([k, x]) => [String(k), encode(x)]));
|
|
36
|
-
if (v instanceof Date) return { $repr: 'Date(' + v.toISOString() + ')' };
|
|
37
|
-
if (Buffer.isBuffer(v) || v instanceof Uint8Array) return { $bytes: Buffer.from(v).toString('base64') };
|
|
38
|
-
if (typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, encode(x)]));
|
|
39
|
-
return { $repr: String(v).slice(0, 200) };
|
|
40
|
-
}
|
|
41
|
-
function decode(v) {
|
|
42
|
-
if (Array.isArray(v)) return v.map(decode);
|
|
43
|
-
if (v && typeof v === 'object') {
|
|
44
|
-
if ('$float' in v) return { nan: NaN, inf: Infinity, '-inf': -Infinity, '-0.0': -0 }[v.$float] ?? Number(v.$float);
|
|
45
|
-
if ('$bytes' in v) return Buffer.from(v.$bytes, 'base64');
|
|
46
|
-
if ('$set' in v) return new Set(v.$set.map(decode));
|
|
47
|
-
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, decode(x)]));
|
|
48
|
-
}
|
|
49
|
-
return v;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// ------------------------------------------------------------------ module loading
|
|
53
|
-
const EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts']);
|
|
54
|
-
const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'out', 'coverage', '.next', 'vendor']);
|
|
55
|
-
function walk(dir, out = []) {
|
|
56
|
-
for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
57
|
-
if (e.isSymbolicLink()) continue;
|
|
58
|
-
const full = path.join(dir, e.name);
|
|
59
|
-
if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(full, out); }
|
|
60
|
-
else if (EXTS.has(path.extname(e.name)) && !/\.(test|spec|d)\.[cm]?[jt]s$/.test(e.name)) out.push(full);
|
|
61
|
-
}
|
|
62
|
-
return out;
|
|
63
|
-
}
|
|
64
|
-
function insideSrc(file) {
|
|
65
|
-
const real = fs.realpathSync(path.resolve(SRC, file));
|
|
66
|
-
if (!real.startsWith(fs.realpathSync(SRC) + path.sep)) throw new Error('module_file escapes the source root');
|
|
67
|
-
return real;
|
|
68
|
-
}
|
|
69
|
-
// TypeScript: transpile the whole source tree once into a /tmp mirror (types removed, inline
|
|
70
|
-
// source maps so stack traces and throw lines point at the original .ts lines), then import from there.
|
|
71
|
-
let tsMirror = null;
|
|
72
|
-
async function mirrorFor(file) {
|
|
73
|
-
if (!/\.m?ts$/.test(file)) return file;
|
|
74
|
-
if (!tsMirror) {
|
|
75
|
-
// Resolved like any dependency: this folder's node_modules in development, the package's when installed.
|
|
76
|
-
const ts = createRequire(import.meta.url)('typescript');
|
|
77
|
-
tsMirror = fs.mkdtempSync(path.join(os.tmpdir(), 'pp-ts-'));
|
|
78
|
-
fs.writeFileSync(path.join(tsMirror, 'package.json'), '{"type":"module"}');
|
|
79
|
-
for (const src of walk(SRC)) {
|
|
80
|
-
const rel = path.relative(SRC, src);
|
|
81
|
-
const out = path.join(tsMirror, rel.replace(/\.m?ts$/, '.js'));
|
|
82
|
-
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
83
|
-
const code = fs.readFileSync(src, 'utf8');
|
|
84
|
-
const js = /\.m?ts$/.test(src)
|
|
85
|
-
? ts.transpileModule(code, { fileName: src, compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, inlineSourceMap: true, inlineSources: true, rewriteRelativeImportExtensions: true } }).outputText
|
|
86
|
-
: code;
|
|
87
|
-
fs.writeFileSync(out, js);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
return path.join(tsMirror, path.relative(SRC, file).replace(/\.m?ts$/, '.js'));
|
|
91
|
-
}
|
|
92
|
-
async function loadModule(file) {
|
|
93
|
-
file = await mirrorFor(file);
|
|
94
|
-
const silent = () => true;
|
|
95
|
-
const restore = { log: console.log, warn: console.warn, error: console.error, info: console.info, w: process.stdout.write };
|
|
96
|
-
console.log = console.warn = console.error = console.info = () => {}; process.stdout.write = silent;
|
|
97
|
-
try {
|
|
98
|
-
const mod = await import(pathToFileURL(file).href);
|
|
99
|
-
const ns = {};
|
|
100
|
-
if (mod.default && typeof mod.default === 'object') Object.assign(ns, mod.default); // CommonJS module.exports
|
|
101
|
-
for (const [k, v] of Object.entries(mod)) if (k !== 'default') ns[k] = v;
|
|
102
|
-
if (typeof mod.default === 'function' && !ns[mod.default.name || 'default']) ns[mod.default.name || 'default'] = mod.default;
|
|
103
|
-
return ns;
|
|
104
|
-
} finally {
|
|
105
|
-
Object.assign(console, { log: restore.log, warn: restore.warn, error: restore.error, info: restore.info });
|
|
106
|
-
process.stdout.write = restore.w;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// ------------------------------------------------------------------ analyze
|
|
111
|
-
const EFFECTS = [
|
|
112
|
-
['filesystem', /\bfs\.|\bwriteFile|\breadFile|\bmkdir|\bunlink\(/],
|
|
113
|
-
['network', /\bfetch\(|\bhttps?\.(request|get)\(|\baxios\b|\bnew WebSocket\(|\bnet\.connect/],
|
|
114
|
-
['database', /\b(prisma|knex|sequelize|mongoose|pg|mysql2?)\./],
|
|
115
|
-
['process', /\bchild_process\b|\bexecSync\(|\bspawn\(|\bexec\(/],
|
|
116
|
-
['stdout', /\bconsole\.(log|info|warn|error)\(|process\.stdout\.write/],
|
|
117
|
-
['nondeterminism', /\bDate\.now\(|\bnew Date\(\)|\bMath\.random\(|\bcrypto\.random/],
|
|
118
|
-
['environment', /\bprocess\.env\b/],
|
|
119
|
-
];
|
|
120
|
-
function paramsOf(fnSource) {
|
|
121
|
-
const m = fnSource.match(/^[^(]*\(([^)]*)\)/s) || fnSource.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/);
|
|
122
|
-
if (!m) return [];
|
|
123
|
-
const list = m[1].split(',').map(p => p.trim()).filter(Boolean);
|
|
124
|
-
return list.map(p => {
|
|
125
|
-
const rest = p.startsWith('...');
|
|
126
|
-
const [left, def] = p.replace(/^\.\.\./, '').split('=').map(s => s.trim());
|
|
127
|
-
const [name, ann] = left.split(':').map(s => s && s.trim());
|
|
128
|
-
return { name: name.replace(/\?$/, ''), annotation: ann || null, default: def ?? null, kind: rest ? 'varargs' : 'positional' };
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
function analyze() {
|
|
132
|
-
const files = walk(SRC);
|
|
133
|
-
emit('log', { message: `found ${files.length} JS/TS files` });
|
|
134
|
-
return (async () => {
|
|
135
|
-
for (const full of files) {
|
|
136
|
-
const rel = path.relative(SRC, full).split(path.sep).join('/');
|
|
137
|
-
const raw = fs.readFileSync(full, 'utf8');
|
|
138
|
-
const isTs = /\.m?ts$/.test(full);
|
|
139
|
-
const imports = [...raw.matchAll(/(?:import\s[^'"]*from\s*|require\()\s*['"]([^'"]+)['"]/g)].map(m => m[1]);
|
|
140
|
-
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]))];
|
|
141
|
-
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') });
|
|
142
|
-
let ns;
|
|
143
|
-
try { ns = await loadModule(full); } catch (e) { emit('log', { message: `${rel}: could not import (${e.name}: ${e.message})` }); continue; }
|
|
144
|
-
const names = Object.keys(ns).filter(k => typeof ns[k] === 'function' && !/^class\s/.test(Function.prototype.toString.call(ns[k])));
|
|
145
|
-
for (const name of names) {
|
|
146
|
-
const compiled = Function.prototype.toString.call(ns[name]);
|
|
147
|
-
// Prefer the original (typed) text from the file; fall back to the compiled function text.
|
|
148
|
-
const head = compiled.slice(0, compiled.indexOf('{') > 0 ? compiled.indexOf('{') : 40).split('(')[0].trim();
|
|
149
|
-
const startIdx = locate(raw, name, isTs);
|
|
150
|
-
const original = startIdx >= 0 ? sliceFunction(raw, startIdx) : compiled;
|
|
151
|
-
const lineStart = startIdx >= 0 ? raw.slice(0, startIdx).split('\n').length : null;
|
|
152
|
-
const lineEnd = lineStart ? lineStart + original.split('\n').length - 1 : null;
|
|
153
|
-
const body = original;
|
|
154
|
-
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();
|
|
155
|
-
const effects = EFFECTS.filter(([, re]) => re.test(body)).map(([k]) => k);
|
|
156
|
-
const throwLines = [];
|
|
157
|
-
if (lineStart) body.split('\n').forEach((l, i) => { if (/\bthrow\b/.test(l)) throwLines.push(lineStart + i); });
|
|
158
|
-
const complexity = 1 + (body.match(/\b(if|for|while|case|catch)\b|\?\s|&&|\|\|/g) || []).length;
|
|
159
|
-
const depth = (body.match(/\b(for|while)\b[^{]*\{[^}]*\b(for|while)\b/s) ? 2 : 1);
|
|
160
|
-
emit('unit', {
|
|
161
|
-
file: rel, module: rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.'), name, owner: null,
|
|
162
|
-
qualified_name: `${rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.')}.${name}`, kind: 'function',
|
|
163
|
-
is_async: /^async\b/.test(head) || /^\s*export\s+async/.test(original), line_start: lineStart, line_end: lineEnd,
|
|
164
|
-
params: paramsOf(original.replace(/^\s*export\s+(default\s+)?/, '').replace(/^(async\s+)?function\s*\*?\s*[\w$]*/, '')),
|
|
165
|
-
returns: (original.match(/\)\s*:\s*([^{=]+?)\s*(\{|=>)/) || [])[1] || null, docstring: docComment(raw, startIdx),
|
|
166
|
-
source: original, digest: 'sha256:' + crypto.createHash('sha256').update(original).digest('hex'),
|
|
167
|
-
calls, internal_deps: calls.filter(c => names.includes(c) && c !== name), side_effects: effects,
|
|
168
|
-
complexity, loop_depth: depth, perf_hints: depth >= 2 ? [`nested loops (depth ${depth}): possible O(n^${depth}) path - static hint, not measured`] : [],
|
|
169
|
-
raise_lines: throwLines, loc: original.split('\n').length,
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
emit('done');
|
|
174
|
-
})();
|
|
175
|
-
}
|
|
176
|
-
function locate(raw, name, isTs) {
|
|
177
|
-
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*(:[^=]+)?=`),
|
|
178
|
-
new RegExp(`(^|\\n)[ \\t]*(exports|module\\.exports)\\.${name}\\s*=`)];
|
|
179
|
-
for (const p of pats) { const m = p.exec(raw); if (m) return m.index + (m[1] ? m[1].length : 0); }
|
|
180
|
-
return -1;
|
|
181
|
-
}
|
|
182
|
-
function sliceFunction(raw, start) {
|
|
183
|
-
const open = raw.indexOf('{', start); const arrow = raw.indexOf('=>', start);
|
|
184
|
-
// Arrow with an expression body (no block right after =>): the function ends at the line end.
|
|
185
|
-
if (open < 0 || (arrow >= 0 && arrow < open && raw.slice(arrow + 2, open).trim() !== '')) {
|
|
186
|
-
const end = raw.indexOf('\n', arrow >= 0 ? arrow : start);
|
|
187
|
-
return raw.slice(start, end < 0 ? raw.length : end).trimEnd();
|
|
188
|
-
}
|
|
189
|
-
let depth = 0; let i = open; let q = null;
|
|
190
|
-
for (; i < raw.length; i++) {
|
|
191
|
-
const c = raw[i];
|
|
192
|
-
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
|
|
193
|
-
if (c === '"' || c === "'" || c === '`') q = c;
|
|
194
|
-
else if (c === '{') depth++;
|
|
195
|
-
else if (c === '}' && --depth === 0) break;
|
|
196
|
-
}
|
|
197
|
-
return raw.slice(start, i + 1);
|
|
198
|
-
}
|
|
199
|
-
function docComment(raw, start) {
|
|
200
|
-
if (start <= 0) return null;
|
|
201
|
-
const before = raw.slice(0, start);
|
|
202
|
-
const open = before.lastIndexOf('/**');
|
|
203
|
-
const close = before.lastIndexOf('*/');
|
|
204
|
-
if (open < 0 || close < open || before.slice(close + 2).trim() !== '') return null;
|
|
205
|
-
return before.slice(open + 3, close).replace(/^\s*\* ?/gm, '').trim();
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// ------------------------------------------------------------------ input generation
|
|
209
|
-
const POOLS = {
|
|
210
|
-
string: ['', ' ', 'a', 'Hello World', ' multiple spaces ', 'UPPER lower', 'ünïcödé café', 'emoji 😀 here', '-0', '42', 'x'.repeat(300), '!!!'],
|
|
211
|
-
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' }],
|
|
212
|
-
boolean: [true, false],
|
|
213
|
-
array: [[], [1], [1, 2, 3], [-1.5, 2.5], ['apple', 'avocado', 'banana']],
|
|
214
|
-
matrix: [[], [[1, 250]], [[2, 1999], [1, 5]], [[0, 100]], [[-1, 5]], [[3, 0.5]], [[1, 1], [2, 2], [3, 3]]],
|
|
215
|
-
any: ['', 'a', 0, 1, -1, null, [], [1, 2], { a: 1 }, true],
|
|
216
|
-
};
|
|
217
|
-
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;
|
|
218
|
-
function rng(seed) { let s = (seed >>> 0) || 1; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
|
|
219
|
-
function randomValue(r, ann) {
|
|
220
|
-
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';
|
|
221
|
-
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(''); }
|
|
222
|
-
if (k === 'number') return r() < 0.5 ? Math.floor(r() * 21) - 10 : Math.round((r() * 2e6 - 1e6) * 100) / 100;
|
|
223
|
-
if (k === 'boolean') return r() < 0.5;
|
|
224
|
-
if (k === 'matrix') return Array.from({ length: Math.floor(r() * 4) }, () => [Math.floor(r() * 7) - 1, Math.floor(r() * 5000)]);
|
|
225
|
-
if (k === 'array') return Array.from({ length: Math.floor(r() * 6) }, () => Math.floor(r() * 101) - 50);
|
|
226
|
-
return [null, 1, 's'][Math.floor(r() * 3)];
|
|
227
|
-
}
|
|
228
|
-
function generate(params, count, seed, mode) {
|
|
229
|
-
const r = rng(seed); const seen = new Set(); const out = [];
|
|
230
|
-
const req = params.filter(p => p.kind === 'positional');
|
|
231
|
-
for (let n = 0; out.length < count && n < count * 20; n++) {
|
|
232
|
-
const args = [];
|
|
233
|
-
for (const [i, p] of req.entries()) {
|
|
234
|
-
if (p.default !== null && r() < 0.5) break;
|
|
235
|
-
if (mode === 'fuzz') args.push(randomValue(r, p.annotation));
|
|
236
|
-
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)]); }
|
|
237
|
-
}
|
|
238
|
-
const key = JSON.stringify(args);
|
|
239
|
-
if (seen.has(key)) continue;
|
|
240
|
-
seen.add(key); out.push({ args: encode(decode(args)), kwargs: {}, origin: mode === 'fuzz' ? 'fuzz' : 'generated' });
|
|
241
|
-
}
|
|
242
|
-
return out;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// ------------------------------------------------------------------ record / bench
|
|
246
|
-
function snapshot(root) {
|
|
247
|
-
const out = [];
|
|
248
|
-
(function rec(d) {
|
|
249
|
-
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
250
|
-
const f = path.join(d, e.name);
|
|
251
|
-
if (e.isDirectory()) rec(f);
|
|
252
|
-
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') }); }
|
|
253
|
-
}
|
|
254
|
-
})(root);
|
|
255
|
-
return out.sort((a, b) => a.path.localeCompare(b.path));
|
|
256
|
-
}
|
|
257
|
-
function throwLine(err, file) {
|
|
258
|
-
const lines = String(err && err.stack || '').split('\n');
|
|
259
|
-
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]); }
|
|
260
|
-
return null;
|
|
261
|
-
}
|
|
262
|
-
async function runCase(fn, file, c) {
|
|
263
|
-
const args = decode(c.args || []);
|
|
264
|
-
let out = '', err = '';
|
|
265
|
-
const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error, ow: process.stdout.write, ew: process.stderr.write };
|
|
266
|
-
console.log = console.info = (...a) => { out += a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\n'; };
|
|
267
|
-
console.warn = console.error = (...a) => { err += a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\n'; };
|
|
268
|
-
process.stdout.write = s => { out += s; return true; }; process.stderr.write = s => { err += s; return true; };
|
|
269
|
-
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'pp-case-')); const cwd = process.cwd(); process.chdir(scratch);
|
|
270
|
-
const t0 = process.hrtime.bigint(); let outcome;
|
|
271
|
-
try { outcome = { kind: 'return', value: encode(await fn(...args)) }; }
|
|
272
|
-
catch (e) {
|
|
273
|
-
outcome = { kind: 'raise', type: (e && e.constructor && e.constructor.name) || typeof e, message: String(e && e.message !== undefined ? e.message : e) };
|
|
274
|
-
const line = throwLine(e, file); if (line) outcome.raise_line = line;
|
|
275
|
-
} finally {
|
|
276
|
-
Object.assign(console, { log: saved.log, info: saved.info, warn: saved.warn, error: saved.error });
|
|
277
|
-
process.stdout.write = saved.ow; process.stderr.write = saved.ew;
|
|
278
|
-
}
|
|
279
|
-
const duration_us = Number((process.hrtime.bigint() - t0) / 1000n);
|
|
280
|
-
const effects = snapshot(scratch); process.chdir(cwd); fs.rmSync(scratch, { recursive: true, force: true });
|
|
281
|
-
return { outcome, stdout: out, stderr: err, effects, duration_us };
|
|
282
|
-
}
|
|
283
|
-
async function target(req) {
|
|
284
|
-
const file = insideSrc(req.module_file);
|
|
285
|
-
const ns = await loadModule(file);
|
|
286
|
-
const fn = ns[req.function];
|
|
287
|
-
if (typeof fn !== 'function') { emit('fatal', { message: `${req.function} is not an exported function of ${req.module_file}` }); process.exit(2); }
|
|
288
|
-
return { fn, file };
|
|
289
|
-
}
|
|
290
|
-
// Opt-in (req.pin_clock): the clock reads 2026-01-01T00:00:00Z and Math.random restarts from seed 0
|
|
291
|
-
// before every run, so time- and random-dependent results are reproducible.
|
|
292
|
-
const PIN_MS = 1767225600000;
|
|
293
|
-
let rngState = 0;
|
|
294
|
-
function reseed() { rngState = 0; }
|
|
295
|
-
function pinClock() {
|
|
296
|
-
const RealDate = Date;
|
|
297
|
-
class PinnedDate extends RealDate {
|
|
298
|
-
constructor(...a) { if (a.length === 0) super(PIN_MS); else super(...a); }
|
|
299
|
-
static now() { return PIN_MS; }
|
|
300
|
-
}
|
|
301
|
-
globalThis.Date = PinnedDate;
|
|
302
|
-
Math.random = () => { // mulberry32
|
|
303
|
-
rngState = (rngState + 0x6D2B79F5) | 0;
|
|
304
|
-
let t = Math.imul(rngState ^ (rngState >>> 15), 1 | rngState);
|
|
305
|
-
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
306
|
-
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
async function record(req) {
|
|
310
|
-
const pinned = !!req.pin_clock;
|
|
311
|
-
if (pinned) pinClock();
|
|
312
|
-
const { fn, file } = await target(req);
|
|
313
|
-
const raw = fs.readFileSync(file, 'utf8'); const start = locate(raw, req.function, /ts$/.test(file));
|
|
314
|
-
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$]*/, ''));
|
|
315
|
-
const cases = [...(req.cases || [])];
|
|
316
|
-
const g = req.generate || {};
|
|
317
|
-
if (g.count) cases.push(...generate(params, Number(g.count), Number(g.seed || 0), g.mode || 'edge'));
|
|
318
|
-
emit('log', { message: `recording ${cases.length} cases for ${req.function} (node ${process.versions.node})` });
|
|
319
|
-
emit('plan', { total: cases.length, runtime: `node ${process.versions.node}` });
|
|
320
|
-
const obs = r => JSON.stringify([r.outcome, r.stdout, r.stderr, r.effects]);
|
|
321
|
-
for (const [index, c] of cases.entries()) {
|
|
322
|
-
if (pinned) reseed();
|
|
323
|
-
const first = await runCase(fn, file, c);
|
|
324
|
-
if (pinned) reseed();
|
|
325
|
-
const second = await runCase(fn, file, c);
|
|
326
|
-
emit('case', { index, ref: c.ref ?? null, origin: c.origin || 'manual', args: c.args || [], kwargs: c.kwargs || {}, stable: obs(first) === obs(second), ...first });
|
|
327
|
-
}
|
|
328
|
-
emit('done');
|
|
329
|
-
}
|
|
330
|
-
async function bench(req) {
|
|
331
|
-
const { fn } = await target(req);
|
|
332
|
-
const iterations = Math.max(1, Math.min(Number(req.iterations || 30), 10000));
|
|
333
|
-
emit('plan', { total: req.cases.length, runtime: `node ${process.versions.node}` });
|
|
334
|
-
const saved = console.log; console.log = () => {};
|
|
335
|
-
for (const c of req.cases) {
|
|
336
|
-
const args = decode(c.args || []); const samples = [];
|
|
337
|
-
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)); }
|
|
338
|
-
emit('case', { ref: c.ref ?? null, samples_ns: samples, peak_memory_bytes: null });
|
|
339
|
-
}
|
|
340
|
-
console.log = saved;
|
|
341
|
-
emit('done');
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
let input = '';
|
|
345
|
-
process.stdin.setEncoding('utf8');
|
|
346
|
-
for await (const chunk of process.stdin) input += chunk;
|
|
347
|
-
const req = JSON.parse(input || '{}');
|
|
348
|
-
const handlers = { analyze, record, bench };
|
|
349
|
-
if (!handlers[req.command]) { emit('fatal', { message: `unknown command ${req.command}` }); process.exit(2); }
|
|
350
|
-
await handlers[req.command](req);
|
|
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
|
+
import { createRequire } from 'node:module';
|
|
15
|
+
|
|
16
|
+
const SRC = process.env.PORTPILOT_SRC || '/work/src';
|
|
17
|
+
const realWrite = process.stdout.write.bind(process.stdout);
|
|
18
|
+
const emit = (event, data = {}) => realWrite(JSON.stringify({ ...data, event }) + '\n');
|
|
19
|
+
|
|
20
|
+
// ------------------------------------------------------------------ value codec
|
|
21
|
+
function encode(v) {
|
|
22
|
+
if (v === null || v === undefined) return null;
|
|
23
|
+
if (typeof v === 'boolean' || typeof v === 'string') return v;
|
|
24
|
+
if (typeof v === 'bigint') return Number.isSafeInteger(Number(v)) ? Number(v) : { $repr: v.toString() + 'n' };
|
|
25
|
+
if (typeof v === 'number') {
|
|
26
|
+
if (Number.isNaN(v)) return { $float: 'nan' };
|
|
27
|
+
if (v === Infinity) return { $float: 'inf' };
|
|
28
|
+
if (v === -Infinity) return { $float: '-inf' };
|
|
29
|
+
if (Object.is(v, -0)) return { $float: '-0.0' };
|
|
30
|
+
if (Number.isInteger(v) && !Number.isSafeInteger(v)) return { $float: String(v) }; // a double, not an exact integer
|
|
31
|
+
return v; // JS has one number type: integral values encode as ints, others as floats
|
|
32
|
+
}
|
|
33
|
+
if (Array.isArray(v)) return v.map(encode);
|
|
34
|
+
if (v instanceof Set) return { $set: [...v].map(encode).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) };
|
|
35
|
+
if (v instanceof Map) return Object.fromEntries([...v].map(([k, x]) => [String(k), encode(x)]));
|
|
36
|
+
if (v instanceof Date) return { $repr: 'Date(' + v.toISOString() + ')' };
|
|
37
|
+
if (Buffer.isBuffer(v) || v instanceof Uint8Array) return { $bytes: Buffer.from(v).toString('base64') };
|
|
38
|
+
if (typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, encode(x)]));
|
|
39
|
+
return { $repr: String(v).slice(0, 200) };
|
|
40
|
+
}
|
|
41
|
+
function decode(v) {
|
|
42
|
+
if (Array.isArray(v)) return v.map(decode);
|
|
43
|
+
if (v && typeof v === 'object') {
|
|
44
|
+
if ('$float' in v) return { nan: NaN, inf: Infinity, '-inf': -Infinity, '-0.0': -0 }[v.$float] ?? Number(v.$float);
|
|
45
|
+
if ('$bytes' in v) return Buffer.from(v.$bytes, 'base64');
|
|
46
|
+
if ('$set' in v) return new Set(v.$set.map(decode));
|
|
47
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, decode(x)]));
|
|
48
|
+
}
|
|
49
|
+
return v;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ------------------------------------------------------------------ module loading
|
|
53
|
+
const EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts']);
|
|
54
|
+
const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'out', 'coverage', '.next', 'vendor']);
|
|
55
|
+
function walk(dir, out = []) {
|
|
56
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
57
|
+
if (e.isSymbolicLink()) continue;
|
|
58
|
+
const full = path.join(dir, e.name);
|
|
59
|
+
if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(full, out); }
|
|
60
|
+
else if (EXTS.has(path.extname(e.name)) && !/\.(test|spec|d)\.[cm]?[jt]s$/.test(e.name)) out.push(full);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
function insideSrc(file) {
|
|
65
|
+
const real = fs.realpathSync(path.resolve(SRC, file));
|
|
66
|
+
if (!real.startsWith(fs.realpathSync(SRC) + path.sep)) throw new Error('module_file escapes the source root');
|
|
67
|
+
return real;
|
|
68
|
+
}
|
|
69
|
+
// TypeScript: transpile the whole source tree once into a /tmp mirror (types removed, inline
|
|
70
|
+
// source maps so stack traces and throw lines point at the original .ts lines), then import from there.
|
|
71
|
+
let tsMirror = null;
|
|
72
|
+
async function mirrorFor(file) {
|
|
73
|
+
if (!/\.m?ts$/.test(file)) return file;
|
|
74
|
+
if (!tsMirror) {
|
|
75
|
+
// Resolved like any dependency: this folder's node_modules in development, the package's when installed.
|
|
76
|
+
const ts = createRequire(import.meta.url)('typescript');
|
|
77
|
+
tsMirror = fs.mkdtempSync(path.join(os.tmpdir(), 'pp-ts-'));
|
|
78
|
+
fs.writeFileSync(path.join(tsMirror, 'package.json'), '{"type":"module"}');
|
|
79
|
+
for (const src of walk(SRC)) {
|
|
80
|
+
const rel = path.relative(SRC, src);
|
|
81
|
+
const out = path.join(tsMirror, rel.replace(/\.m?ts$/, '.js'));
|
|
82
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
83
|
+
const code = fs.readFileSync(src, 'utf8');
|
|
84
|
+
const js = /\.m?ts$/.test(src)
|
|
85
|
+
? ts.transpileModule(code, { fileName: src, compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, inlineSourceMap: true, inlineSources: true, rewriteRelativeImportExtensions: true } }).outputText
|
|
86
|
+
: code;
|
|
87
|
+
fs.writeFileSync(out, js);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return path.join(tsMirror, path.relative(SRC, file).replace(/\.m?ts$/, '.js'));
|
|
91
|
+
}
|
|
92
|
+
async function loadModule(file) {
|
|
93
|
+
file = await mirrorFor(file);
|
|
94
|
+
const silent = () => true;
|
|
95
|
+
const restore = { log: console.log, warn: console.warn, error: console.error, info: console.info, w: process.stdout.write };
|
|
96
|
+
console.log = console.warn = console.error = console.info = () => {}; process.stdout.write = silent;
|
|
97
|
+
try {
|
|
98
|
+
const mod = await import(pathToFileURL(file).href);
|
|
99
|
+
const ns = {};
|
|
100
|
+
if (mod.default && typeof mod.default === 'object') Object.assign(ns, mod.default); // CommonJS module.exports
|
|
101
|
+
for (const [k, v] of Object.entries(mod)) if (k !== 'default') ns[k] = v;
|
|
102
|
+
if (typeof mod.default === 'function' && !ns[mod.default.name || 'default']) ns[mod.default.name || 'default'] = mod.default;
|
|
103
|
+
return ns;
|
|
104
|
+
} finally {
|
|
105
|
+
Object.assign(console, { log: restore.log, warn: restore.warn, error: restore.error, info: restore.info });
|
|
106
|
+
process.stdout.write = restore.w;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ------------------------------------------------------------------ analyze
|
|
111
|
+
const EFFECTS = [
|
|
112
|
+
['filesystem', /\bfs\.|\bwriteFile|\breadFile|\bmkdir|\bunlink\(/],
|
|
113
|
+
['network', /\bfetch\(|\bhttps?\.(request|get)\(|\baxios\b|\bnew WebSocket\(|\bnet\.connect/],
|
|
114
|
+
['database', /\b(prisma|knex|sequelize|mongoose|pg|mysql2?)\./],
|
|
115
|
+
['process', /\bchild_process\b|\bexecSync\(|\bspawn\(|\bexec\(/],
|
|
116
|
+
['stdout', /\bconsole\.(log|info|warn|error)\(|process\.stdout\.write/],
|
|
117
|
+
['nondeterminism', /\bDate\.now\(|\bnew Date\(\)|\bMath\.random\(|\bcrypto\.random/],
|
|
118
|
+
['environment', /\bprocess\.env\b/],
|
|
119
|
+
];
|
|
120
|
+
function paramsOf(fnSource) {
|
|
121
|
+
const m = fnSource.match(/^[^(]*\(([^)]*)\)/s) || fnSource.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/);
|
|
122
|
+
if (!m) return [];
|
|
123
|
+
const list = m[1].split(',').map(p => p.trim()).filter(Boolean);
|
|
124
|
+
return list.map(p => {
|
|
125
|
+
const rest = p.startsWith('...');
|
|
126
|
+
const [left, def] = p.replace(/^\.\.\./, '').split('=').map(s => s.trim());
|
|
127
|
+
const [name, ann] = left.split(':').map(s => s && s.trim());
|
|
128
|
+
return { name: name.replace(/\?$/, ''), annotation: ann || null, default: def ?? null, kind: rest ? 'varargs' : 'positional' };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function analyze() {
|
|
132
|
+
const files = walk(SRC);
|
|
133
|
+
emit('log', { message: `found ${files.length} JS/TS files` });
|
|
134
|
+
return (async () => {
|
|
135
|
+
for (const full of files) {
|
|
136
|
+
const rel = path.relative(SRC, full).split(path.sep).join('/');
|
|
137
|
+
const raw = fs.readFileSync(full, 'utf8');
|
|
138
|
+
const isTs = /\.m?ts$/.test(full);
|
|
139
|
+
const imports = [...raw.matchAll(/(?:import\s[^'"]*from\s*|require\()\s*['"]([^'"]+)['"]/g)].map(m => m[1]);
|
|
140
|
+
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]))];
|
|
141
|
+
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') });
|
|
142
|
+
let ns;
|
|
143
|
+
try { ns = await loadModule(full); } catch (e) { emit('log', { message: `${rel}: could not import (${e.name}: ${e.message})` }); continue; }
|
|
144
|
+
const names = Object.keys(ns).filter(k => typeof ns[k] === 'function' && !/^class\s/.test(Function.prototype.toString.call(ns[k])));
|
|
145
|
+
for (const name of names) {
|
|
146
|
+
const compiled = Function.prototype.toString.call(ns[name]);
|
|
147
|
+
// Prefer the original (typed) text from the file; fall back to the compiled function text.
|
|
148
|
+
const head = compiled.slice(0, compiled.indexOf('{') > 0 ? compiled.indexOf('{') : 40).split('(')[0].trim();
|
|
149
|
+
const startIdx = locate(raw, name, isTs);
|
|
150
|
+
const original = startIdx >= 0 ? sliceFunction(raw, startIdx) : compiled;
|
|
151
|
+
const lineStart = startIdx >= 0 ? raw.slice(0, startIdx).split('\n').length : null;
|
|
152
|
+
const lineEnd = lineStart ? lineStart + original.split('\n').length - 1 : null;
|
|
153
|
+
const body = original;
|
|
154
|
+
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();
|
|
155
|
+
const effects = EFFECTS.filter(([, re]) => re.test(body)).map(([k]) => k);
|
|
156
|
+
const throwLines = [];
|
|
157
|
+
if (lineStart) body.split('\n').forEach((l, i) => { if (/\bthrow\b/.test(l)) throwLines.push(lineStart + i); });
|
|
158
|
+
const complexity = 1 + (body.match(/\b(if|for|while|case|catch)\b|\?\s|&&|\|\|/g) || []).length;
|
|
159
|
+
const depth = (body.match(/\b(for|while)\b[^{]*\{[^}]*\b(for|while)\b/s) ? 2 : 1);
|
|
160
|
+
emit('unit', {
|
|
161
|
+
file: rel, module: rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.'), name, owner: null,
|
|
162
|
+
qualified_name: `${rel.replace(/\.[cm]?[jt]s$/, '').replace(/\//g, '.')}.${name}`, kind: 'function',
|
|
163
|
+
is_async: /^async\b/.test(head) || /^\s*export\s+async/.test(original), line_start: lineStart, line_end: lineEnd,
|
|
164
|
+
params: paramsOf(original.replace(/^\s*export\s+(default\s+)?/, '').replace(/^(async\s+)?function\s*\*?\s*[\w$]*/, '')),
|
|
165
|
+
returns: (original.match(/\)\s*:\s*([^{=]+?)\s*(\{|=>)/) || [])[1] || null, docstring: docComment(raw, startIdx),
|
|
166
|
+
source: original, digest: 'sha256:' + crypto.createHash('sha256').update(original).digest('hex'),
|
|
167
|
+
calls, internal_deps: calls.filter(c => names.includes(c) && c !== name), side_effects: effects,
|
|
168
|
+
complexity, loop_depth: depth, perf_hints: depth >= 2 ? [`nested loops (depth ${depth}): possible O(n^${depth}) path - static hint, not measured`] : [],
|
|
169
|
+
raise_lines: throwLines, loc: original.split('\n').length,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
emit('done');
|
|
174
|
+
})();
|
|
175
|
+
}
|
|
176
|
+
function locate(raw, name, isTs) {
|
|
177
|
+
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*(:[^=]+)?=`),
|
|
178
|
+
new RegExp(`(^|\\n)[ \\t]*(exports|module\\.exports)\\.${name}\\s*=`)];
|
|
179
|
+
for (const p of pats) { const m = p.exec(raw); if (m) return m.index + (m[1] ? m[1].length : 0); }
|
|
180
|
+
return -1;
|
|
181
|
+
}
|
|
182
|
+
function sliceFunction(raw, start) {
|
|
183
|
+
const open = raw.indexOf('{', start); const arrow = raw.indexOf('=>', start);
|
|
184
|
+
// Arrow with an expression body (no block right after =>): the function ends at the line end.
|
|
185
|
+
if (open < 0 || (arrow >= 0 && arrow < open && raw.slice(arrow + 2, open).trim() !== '')) {
|
|
186
|
+
const end = raw.indexOf('\n', arrow >= 0 ? arrow : start);
|
|
187
|
+
return raw.slice(start, end < 0 ? raw.length : end).trimEnd();
|
|
188
|
+
}
|
|
189
|
+
let depth = 0; let i = open; let q = null;
|
|
190
|
+
for (; i < raw.length; i++) {
|
|
191
|
+
const c = raw[i];
|
|
192
|
+
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
|
|
193
|
+
if (c === '"' || c === "'" || c === '`') q = c;
|
|
194
|
+
else if (c === '{') depth++;
|
|
195
|
+
else if (c === '}' && --depth === 0) break;
|
|
196
|
+
}
|
|
197
|
+
return raw.slice(start, i + 1);
|
|
198
|
+
}
|
|
199
|
+
function docComment(raw, start) {
|
|
200
|
+
if (start <= 0) return null;
|
|
201
|
+
const before = raw.slice(0, start);
|
|
202
|
+
const open = before.lastIndexOf('/**');
|
|
203
|
+
const close = before.lastIndexOf('*/');
|
|
204
|
+
if (open < 0 || close < open || before.slice(close + 2).trim() !== '') return null;
|
|
205
|
+
return before.slice(open + 3, close).replace(/^\s*\* ?/gm, '').trim();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ------------------------------------------------------------------ input generation
|
|
209
|
+
const POOLS = {
|
|
210
|
+
string: ['', ' ', 'a', 'Hello World', ' multiple spaces ', 'UPPER lower', 'ünïcödé café', 'emoji 😀 here', '-0', '42', 'x'.repeat(300), '!!!'],
|
|
211
|
+
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' }],
|
|
212
|
+
boolean: [true, false],
|
|
213
|
+
array: [[], [1], [1, 2, 3], [-1.5, 2.5], ['apple', 'avocado', 'banana']],
|
|
214
|
+
matrix: [[], [[1, 250]], [[2, 1999], [1, 5]], [[0, 100]], [[-1, 5]], [[3, 0.5]], [[1, 1], [2, 2], [3, 3]]],
|
|
215
|
+
any: ['', 'a', 0, 1, -1, null, [], [1, 2], { a: 1 }, true],
|
|
216
|
+
};
|
|
217
|
+
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;
|
|
218
|
+
function rng(seed) { let s = (seed >>> 0) || 1; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
|
|
219
|
+
function randomValue(r, ann) {
|
|
220
|
+
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';
|
|
221
|
+
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(''); }
|
|
222
|
+
if (k === 'number') return r() < 0.5 ? Math.floor(r() * 21) - 10 : Math.round((r() * 2e6 - 1e6) * 100) / 100;
|
|
223
|
+
if (k === 'boolean') return r() < 0.5;
|
|
224
|
+
if (k === 'matrix') return Array.from({ length: Math.floor(r() * 4) }, () => [Math.floor(r() * 7) - 1, Math.floor(r() * 5000)]);
|
|
225
|
+
if (k === 'array') return Array.from({ length: Math.floor(r() * 6) }, () => Math.floor(r() * 101) - 50);
|
|
226
|
+
return [null, 1, 's'][Math.floor(r() * 3)];
|
|
227
|
+
}
|
|
228
|
+
function generate(params, count, seed, mode) {
|
|
229
|
+
const r = rng(seed); const seen = new Set(); const out = [];
|
|
230
|
+
const req = params.filter(p => p.kind === 'positional');
|
|
231
|
+
for (let n = 0; out.length < count && n < count * 20; n++) {
|
|
232
|
+
const args = [];
|
|
233
|
+
for (const [i, p] of req.entries()) {
|
|
234
|
+
if (p.default !== null && r() < 0.5) break;
|
|
235
|
+
if (mode === 'fuzz') args.push(randomValue(r, p.annotation));
|
|
236
|
+
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)]); }
|
|
237
|
+
}
|
|
238
|
+
const key = JSON.stringify(args);
|
|
239
|
+
if (seen.has(key)) continue;
|
|
240
|
+
seen.add(key); out.push({ args: encode(decode(args)), kwargs: {}, origin: mode === 'fuzz' ? 'fuzz' : 'generated' });
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ------------------------------------------------------------------ record / bench
|
|
246
|
+
function snapshot(root) {
|
|
247
|
+
const out = [];
|
|
248
|
+
(function rec(d) {
|
|
249
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
250
|
+
const f = path.join(d, e.name);
|
|
251
|
+
if (e.isDirectory()) rec(f);
|
|
252
|
+
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') }); }
|
|
253
|
+
}
|
|
254
|
+
})(root);
|
|
255
|
+
return out.sort((a, b) => a.path.localeCompare(b.path));
|
|
256
|
+
}
|
|
257
|
+
function throwLine(err, file) {
|
|
258
|
+
const lines = String(err && err.stack || '').split('\n');
|
|
259
|
+
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]); }
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
async function runCase(fn, file, c) {
|
|
263
|
+
const args = decode(c.args || []);
|
|
264
|
+
let out = '', err = '';
|
|
265
|
+
const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error, ow: process.stdout.write, ew: process.stderr.write };
|
|
266
|
+
console.log = console.info = (...a) => { out += a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\n'; };
|
|
267
|
+
console.warn = console.error = (...a) => { err += a.map(x => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\n'; };
|
|
268
|
+
process.stdout.write = s => { out += s; return true; }; process.stderr.write = s => { err += s; return true; };
|
|
269
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'pp-case-')); const cwd = process.cwd(); process.chdir(scratch);
|
|
270
|
+
const t0 = process.hrtime.bigint(); let outcome;
|
|
271
|
+
try { outcome = { kind: 'return', value: encode(await fn(...args)) }; }
|
|
272
|
+
catch (e) {
|
|
273
|
+
outcome = { kind: 'raise', type: (e && e.constructor && e.constructor.name) || typeof e, message: String(e && e.message !== undefined ? e.message : e) };
|
|
274
|
+
const line = throwLine(e, file); if (line) outcome.raise_line = line;
|
|
275
|
+
} finally {
|
|
276
|
+
Object.assign(console, { log: saved.log, info: saved.info, warn: saved.warn, error: saved.error });
|
|
277
|
+
process.stdout.write = saved.ow; process.stderr.write = saved.ew;
|
|
278
|
+
}
|
|
279
|
+
const duration_us = Number((process.hrtime.bigint() - t0) / 1000n);
|
|
280
|
+
const effects = snapshot(scratch); process.chdir(cwd); fs.rmSync(scratch, { recursive: true, force: true });
|
|
281
|
+
return { outcome, stdout: out, stderr: err, effects, duration_us };
|
|
282
|
+
}
|
|
283
|
+
async function target(req) {
|
|
284
|
+
const file = insideSrc(req.module_file);
|
|
285
|
+
const ns = await loadModule(file);
|
|
286
|
+
const fn = ns[req.function];
|
|
287
|
+
if (typeof fn !== 'function') { emit('fatal', { message: `${req.function} is not an exported function of ${req.module_file}` }); process.exit(2); }
|
|
288
|
+
return { fn, file };
|
|
289
|
+
}
|
|
290
|
+
// Opt-in (req.pin_clock): the clock reads 2026-01-01T00:00:00Z and Math.random restarts from seed 0
|
|
291
|
+
// before every run, so time- and random-dependent results are reproducible.
|
|
292
|
+
const PIN_MS = 1767225600000;
|
|
293
|
+
let rngState = 0;
|
|
294
|
+
function reseed() { rngState = 0; }
|
|
295
|
+
function pinClock() {
|
|
296
|
+
const RealDate = Date;
|
|
297
|
+
class PinnedDate extends RealDate {
|
|
298
|
+
constructor(...a) { if (a.length === 0) super(PIN_MS); else super(...a); }
|
|
299
|
+
static now() { return PIN_MS; }
|
|
300
|
+
}
|
|
301
|
+
globalThis.Date = PinnedDate;
|
|
302
|
+
Math.random = () => { // mulberry32
|
|
303
|
+
rngState = (rngState + 0x6D2B79F5) | 0;
|
|
304
|
+
let t = Math.imul(rngState ^ (rngState >>> 15), 1 | rngState);
|
|
305
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
306
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
async function record(req) {
|
|
310
|
+
const pinned = !!req.pin_clock;
|
|
311
|
+
if (pinned) pinClock();
|
|
312
|
+
const { fn, file } = await target(req);
|
|
313
|
+
const raw = fs.readFileSync(file, 'utf8'); const start = locate(raw, req.function, /ts$/.test(file));
|
|
314
|
+
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$]*/, ''));
|
|
315
|
+
const cases = [...(req.cases || [])];
|
|
316
|
+
const g = req.generate || {};
|
|
317
|
+
if (g.count) cases.push(...generate(params, Number(g.count), Number(g.seed || 0), g.mode || 'edge'));
|
|
318
|
+
emit('log', { message: `recording ${cases.length} cases for ${req.function} (node ${process.versions.node})` });
|
|
319
|
+
emit('plan', { total: cases.length, runtime: `node ${process.versions.node}` });
|
|
320
|
+
const obs = r => JSON.stringify([r.outcome, r.stdout, r.stderr, r.effects]);
|
|
321
|
+
for (const [index, c] of cases.entries()) {
|
|
322
|
+
if (pinned) reseed();
|
|
323
|
+
const first = await runCase(fn, file, c);
|
|
324
|
+
if (pinned) reseed();
|
|
325
|
+
const second = await runCase(fn, file, c);
|
|
326
|
+
emit('case', { index, ref: c.ref ?? null, origin: c.origin || 'manual', args: c.args || [], kwargs: c.kwargs || {}, stable: obs(first) === obs(second), ...first });
|
|
327
|
+
}
|
|
328
|
+
emit('done');
|
|
329
|
+
}
|
|
330
|
+
async function bench(req) {
|
|
331
|
+
const { fn } = await target(req);
|
|
332
|
+
const iterations = Math.max(1, Math.min(Number(req.iterations || 30), 10000));
|
|
333
|
+
emit('plan', { total: req.cases.length, runtime: `node ${process.versions.node}` });
|
|
334
|
+
const saved = console.log; console.log = () => {};
|
|
335
|
+
for (const c of req.cases) {
|
|
336
|
+
const args = decode(c.args || []); const samples = [];
|
|
337
|
+
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)); }
|
|
338
|
+
emit('case', { ref: c.ref ?? null, samples_ns: samples, peak_memory_bytes: null });
|
|
339
|
+
}
|
|
340
|
+
console.log = saved;
|
|
341
|
+
emit('done');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
let input = '';
|
|
345
|
+
process.stdin.setEncoding('utf8');
|
|
346
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
347
|
+
const req = JSON.parse(input || '{}');
|
|
348
|
+
const handlers = { analyze, record, bench };
|
|
349
|
+
if (!handlers[req.command]) { emit('fatal', { message: `unknown command ${req.command}` }); process.exit(2); }
|
|
350
|
+
await handlers[req.command](req);
|