mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-04 00:15:41 -08:00
837 lines
34 KiB
JavaScript
837 lines
34 KiB
JavaScript
#!/usr/bin/env node
|
|||
|
|
// Install/update benchmark for Plan2Code. Dev-only: lives in scripts/ so it
|
||
|
|
// never ships inside a skill or the runtime install payload.
|
||
|
|
//
|
||
|
|
// node scripts/bench-install-update.mjs --mode cold-npx --baseline v3.2.1 --candidate main
|
||
|
|
//
|
||
|
|
// Every timed run is given throwaway home, npm, console and application-data
|
||
|
|
// locations. The measured installer never sees the developer's real HOME,
|
||
|
|
// npm prefix or npm cache. warm-npx deliberately separates cache warmth from
|
||
|
|
// installer-state warmth: one untimed warm-up per ref primes the npm cache
|
||
|
|
// shared by that ref's timed runs, but uses a sibling warm-up HOME, so every
|
||
|
|
// timed run still starts with a fresh HOME. warm-canonical is the mode that
|
||
|
|
// reuses HOME, because its purpose is to measure repeated updates against
|
||
|
|
// already-installed state.
|
||
|
|
|
||
|
|
import fs from "node:fs";
|
||
|
|
import os from "node:os";
|
||
|
|
import path from "node:path";
|
||
|
|
import { spawn } from "node:child_process";
|
||
|
|
import { fileURLToPath } from "node:url";
|
||
|
|
import { createRequire } from "node:module";
|
||
|
|
|
||
|
|
const require = createRequire(import.meta.url);
|
||
|
|
const { readTimingEvents } = require("../src/installer/timing.js");
|
||
|
|
|
||
|
|
export const MODES = ["cold-npx", "warm-npx", "warm-canonical"];
|
||
|
|
// The desktop app kills an update after this long; the benchmark reports each ref's headroom
|
||
|
|
// against it so a healthy run that approaches it is visible. The timeout itself lives in the app.
|
||
|
|
export const DESKTOP_APP_TIMEOUT_MS = 300000;
|
||
|
|
|
||
|
|
export function desktopTimeoutHeadroom(totalMs, limitMs = DESKTOP_APP_TIMEOUT_MS) {
|
||
|
|
const max = totalMs && typeof totalMs.max === "number" ? totalMs.max : null;
|
||
|
|
if (max === null) return { limitMs, maxTotalMs: null, headroomMs: null, exceeded: null };
|
||
|
|
return { limitMs, maxTotalMs: max, headroomMs: Math.round(limitMs - max), exceeded: max >= limitMs };
|
||
|
|
}
|
||
|
|
|
||
|
|
export const PHASES = ["bootstrap", "skills", "console", "canonical", "link-refresh", "pieces"];
|
||
|
|
|
||
|
|
export const MODE_BEHAVIOR = {
|
||
|
|
"cold-npx": "fresh isolated HOME and npm cache per timed run; the cache is cleared immediately before timing",
|
||
|
|
"warm-npx": "one untimed warm-up per ref primes the npm cache shared by that ref's timed runs, but uses a separate warm-up HOME; every timed HOME is fresh",
|
||
|
|
"warm-canonical": "one untimed warm-up per ref reuses the same isolated HOME and npm cache; every timed run is a repeated update against that HOME",
|
||
|
|
};
|
||
|
|
|
||
|
|
const VALUE_FLAGS = new Set(["baseline", "candidate", "mode", "runs", "json", "workdir", "repo-url"]);
|
||
|
|
const BOOLEAN_FLAGS = new Set(["keep-workdirs", "help"]);
|
||
|
|
const EXPECTED_EVENTS = [
|
||
|
|
"bootstrap-start",
|
||
|
|
"installer-start",
|
||
|
|
"installer-end",
|
||
|
|
"skills-built",
|
||
|
|
"console-staged",
|
||
|
|
"console-committed",
|
||
|
|
"canonical-staged",
|
||
|
|
"canonical-committed",
|
||
|
|
"retired-removed",
|
||
|
|
"links-refreshed",
|
||
|
|
"piece-installed",
|
||
|
|
];
|
||
|
|
|
||
|
|
const CONTROLLED_ENV = [
|
||
|
|
"HOME",
|
||
|
|
"USERPROFILE",
|
||
|
|
"npm_config_prefix",
|
||
|
|
"npm_config_cache",
|
||
|
|
"PLAN2CODE_CONSOLE_HOME",
|
||
|
|
"PLAN2CODE_BENCH_JSON",
|
||
|
|
"PLAN2CODE_BENCH_MODE",
|
||
|
|
"PLAN2CODE_INSTALL_REF",
|
||
|
|
"APPDATA",
|
||
|
|
"LOCALAPPDATA",
|
||
|
|
"XDG_CONFIG_HOME",
|
||
|
|
// Repo-local git state and inline git config must never leak into a child
|
||
|
|
// benchmark. Credential helpers and SSH agent variables stay inherited on
|
||
|
|
// purpose: a benchmark of a private fork needs the person's normal auth.
|
||
|
|
"GIT_DIR",
|
||
|
|
"GIT_WORK_TREE",
|
||
|
|
"GIT_INDEX_FILE",
|
||
|
|
"GIT_CONFIG",
|
||
|
|
"GIT_CONFIG_COUNT",
|
||
|
|
"GIT_CONFIG_PARAMETERS",
|
||
|
|
"npm_config_userconfig",
|
||
|
|
"NPM_CONFIG_USERCONFIG",
|
||
|
|
];
|
||
|
|
|
||
|
|
export function usage() {
|
||
|
|
return `Usage: node scripts/bench-install-update.mjs --mode cold-npx|warm-npx|warm-canonical \\
|
||
|
|
[--baseline <ref>] [--candidate <ref>] [--runs <n>] [--json <path>] [--workdir <path>] [--repo-url <url>] [--keep-workdirs]
|
||
|
|
|
||
|
|
Dev-only benchmark. At least one of --baseline or --candidate is required.
|
||
|
|
--runs defaults to 3. Refs use letters, digits, slash, dot, dash and underscore only.
|
||
|
|
|
||
|
|
Modes:
|
||
|
|
cold-npx ${MODE_BEHAVIOR["cold-npx"]}
|
||
|
|
warm-npx ${MODE_BEHAVIOR["warm-npx"]}
|
||
|
|
warm-canonical ${MODE_BEHAVIOR["warm-canonical"]}`;
|
||
|
|
}
|
||
|
|
|
||
|
|
function fail(message) {
|
||
|
|
return { ok: false, error: message };
|
||
|
|
}
|
||
|
|
|
||
|
|
function validRef(ref) {
|
||
|
|
// Windows runs npx through the shell. This intentionally accepts the normal
|
||
|
|
// branch/tag/sha alphabet and excludes shell metacharacters, whitespace and
|
||
|
|
// '#' rather than trying to make cmd.exe quoting safe for every byte git
|
||
|
|
// might theoretically permit in a ref.
|
||
|
|
return typeof ref === "string" && /^[A-Za-z0-9_][A-Za-z0-9._/-]{0,199}$/.test(ref) && !ref.includes("..") && !ref.includes("//");
|
||
|
|
}
|
||
|
|
|
||
|
|
export function parseArgs(argv) {
|
||
|
|
const options = { runs: 3, keepWorkdirs: false };
|
||
|
|
for (let i = 0; i < argv.length; i++) {
|
||
|
|
const arg = argv[i];
|
||
|
|
if (!arg.startsWith("--")) return fail(`Unexpected argument: ${arg}`);
|
||
|
|
const name = arg.slice(2);
|
||
|
|
if (BOOLEAN_FLAGS.has(name)) {
|
||
|
|
options[toCamel(name)] = true;
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if (!VALUE_FLAGS.has(name)) return fail(`Unknown flag: --${name}`);
|
||
|
|
const value = argv[i + 1];
|
||
|
|
if (value === undefined || value.startsWith("--")) return fail(`Missing value for --${name}`);
|
||
|
|
options[toCamel(name)] = value;
|
||
|
|
i++;
|
||
|
|
}
|
||
|
|
if (options.help) return { ok: true, help: true, options };
|
||
|
|
if (!options.mode) return fail("Missing required --mode cold-npx|warm-npx|warm-canonical");
|
||
|
|
if (!MODES.includes(options.mode)) return fail(`Unknown mode: ${options.mode}`);
|
||
|
|
if (!options.baseline && !options.candidate) return fail("At least one of --baseline or --candidate is required");
|
||
|
|
for (const [label, ref] of [
|
||
|
|
["baseline", options.baseline],
|
||
|
|
["candidate", options.candidate],
|
||
|
|
]) {
|
||
|
|
if (ref && !validRef(ref)) return fail(`Unsafe or unsupported ${label} ref: ${ref}`);
|
||
|
|
}
|
||
|
|
const runs = Number(options.runs);
|
||
|
|
if (!Number.isInteger(runs) || runs < 1) return fail("--runs must be a positive integer");
|
||
|
|
options.runs = runs;
|
||
|
|
options.refs = [];
|
||
|
|
if (options.baseline) options.refs.push({ label: "baseline", ref: options.baseline });
|
||
|
|
if (options.candidate) options.refs.push({ label: "candidate", ref: options.candidate });
|
||
|
|
return { ok: true, options };
|
||
|
|
}
|
||
|
|
|
||
|
|
function toCamel(flag) {
|
||
|
|
return flag.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
|
||
|
|
}
|
||
|
|
|
||
|
|
function normalizeForCompare(value) {
|
||
|
|
let normalized = path.resolve(String(value));
|
||
|
|
while (normalized.length > path.parse(normalized).root.length && /[\\/]$/.test(normalized)) normalized = normalized.slice(0, -1);
|
||
|
|
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
|
||
|
|
}
|
||
|
|
|
||
|
|
function samePath(a, b) {
|
||
|
|
return normalizeForCompare(a) === normalizeForCompare(b);
|
||
|
|
}
|
||
|
|
|
||
|
|
function uniquePaths(values) {
|
||
|
|
const seen = new Set();
|
||
|
|
const out = [];
|
||
|
|
for (const value of values.flat()) {
|
||
|
|
if (!value || typeof value !== "string") continue;
|
||
|
|
const key = normalizeForCompare(value);
|
||
|
|
if (!seen.has(key)) {
|
||
|
|
seen.add(key);
|
||
|
|
out.push(value);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function realInstallPaths(env = process.env) {
|
||
|
|
const home = env.HOME || env.USERPROFILE || os.homedir();
|
||
|
|
const appData = env.APPDATA || (home ? path.join(home, "AppData", "Roaming") : null);
|
||
|
|
const localAppData = env.LOCALAPPDATA || (home ? path.join(home, "AppData", "Local") : null);
|
||
|
|
return {
|
||
|
|
home: uniquePaths([os.homedir(), env.HOME, env.USERPROFILE]),
|
||
|
|
npmPrefix: uniquePaths([
|
||
|
|
env.npm_config_prefix,
|
||
|
|
env.NPM_CONFIG_PREFIX,
|
||
|
|
process.platform === "win32" && appData ? path.join(appData, "npm") : "/usr/local",
|
||
|
|
]),
|
||
|
|
npmCache: uniquePaths([
|
||
|
|
env.npm_config_cache,
|
||
|
|
env.NPM_CONFIG_CACHE,
|
||
|
|
process.platform === "win32" && localAppData ? path.join(localAppData, "npm-cache") : home ? path.join(home, ".npm") : null,
|
||
|
|
]),
|
||
|
|
consoleHome: uniquePaths([env.PLAN2CODE_CONSOLE_HOME, home ? path.join(home, ".plan2code", "console") : null]),
|
||
|
|
appData: uniquePaths([env.APPDATA, env.LOCALAPPDATA, env.XDG_CONFIG_HOME]),
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export function isolationErrors(env, real = realInstallPaths(), { boundaryRoot = null } = {}) {
|
||
|
|
const errors = [];
|
||
|
|
const required = [
|
||
|
|
"HOME",
|
||
|
|
"USERPROFILE",
|
||
|
|
"npm_config_prefix",
|
||
|
|
"npm_config_cache",
|
||
|
|
"PLAN2CODE_CONSOLE_HOME",
|
||
|
|
"PLAN2CODE_BENCH_JSON",
|
||
|
|
"APPDATA",
|
||
|
|
"LOCALAPPDATA",
|
||
|
|
"XDG_CONFIG_HOME",
|
||
|
|
];
|
||
|
|
for (const key of required) {
|
||
|
|
if (!env[key]) errors.push(`${key} is missing`);
|
||
|
|
else if (!path.isAbsolute(env[key])) errors.push(`${key} is not absolute: ${env[key]}`);
|
||
|
|
}
|
||
|
|
if (errors.length) return errors;
|
||
|
|
|
||
|
|
const sensitive = [
|
||
|
|
...(real.home || []).map((p) => ["real home", p]),
|
||
|
|
...(real.npmPrefix || []).map((p) => ["real npm prefix", p]),
|
||
|
|
...(real.npmCache || []).map((p) => ["real npm cache", p]),
|
||
|
|
...(real.consoleHome || []).map((p) => ["real console home", p]),
|
||
|
|
...(real.appData || []).map((p) => ["real application-data path", p]),
|
||
|
|
];
|
||
|
|
for (const key of required) {
|
||
|
|
for (const [label, realPath] of sensitive) {
|
||
|
|
if (samePath(env[key], realPath)) errors.push(`${key} equals the ${label}: ${env[key]}`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (boundaryRoot) {
|
||
|
|
const root = normalizeForCompare(boundaryRoot);
|
||
|
|
for (const key of required) {
|
||
|
|
const value = normalizeForCompare(env[key]);
|
||
|
|
const relative = path.relative(root, value);
|
||
|
|
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) errors.push(`${key} is outside the benchmark work root: ${env[key]}`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return [...new Set(errors)];
|
||
|
|
}
|
||
|
|
|
||
|
|
export function assertIsolatedEnvironment(env, real, options) {
|
||
|
|
const errors = isolationErrors(env, real, options);
|
||
|
|
if (errors.length) {
|
||
|
|
const error = new Error(`Refusing to benchmark outside an isolated environment:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
|
||
|
|
error.isolationFailure = true;
|
||
|
|
throw error;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function mkdirs(paths) {
|
||
|
|
for (const dir of paths) fs.mkdirSync(dir, { recursive: true });
|
||
|
|
}
|
||
|
|
|
||
|
|
export function createIsolatedEnvironment({ root, cachePath = null, cacheDescription = "<shared with the timed run>", benchJsonName = path.join("timing", "events.jsonl"), stdoutName = path.join("logs", "stdout.log"), stderrName = path.join("logs", "stderr.log") }) {
|
||
|
|
const home = path.join(root, "home");
|
||
|
|
const npmPrefix = path.join(root, "npm-prefix");
|
||
|
|
const npmCache = cachePath || path.join(root, "npm-cache");
|
||
|
|
const consoleHome = path.join(root, "console-home");
|
||
|
|
const appData = path.join(root, "app-data", "roaming");
|
||
|
|
const localAppData = path.join(root, "app-data", "local");
|
||
|
|
const xdgConfigHome = path.join(root, "xdg-config");
|
||
|
|
const benchJson = path.join(root, benchJsonName);
|
||
|
|
const stdoutLog = path.join(root, stdoutName);
|
||
|
|
const stderrLog = path.join(root, stderrName);
|
||
|
|
mkdirs([home, npmPrefix, npmCache, consoleHome, appData, localAppData, xdgConfigHome, path.dirname(benchJson), path.dirname(stdoutLog), path.dirname(stderrLog)]);
|
||
|
|
|
||
|
|
const paths = { root, home, npmPrefix, npmCache, consoleHome, appData, localAppData, xdgConfigHome, benchJson, stdoutLog, stderrLog };
|
||
|
|
const env = {
|
||
|
|
HOME: home,
|
||
|
|
USERPROFILE: home,
|
||
|
|
npm_config_prefix: npmPrefix,
|
||
|
|
npm_config_cache: npmCache,
|
||
|
|
PLAN2CODE_CONSOLE_HOME: consoleHome,
|
||
|
|
PLAN2CODE_BENCH_JSON: benchJson,
|
||
|
|
// Set all three on every platform. Windows installers read the first two,
|
||
|
|
// Linux tools read the XDG path, and cross-platform tools may read either;
|
||
|
|
// keeping all of them inside the temp tree is stronger isolation.
|
||
|
|
APPDATA: appData,
|
||
|
|
LOCALAPPDATA: localAppData,
|
||
|
|
XDG_CONFIG_HOME: xdgConfigHome,
|
||
|
|
};
|
||
|
|
const layout = {
|
||
|
|
home: "home/",
|
||
|
|
npmPrefix: "npm-prefix/",
|
||
|
|
npmCache: cachePath ? cacheDescription : "npm-cache/",
|
||
|
|
consoleHome: "console-home/",
|
||
|
|
appData: "app-data/roaming/",
|
||
|
|
localAppData: "app-data/local/",
|
||
|
|
xdgConfigHome: "xdg-config/",
|
||
|
|
benchJson: benchJsonName.split(path.sep).join("/"),
|
||
|
|
stdoutLog: stdoutName.split(path.sep).join("/"),
|
||
|
|
stderrLog: stderrName.split(path.sep).join("/"),
|
||
|
|
};
|
||
|
|
return { root, paths, env, layout };
|
||
|
|
}
|
||
|
|
|
||
|
|
export function childProcessEnvironment(overrides, base = process.env) {
|
||
|
|
const controlled = new Set(CONTROLLED_ENV.map((key) => key.toLowerCase()));
|
||
|
|
const env = {};
|
||
|
|
for (const [key, value] of Object.entries(base)) {
|
||
|
|
const upper = key.toUpperCase();
|
||
|
|
if (!controlled.has(key.toLowerCase()) && !/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(upper)) env[key] = value;
|
||
|
|
}
|
||
|
|
return { ...env, ...overrides };
|
||
|
|
}
|
||
|
|
|
||
|
|
function safePart(text) {
|
||
|
|
return String(text).replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 60) || "ref";
|
||
|
|
}
|
||
|
|
|
||
|
|
export function createWorkspace(workdir = null) {
|
||
|
|
if (workdir) {
|
||
|
|
const parent = path.resolve(workdir);
|
||
|
|
fs.mkdirSync(parent, { recursive: true });
|
||
|
|
return { parent, root: fs.mkdtempSync(path.join(parent, "install-bench-")) };
|
||
|
|
}
|
||
|
|
return { parent: os.tmpdir(), root: fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-bench-")) };
|
||
|
|
}
|
||
|
|
|
||
|
|
export function buildNpxInvocation(ref, repoUrl = "https://github.com/jparkerweb/plan2code.git") {
|
||
|
|
if (!validRef(ref)) throw new Error(`Unsafe or unsupported ref: ${ref}`);
|
||
|
|
const args = ["--yes", "--allow-git=all", `git+${repoUrl}#${ref}`, "--update", "--force"];
|
||
|
|
const windows = process.platform === "win32";
|
||
|
|
// Modern Node refuses to spawn a .cmd directly without a shell, while
|
||
|
|
// shell:true concatenates arguments and warns. executeNpx invokes cmd.exe
|
||
|
|
// explicitly on Windows; the invocation shape here remains the logical npx
|
||
|
|
// command the benchmark is measuring. The strict ref alphabet above keeps
|
||
|
|
// the fixed command line free of cmd metacharacters.
|
||
|
|
return {
|
||
|
|
command: windows ? "npx.cmd" : "npx",
|
||
|
|
args,
|
||
|
|
shell: false,
|
||
|
|
argv: [windows ? "npx.cmd" : "npx", ...args],
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
const SECRET_ENV_NAME = /(?:TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|\bKEY\b)/i;
|
||
|
|
|
||
|
|
function secretValues(env) {
|
||
|
|
return Object.entries(env)
|
||
|
|
.filter(([key, value]) => SECRET_ENV_NAME.test(key) && typeof value === "string" && value.length >= 1)
|
||
|
|
.map(([, value]) => value)
|
||
|
|
.sort((a, b) => b.length - a.length)
|
||
|
|
.slice(0, 100);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function redactSecrets(text, secrets = []) {
|
||
|
|
let out = String(text ?? "");
|
||
|
|
out = out.replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{8,}\b/g, "<redacted-token>");
|
||
|
|
out = out.replace(/\bgithub_pat_[A-Za-z0-9_]{8,}\b/g, "<redacted-token>");
|
||
|
|
out = out.replace(/\b(x-access-token:)[^\s/@]+@/gi, "$1<redacted>@");
|
||
|
|
out = out.replace(/\b(https?:\/\/[^\s/@:]+:)[^\s/@]+@/gi, "$1<redacted>@");
|
||
|
|
out = out.replace(/^(\s*(?:username|user|password|pass|token|secret)\s*[=:]\s*)\S+.*$/gim, "$1<redacted>");
|
||
|
|
out = out.replace(/\b((?:access_token|token|password|secret)=)[^\s&]+/gi, "$1<redacted>");
|
||
|
|
out = out.replace(/\b(authorization:\s*(?:basic|bearer)\s+)\S+/gi, "$1<redacted>");
|
||
|
|
for (const secret of secrets) {
|
||
|
|
if (secret) out = out.split(secret).join("<redacted>");
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function sanitizeArgv(argv, env = process.env) {
|
||
|
|
const secrets = secretValues(env);
|
||
|
|
return argv.map((arg) => redactSecrets(arg, secrets));
|
||
|
|
}
|
||
|
|
|
||
|
|
function writeSanitizedLog(file, text, env) {
|
||
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||
|
|
fs.writeFileSync(file, redactSecrets(text, secretValues(env)), "utf8");
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function executeNpx({ command, args, shell, cwd, env, stdoutLog, stderrLog }, spawnImpl = spawn) {
|
||
|
|
return new Promise((resolve) => {
|
||
|
|
let child;
|
||
|
|
try {
|
||
|
|
const windowsNpx = process.platform === "win32" && command.toLowerCase() === "npx.cmd";
|
||
|
|
const spawnCommand = windowsNpx ? process.env.ComSpec || "cmd.exe" : command;
|
||
|
|
const spawnArgs = windowsNpx ? ["/d", "/s", "/c", command, ...args] : args;
|
||
|
|
child = spawnImpl(spawnCommand, spawnArgs, { cwd, env, shell, stdio: ["ignore", "pipe", "pipe"] });
|
||
|
|
} catch (error) {
|
||
|
|
writeSanitizedLog(stdoutLog, "", env);
|
||
|
|
writeSanitizedLog(stderrLog, error.stack || error.message, env);
|
||
|
|
resolve({ exitCode: null, signal: null, error: error.message, endedMs: Date.now() });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
let stdout = "";
|
||
|
|
let stderr = "";
|
||
|
|
let settled = false;
|
||
|
|
const finish = (result) => {
|
||
|
|
if (settled) return;
|
||
|
|
settled = true;
|
||
|
|
// The clock stops when npx closes; sanitizing and writing the logs is
|
||
|
|
// harness overhead, not installer time.
|
||
|
|
const endedMs = Date.now();
|
||
|
|
writeSanitizedLog(stdoutLog, stdout, env);
|
||
|
|
writeSanitizedLog(stderrLog, stderr + (result.error ? `${stderr ? "\n" : ""}${result.error}\n` : ""), env);
|
||
|
|
resolve({ ...result, endedMs });
|
||
|
|
};
|
||
|
|
child.stdout?.on("data", (chunk) => (stdout += chunk));
|
||
|
|
child.stderr?.on("data", (chunk) => (stderr += chunk));
|
||
|
|
child.once("error", (error) => finish({ exitCode: null, signal: null, error: error.message }));
|
||
|
|
child.once("close", (exitCode, signal) => finish({ exitCode, signal, error: null }));
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
function eventAt(event) {
|
||
|
|
const ms = Date.parse(event?.at || "");
|
||
|
|
return Number.isFinite(ms) ? ms : null;
|
||
|
|
}
|
||
|
|
|
||
|
|
function eventsNamed(events, name) {
|
||
|
|
return events.filter((event) => event && event.event === name);
|
||
|
|
}
|
||
|
|
|
||
|
|
function firstEvent(events, name) {
|
||
|
|
return eventsNamed(events, name)[0] || null;
|
||
|
|
}
|
||
|
|
|
||
|
|
function lastEvent(events, name) {
|
||
|
|
const matches = eventsNamed(events, name);
|
||
|
|
return matches[matches.length - 1] || null;
|
||
|
|
}
|
||
|
|
|
||
|
|
function numericDuration(event) {
|
||
|
|
return event && typeof event.durationMs === "number" && Number.isFinite(event.durationMs) ? event.durationMs : null;
|
||
|
|
}
|
||
|
|
|
||
|
|
function roundMs(value) {
|
||
|
|
return typeof value === "number" && Number.isFinite(value) ? Math.round(value * 1000) / 1000 : null;
|
||
|
|
}
|
||
|
|
|
||
|
|
function spanMs(startEvent, endEvent) {
|
||
|
|
const start = eventAt(startEvent);
|
||
|
|
const end = eventAt(endEvent);
|
||
|
|
if (start === null || end === null) return null;
|
||
|
|
return Math.max(0, end - start);
|
||
|
|
}
|
||
|
|
|
||
|
|
function directOrSpan(events, durationName, startName, endName) {
|
||
|
|
const direct = numericDuration(lastEvent(events, durationName));
|
||
|
|
if (direct !== null) return direct;
|
||
|
|
return spanMs(firstEvent(events, startName), lastEvent(events, endName));
|
||
|
|
}
|
||
|
|
|
||
|
|
export function summarizeEvents(events, { startedAt = null } = {}) {
|
||
|
|
// Prefer the durationMs stamped by the installer at a phase's completion
|
||
|
|
// boundary. For older refs whose events are point-in-time only, fall back
|
||
|
|
// to the closest timestamp span. Missing data stays null; it is evidence
|
||
|
|
// about that ref, not a benchmark failure.
|
||
|
|
const valid = (events || []).filter((event) => event && typeof event === "object" && typeof event.event === "string");
|
||
|
|
const counts = {};
|
||
|
|
for (const event of valid) counts[event.event] = (counts[event.event] || 0) + 1;
|
||
|
|
|
||
|
|
const childStart = typeof startedAt === "number" ? startedAt : Date.parse(startedAt || "");
|
||
|
|
const bootstrapEnd = firstEvent(valid, "bootstrap-start") || firstEvent(valid, "installer-start");
|
||
|
|
const bootstrap = Number.isFinite(childStart) && eventAt(bootstrapEnd) !== null ? Math.max(0, eventAt(bootstrapEnd) - childStart) : null;
|
||
|
|
|
||
|
|
const pieceEvents = eventsNamed(valid, "piece-installed");
|
||
|
|
const pieceTotals = {};
|
||
|
|
let piecesTotal = 0;
|
||
|
|
let anyPieceDuration = false;
|
||
|
|
for (const event of pieceEvents) {
|
||
|
|
const piece = event.piece || "<unknown>";
|
||
|
|
const duration = numericDuration(event);
|
||
|
|
if (!pieceTotals[piece]) pieceTotals[piece] = { totalMs: 0, count: 0, results: [] };
|
||
|
|
pieceTotals[piece].count++;
|
||
|
|
if (event.result !== undefined) pieceTotals[piece].results.push(event.result);
|
||
|
|
if (duration !== null) {
|
||
|
|
pieceTotals[piece].totalMs += duration;
|
||
|
|
piecesTotal += duration;
|
||
|
|
anyPieceDuration = true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
for (const piece of Object.values(pieceTotals)) piece.totalMs = roundMs(piece.totalMs);
|
||
|
|
|
||
|
|
const piecesFallback = spanMs(lastEvent(valid, "links-refreshed"), lastEvent(valid, "installer-end"));
|
||
|
|
const redirectDuration = numericDuration(lastEvent(valid, "redirect-end"));
|
||
|
|
const retiredDuration = numericDuration(lastEvent(valid, "retired-removed"));
|
||
|
|
const installerDuration = numericDuration(lastEvent(valid, "installer-end"));
|
||
|
|
const firstAt = valid.map(eventAt).filter((v) => v !== null).sort((a, b) => a - b)[0] ?? null;
|
||
|
|
const lastAt = valid.map(eventAt).filter((v) => v !== null).sort((a, b) => a - b).at(-1) ?? null;
|
||
|
|
|
||
|
|
const phases = {
|
||
|
|
bootstrap: roundMs(bootstrap),
|
||
|
|
skills: roundMs(directOrSpan(valid, "skills-built", "installer-start", "skills-built")),
|
||
|
|
console: roundMs(directOrSpan(valid, "console-committed", "console-staged", "console-committed")),
|
||
|
|
canonical: roundMs(directOrSpan(valid, "canonical-committed", "canonical-staged", "canonical-committed")),
|
||
|
|
"link-refresh": roundMs(directOrSpan(valid, "links-refreshed", "retired-removed", "links-refreshed")),
|
||
|
|
pieces: roundMs(anyPieceDuration ? piecesTotal : piecesFallback),
|
||
|
|
};
|
||
|
|
|
||
|
|
return {
|
||
|
|
phases,
|
||
|
|
pieces: pieceTotals,
|
||
|
|
eventCount: valid.length,
|
||
|
|
eventCounts: Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b))),
|
||
|
|
missingEvents: EXPECTED_EVENTS.filter((name) => !counts[name]),
|
||
|
|
firstEventAt: firstAt === null ? null : new Date(firstAt).toISOString(),
|
||
|
|
lastEventAt: lastAt === null ? null : new Date(lastAt).toISOString(),
|
||
|
|
eventSpanMs: firstAt === null || lastAt === null ? null : roundMs(Math.max(0, lastAt - firstAt)),
|
||
|
|
installerMs: roundMs(installerDuration),
|
||
|
|
extraPhases: {
|
||
|
|
redirect: roundMs(redirectDuration),
|
||
|
|
"retired-removal": roundMs(retiredDuration),
|
||
|
|
},
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export function stats(values) {
|
||
|
|
const nums = (values || []).filter((value) => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b);
|
||
|
|
if (!nums.length) return null;
|
||
|
|
const middle = Math.floor(nums.length / 2);
|
||
|
|
const median = nums.length % 2 ? nums[middle] : (nums[middle - 1] + nums[middle]) / 2;
|
||
|
|
return { median: roundMs(median), min: roundMs(nums[0]), max: roundMs(nums[nums.length - 1]), count: nums.length };
|
||
|
|
}
|
||
|
|
|
||
|
|
export function summarizeRuns(runs) {
|
||
|
|
const groups = new Map();
|
||
|
|
for (const run of runs || []) {
|
||
|
|
const key = `${run.ref}\u0000${run.mode}`;
|
||
|
|
if (!groups.has(key)) groups.set(key, { ref: run.ref, mode: run.mode, labels: new Set(), runs: [] });
|
||
|
|
const group = groups.get(key);
|
||
|
|
group.labels.add(run.label);
|
||
|
|
group.runs.push(run);
|
||
|
|
}
|
||
|
|
return [...groups.values()].map((group) => {
|
||
|
|
const rows = group.runs;
|
||
|
|
const pieceNames = [...new Set(rows.flatMap((run) => Object.keys(run.pieceTotals || {})))].sort();
|
||
|
|
const exitCodes = {};
|
||
|
|
for (const run of rows) exitCodes[String(run.exitCode)] = (exitCodes[String(run.exitCode)] || 0) + 1;
|
||
|
|
return {
|
||
|
|
ref: group.ref,
|
||
|
|
mode: group.mode,
|
||
|
|
labels: [...group.labels].sort(),
|
||
|
|
runs: rows.length,
|
||
|
|
exitCodes,
|
||
|
|
nonZeroExitRuns: rows.filter((run) => run.exitCode !== 0).length,
|
||
|
|
missingJsonlRuns: rows.filter((run) => !run.hasTimingJson).length,
|
||
|
|
totalMs: stats(rows.map((run) => run.totalMs)),
|
||
|
|
desktopTimeout: desktopTimeoutHeadroom(stats(rows.map((run) => run.totalMs))),
|
||
|
|
installerMs: stats(rows.map((run) => run.installerMs)),
|
||
|
|
eventCount: stats(rows.map((run) => run.eventCount)),
|
||
|
|
phases: Object.fromEntries(PHASES.map((phase) => [phase, stats(rows.map((run) => run.phases?.[phase]))])),
|
||
|
|
pieces: Object.fromEntries(pieceNames.map((piece) => [piece, stats(rows.map((run) => run.pieceTotals?.[piece]?.totalMs))])),
|
||
|
|
};
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
function environmentRecord({ kind, runId, label, ref, mode, runIndex, isolated, reuse }) {
|
||
|
|
return {
|
||
|
|
kind,
|
||
|
|
runId,
|
||
|
|
label,
|
||
|
|
ref,
|
||
|
|
mode,
|
||
|
|
runIndex,
|
||
|
|
tempRoot: isolated.root,
|
||
|
|
layout: isolated.layout,
|
||
|
|
variables: { ...isolated.env, PLAN2CODE_BENCH_MODE: mode, PLAN2CODE_INSTALL_REF: ref },
|
||
|
|
paths: isolated.paths,
|
||
|
|
reuse,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
function canonicalWarmupEnvironment(timed) {
|
||
|
|
const benchJson = path.join(timed.root, "timing", "warmup-events.jsonl");
|
||
|
|
const stdoutLog = path.join(timed.root, "logs", "warmup.stdout.log");
|
||
|
|
const stderrLog = path.join(timed.root, "logs", "warmup.stderr.log");
|
||
|
|
mkdirs([path.dirname(benchJson), path.dirname(stdoutLog)]);
|
||
|
|
return {
|
||
|
|
root: timed.root,
|
||
|
|
paths: { ...timed.paths, benchJson, stdoutLog, stderrLog },
|
||
|
|
env: { ...timed.env, PLAN2CODE_BENCH_JSON: benchJson },
|
||
|
|
layout: { ...timed.layout, benchJson: "timing/warmup-events.jsonl", stdoutLog: "logs/warmup.stdout.log", stderrLog: "logs/warmup.stderr.log" },
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
function canonicalTimedEnvironment(shared, runIndex) {
|
||
|
|
const benchJson = path.join(shared.root, "timing", `run-${runIndex}-events.jsonl`);
|
||
|
|
const stdoutLog = path.join(shared.root, "logs", `run-${runIndex}.stdout.log`);
|
||
|
|
const stderrLog = path.join(shared.root, "logs", `run-${runIndex}.stderr.log`);
|
||
|
|
mkdirs([path.dirname(benchJson), path.dirname(stdoutLog)]);
|
||
|
|
return {
|
||
|
|
root: shared.root,
|
||
|
|
paths: { ...shared.paths, benchJson, stdoutLog, stderrLog },
|
||
|
|
env: { ...shared.env, PLAN2CODE_BENCH_JSON: benchJson },
|
||
|
|
layout: {
|
||
|
|
...shared.layout,
|
||
|
|
benchJson: `timing/run-${runIndex}-events.jsonl`,
|
||
|
|
stdoutLog: `logs/run-${runIndex}.stdout.log`,
|
||
|
|
stderrLog: `logs/run-${runIndex}.stderr.log`,
|
||
|
|
},
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
async function executeIsolated({ execute, target, mode, isolated, boundaryRoot, realPaths, repoUrl }) {
|
||
|
|
const invocation = buildNpxInvocation(target.ref, repoUrl);
|
||
|
|
const env = childProcessEnvironment({
|
||
|
|
...isolated.env,
|
||
|
|
PLAN2CODE_BENCH_MODE: mode,
|
||
|
|
// The ref is intentional: exact benchmark refs must not be silently
|
||
|
|
// redirected to another release, and the installer timing seam uses this
|
||
|
|
// variable to stamp the ref onto every JSONL event.
|
||
|
|
PLAN2CODE_INSTALL_REF: target.ref,
|
||
|
|
});
|
||
|
|
assertIsolatedEnvironment(env, realPaths, { boundaryRoot });
|
||
|
|
const startedMs = Date.now();
|
||
|
|
const startedAt = new Date(startedMs).toISOString();
|
||
|
|
let outcome;
|
||
|
|
try {
|
||
|
|
outcome = await execute({
|
||
|
|
command: invocation.command,
|
||
|
|
args: invocation.args,
|
||
|
|
shell: invocation.shell,
|
||
|
|
cwd: isolated.paths.home,
|
||
|
|
env,
|
||
|
|
stdoutLog: isolated.paths.stdoutLog,
|
||
|
|
stderrLog: isolated.paths.stderrLog,
|
||
|
|
timingPath: isolated.paths.benchJson,
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
outcome = { exitCode: null, signal: null, error: error.message };
|
||
|
|
}
|
||
|
|
const measuredEndMs = typeof outcome?.endedMs === "number" && Number.isFinite(outcome.endedMs) ? outcome.endedMs : Date.now();
|
||
|
|
return {
|
||
|
|
argv: sanitizeArgv(invocation.argv, env),
|
||
|
|
cwd: isolated.paths.home,
|
||
|
|
startedAt,
|
||
|
|
endedAt: new Date(measuredEndMs).toISOString(),
|
||
|
|
startedMs,
|
||
|
|
totalMs: roundMs(measuredEndMs - startedMs),
|
||
|
|
exitCode: outcome?.exitCode ?? outcome?.code ?? outcome?.status ?? null,
|
||
|
|
signal: outcome?.signal ?? null,
|
||
|
|
spawnError: redactSecrets(outcome?.error || "", secretValues(env)) || null,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
function normalizeRunOptions(options) {
|
||
|
|
const refs = options.refs || [
|
||
|
|
...(options.baseline ? [{ label: "baseline", ref: options.baseline }] : []),
|
||
|
|
...(options.candidate ? [{ label: "candidate", ref: options.candidate }] : []),
|
||
|
|
];
|
||
|
|
return {
|
||
|
|
refs,
|
||
|
|
mode: options.mode,
|
||
|
|
runs: options.runs ?? 3,
|
||
|
|
workdir: options.workdir || null,
|
||
|
|
repoUrl: options.repoUrl || undefined,
|
||
|
|
keepWorkdirs: Boolean(options.keepWorkdirs),
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function runBenchmark(rawOptions, { execute = executeNpx, realPaths = realInstallPaths(), workspace = null } = {}) {
|
||
|
|
const options = normalizeRunOptions(rawOptions);
|
||
|
|
if (!MODES.includes(options.mode)) throw new Error(`Unknown mode: ${options.mode}`);
|
||
|
|
if (!options.refs.length) throw new Error("At least one ref is required");
|
||
|
|
if (!Number.isInteger(options.runs) || options.runs < 1) throw new Error("runs must be a positive integer");
|
||
|
|
|
||
|
|
const space = workspace || createWorkspace(options.workdir);
|
||
|
|
const report = {
|
||
|
|
generatedAt: new Date().toISOString(),
|
||
|
|
mode: options.mode,
|
||
|
|
modeBehavior: MODE_BEHAVIOR[options.mode],
|
||
|
|
repoUrl: options.repoUrl || "https://github.com/jparkerweb/plan2code.git",
|
||
|
|
runs: [],
|
||
|
|
warmups: [],
|
||
|
|
summary: [],
|
||
|
|
environments: [],
|
||
|
|
};
|
||
|
|
|
||
|
|
for (const [targetIndex, target] of options.refs.entries()) {
|
||
|
|
const targetId = `${targetIndex + 1}-${target.label}-${safePart(target.ref)}`;
|
||
|
|
let sharedCachePath = null;
|
||
|
|
let sharedCanonical = null;
|
||
|
|
|
||
|
|
// Warm modes get exactly one untimed warm-up per ref, before that ref's
|
||
|
|
// timed repetitions. warm-npx shares only the npm cache with timed runs;
|
||
|
|
// warm-canonical shares the whole isolated install state.
|
||
|
|
if (options.mode !== "cold-npx") {
|
||
|
|
const warmupId = `${targetId}-warmup`;
|
||
|
|
let warmup;
|
||
|
|
if (options.mode === "warm-npx") {
|
||
|
|
sharedCachePath = path.join(space.root, `${targetId}-shared-npm-cache`);
|
||
|
|
fs.mkdirSync(sharedCachePath, { recursive: true });
|
||
|
|
// Deliberate measurement choice: cache warmth yes, HOME/canonical
|
||
|
|
// state no. This keeps warm-npx distinct from warm-canonical.
|
||
|
|
warmup = createIsolatedEnvironment({
|
||
|
|
root: path.join(space.root, warmupId),
|
||
|
|
cachePath: sharedCachePath,
|
||
|
|
cacheDescription: "<shared warm-npx cache for this ref>",
|
||
|
|
});
|
||
|
|
} else {
|
||
|
|
sharedCanonical = createIsolatedEnvironment({ root: path.join(space.root, `${targetId}-canonical-home`) });
|
||
|
|
sharedCachePath = sharedCanonical.paths.npmCache;
|
||
|
|
warmup = canonicalWarmupEnvironment(sharedCanonical);
|
||
|
|
}
|
||
|
|
const warmReuse = {
|
||
|
|
warmsCacheForTimedRuns: true,
|
||
|
|
warmupHomeReusedByTimedRuns: options.mode === "warm-canonical",
|
||
|
|
oneWarmupPerRef: true,
|
||
|
|
};
|
||
|
|
report.environments.push(environmentRecord({ kind: "warmup", runId: warmupId, label: target.label, ref: target.ref, mode: options.mode, runIndex: null, isolated: warmup, reuse: warmReuse }));
|
||
|
|
const warmResult = await executeIsolated({ execute, target, mode: options.mode, isolated: warmup, boundaryRoot: space.root, realPaths, repoUrl: options.repoUrl });
|
||
|
|
report.warmups.push({
|
||
|
|
runId: warmupId,
|
||
|
|
label: target.label,
|
||
|
|
ref: target.ref,
|
||
|
|
mode: options.mode,
|
||
|
|
runIndex: null,
|
||
|
|
...warmResult,
|
||
|
|
stdoutLog: warmup.paths.stdoutLog,
|
||
|
|
stderrLog: warmup.paths.stderrLog,
|
||
|
|
timingJsonl: warmup.paths.benchJson,
|
||
|
|
timed: false,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
for (let runIndex = 1; runIndex <= options.runs; runIndex++) {
|
||
|
|
const runId = `${targetId}-run-${runIndex}`;
|
||
|
|
let timed;
|
||
|
|
const reuse = {
|
||
|
|
npmCacheFromWarmup: options.mode !== "cold-npx",
|
||
|
|
homeFromWarmup: options.mode === "warm-canonical",
|
||
|
|
cacheSharedAcrossTimedRuns: options.mode !== "cold-npx",
|
||
|
|
homeSharedAcrossTimedRuns: options.mode === "warm-canonical",
|
||
|
|
};
|
||
|
|
|
||
|
|
if (options.mode === "cold-npx") {
|
||
|
|
timed = createIsolatedEnvironment({ root: path.join(space.root, runId) });
|
||
|
|
fs.rmSync(timed.paths.npmCache, { recursive: true, force: true });
|
||
|
|
fs.mkdirSync(timed.paths.npmCache, { recursive: true });
|
||
|
|
} else if (options.mode === "warm-npx") {
|
||
|
|
timed = createIsolatedEnvironment({
|
||
|
|
root: path.join(space.root, runId),
|
||
|
|
cachePath: sharedCachePath,
|
||
|
|
cacheDescription: "<shared warm-npx cache for this ref>",
|
||
|
|
});
|
||
|
|
} else {
|
||
|
|
timed = canonicalTimedEnvironment(sharedCanonical, runIndex);
|
||
|
|
}
|
||
|
|
|
||
|
|
report.environments.push(environmentRecord({ kind: "timed", runId, label: target.label, ref: target.ref, mode: options.mode, runIndex, isolated: timed, reuse }));
|
||
|
|
const outcome = await executeIsolated({ execute, target, mode: options.mode, isolated: timed, boundaryRoot: space.root, realPaths, repoUrl: options.repoUrl });
|
||
|
|
const events = readTimingEvents(timed.paths.benchJson);
|
||
|
|
const eventSummary = summarizeEvents(events, { startedAt: outcome.startedMs });
|
||
|
|
const modeCounts = {
|
||
|
|
matching: events.filter((event) => event.mode === options.mode).length,
|
||
|
|
missing: events.filter((event) => event.mode === undefined).length,
|
||
|
|
mismatched: events.filter((event) => event.mode !== undefined && event.mode !== options.mode).length,
|
||
|
|
};
|
||
|
|
report.runs.push({
|
||
|
|
runId,
|
||
|
|
label: target.label,
|
||
|
|
ref: target.ref,
|
||
|
|
mode: options.mode,
|
||
|
|
runIndex,
|
||
|
|
...outcome,
|
||
|
|
stdoutLog: timed.paths.stdoutLog,
|
||
|
|
stderrLog: timed.paths.stderrLog,
|
||
|
|
timingJsonl: timed.paths.benchJson,
|
||
|
|
hasTimingJson: fs.existsSync(timed.paths.benchJson),
|
||
|
|
...eventSummary,
|
||
|
|
pieceTotals: eventSummary.pieces,
|
||
|
|
modeCounts,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
report.summary = summarizeRuns(report.runs);
|
||
|
|
return { report, workspace: space };
|
||
|
|
}
|
||
|
|
|
||
|
|
function formatStat(stat, unit = " ms") {
|
||
|
|
if (!stat) return "-";
|
||
|
|
return `${stat.median}${unit} median (min ${stat.min}${unit}, max ${stat.max}${unit})`;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function printReport(report, log = console.log) {
|
||
|
|
log(`install/update benchmark, mode=${report.mode}`);
|
||
|
|
log(`mode behavior: ${report.modeBehavior}`);
|
||
|
|
for (const row of report.summary) {
|
||
|
|
log("");
|
||
|
|
log(`${row.labels.join("+")} ${row.ref}: ${row.runs} timed run${row.runs === 1 ? "" : "s"}, exits ${JSON.stringify(row.exitCodes)}, missing JSONL ${row.missingJsonlRuns}`);
|
||
|
|
log(` total`.padEnd(24) + formatStat(row.totalMs));
|
||
|
|
const timeout = row.desktopTimeout;
|
||
|
|
if (timeout && timeout.maxTotalMs !== null) {
|
||
|
|
log(` desktop-app timeout`.padEnd(24) + `slowest run ${timeout.maxTotalMs} ms of ${timeout.limitMs} ms: ${timeout.exceeded ? "EXCEEDED" : `${timeout.headroomMs} ms headroom`}`);
|
||
|
|
}
|
||
|
|
log(` installer`.padEnd(24) + formatStat(row.installerMs));
|
||
|
|
for (const phase of PHASES) log(` ${phase}`.padEnd(24) + formatStat(row.phases[phase]));
|
||
|
|
const pieces = Object.keys(row.pieces || {});
|
||
|
|
if (pieces.length) {
|
||
|
|
log(" pieces:");
|
||
|
|
for (const piece of pieces) log(` ${piece}`.padEnd(24) + formatStat(row.pieces[piece]));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function writeJsonReport(file, report) {
|
||
|
|
const target = path.resolve(file);
|
||
|
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||
|
|
fs.writeFileSync(target, `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
||
|
|
return target;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function main() {
|
||
|
|
const parsed = parseArgs(process.argv.slice(2));
|
||
|
|
if (!parsed.ok) {
|
||
|
|
console.error(usage());
|
||
|
|
console.error(`\nerror: ${parsed.error}`);
|
||
|
|
process.exit(2);
|
||
|
|
}
|
||
|
|
if (parsed.help) {
|
||
|
|
console.log(usage());
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
let workspace = null;
|
||
|
|
try {
|
||
|
|
workspace = createWorkspace(parsed.options.workdir);
|
||
|
|
const result = await runBenchmark(parsed.options, { workspace });
|
||
|
|
printReport(result.report);
|
||
|
|
if (parsed.options.json) {
|
||
|
|
const written = writeJsonReport(parsed.options.json, result.report);
|
||
|
|
console.log(`\nJSON report: ${written}`);
|
||
|
|
}
|
||
|
|
if (parsed.options.keepWorkdirs) console.log(`workdirs kept under: ${workspace.root}`);
|
||
|
|
} catch (error) {
|
||
|
|
console.error(error.stack || error.message || error);
|
||
|
|
process.exitCode = 1;
|
||
|
|
} finally {
|
||
|
|
if (workspace && !parsed.options.keepWorkdirs) fs.rmSync(workspace.root, { recursive: true, force: true });
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const invokedAs = process.argv[1] ? path.resolve(process.argv[1]) : null;
|
||
|
|
if (invokedAs && invokedAs === path.resolve(fileURLToPath(import.meta.url))) {
|
||
|
|
main();
|
||
|
|
}
|