mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-04 00:15:41 -08:00
535 lines
25 KiB
JavaScript
535 lines
25 KiB
JavaScript
// Tests for src/installer/timing.js and the install/update benchmark harness.
|
|
// Run with: node --test scripts/test-install-bench.mjs
|
|
//
|
|
// timing.js is tested directly here; install.js does not need to be required
|
|
// for this seam. The benchmark execution tests inject the child-process
|
|
// executor, so they never reach the network, npx or a real installer.
|
|
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import fs from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { spawnSync } from "node:child_process";
|
|
import { EventEmitter } from "node:events";
|
|
import { createRequire } from "node:module";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import {
|
|
assertIsolatedEnvironment,
|
|
childProcessEnvironment,
|
|
createIsolatedEnvironment,
|
|
createWorkspace,
|
|
executeNpx,
|
|
isolationErrors,
|
|
parseArgs,
|
|
redactSecrets,
|
|
runBenchmark,
|
|
stats,
|
|
summarizeEvents,
|
|
summarizeRuns,
|
|
desktopTimeoutHeadroom,
|
|
DESKTOP_APP_TIMEOUT_MS,
|
|
usage,
|
|
writeJsonReport,
|
|
} from "./bench-install-update.mjs";
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const timing = require("../src/installer/timing.js");
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
const BENCH = path.join(ROOT, "scripts", "bench-install-update.mjs");
|
|
const INSTALL = path.join(ROOT, "install.js");
|
|
|
|
// install.js reads HOME once at load. Point it at a throwaway directory before
|
|
// requiring it, matching scripts/test-install-update.mjs; no installer command runs here.
|
|
const INSTALL_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-bench-home-"));
|
|
process.env.HOME = INSTALL_HOME;
|
|
process.env.USERPROFILE = INSTALL_HOME;
|
|
require(INSTALL);
|
|
test.after(() => fs.rmSync(INSTALL_HOME, { recursive: true, force: true }));
|
|
|
|
const cleanup = [];
|
|
function tempDir(prefix = "p2c-install-bench-test-") {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
cleanup.push(dir);
|
|
return dir;
|
|
}
|
|
test.after(() => {
|
|
for (const dir of cleanup.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
function withBenchEnv(value, fn) {
|
|
const old = process.env.PLAN2CODE_BENCH_JSON;
|
|
if (value === undefined) delete process.env.PLAN2CODE_BENCH_JSON;
|
|
else process.env.PLAN2CODE_BENCH_JSON = value;
|
|
try {
|
|
return fn();
|
|
} finally {
|
|
if (old === undefined) delete process.env.PLAN2CODE_BENCH_JSON;
|
|
else process.env.PLAN2CODE_BENCH_JSON = old;
|
|
}
|
|
}
|
|
|
|
test("timing: inactive mode is a no-op and writes nothing", () => {
|
|
const dir = tempDir();
|
|
const oldHome = process.env.HOME;
|
|
const oldUserProfile = process.env.USERPROFILE;
|
|
process.env.HOME = dir;
|
|
process.env.USERPROFILE = dir;
|
|
try {
|
|
withBenchEnv(undefined, () => {
|
|
const inactive = timing.createTiming();
|
|
assert.equal(inactive.active, false);
|
|
assert.equal(inactive.outputPath, null);
|
|
assert.equal(inactive.timingEvent("ignored"), null);
|
|
assert.equal(inactive.timingDuration("ignored", performance.now()), null);
|
|
assert.equal(typeof timing.timingEvent, "function");
|
|
assert.deepEqual(fs.readdirSync(dir), []);
|
|
});
|
|
} finally {
|
|
if (oldHome === undefined) delete process.env.HOME;
|
|
else process.env.HOME = oldHome;
|
|
if (oldUserProfile === undefined) delete process.env.USERPROFILE;
|
|
else process.env.USERPROFILE = oldUserProfile;
|
|
}
|
|
});
|
|
|
|
test("timing: active mode writes parseable JSONL and preserves extra fields", () => {
|
|
const dir = tempDir();
|
|
const target = path.join(dir, "nested", "events.jsonl");
|
|
withBenchEnv(target, () => {
|
|
const active = timing.createTiming({ ref: "v3.2.1", version: "3.2.1", mode: "warm-npx" });
|
|
assert.equal(active.active, true);
|
|
active.timingEvent("alpha", { piece: "skills", detail: { answer: 42 }, dropped: undefined });
|
|
active.timingDuration("beta", performance.now() - 5, { piece: "launcher", result: "updated" });
|
|
});
|
|
|
|
const lines = fs.readFileSync(target, "utf8").trim().split(/\r?\n/);
|
|
assert.equal(lines.length, 2);
|
|
const events = lines.map((line) => JSON.parse(line));
|
|
assert.equal(events[0].event, "alpha");
|
|
assert.equal(events[0].ref, "v3.2.1");
|
|
assert.equal(events[0].version, "3.2.1");
|
|
assert.equal(events[0].mode, "warm-npx");
|
|
assert.deepEqual(events[0].detail, { answer: 42 });
|
|
assert.equal("dropped" in events[0], false);
|
|
assert.equal(events[1].event, "beta");
|
|
assert.equal(events[1].piece, "launcher");
|
|
assert.equal(events[1].result, "updated");
|
|
assert.equal(typeof events[1].durationMs, "number");
|
|
assert.ok(events[1].durationMs >= 0);
|
|
assert.deepEqual(timing.readTimingEvents(target), events);
|
|
});
|
|
|
|
test("timing: malformed existing lines do not stop later reads", () => {
|
|
const dir = tempDir();
|
|
const target = path.join(dir, "events.jsonl");
|
|
const first = { event: "first", at: "2026-01-01T00:00:00.000Z" };
|
|
const last = { event: "last", at: "2026-01-01T00:00:01.000Z" };
|
|
fs.writeFileSync(target, `${JSON.stringify(first)}\nnot json\n{"broken":\n${JSON.stringify(last)}\n`, "utf8");
|
|
assert.deepEqual(timing.readTimingEvents(target), [first, last]);
|
|
});
|
|
|
|
test("timing: readTimingEvents returns [] for a missing file", () => {
|
|
assert.deepEqual(timing.readTimingEvents(path.join(tempDir(), "missing.jsonl")), []);
|
|
});
|
|
|
|
test("benchmark args: parses refs, mode, defaults and output options", () => {
|
|
const parsed = parseArgs(["--baseline", "v3.2.1", "--candidate", "main", "--mode", "warm-npx", "--json", "out/report.json", "--workdir", "tmp", "--keep-workdirs"]);
|
|
assert.equal(parsed.ok, true);
|
|
assert.equal(parsed.options.mode, "warm-npx");
|
|
assert.equal(parsed.options.runs, 3);
|
|
assert.equal(parsed.options.json, "out/report.json");
|
|
assert.equal(parsed.options.workdir, "tmp");
|
|
assert.equal(parsed.options.keepWorkdirs, true);
|
|
assert.deepEqual(parsed.options.refs, [
|
|
{ label: "baseline", ref: "v3.2.1" },
|
|
{ label: "candidate", ref: "main" },
|
|
]);
|
|
|
|
const runs = parseArgs(["--baseline", "main", "--mode", "cold-npx", "--runs", "5"]);
|
|
assert.equal(runs.ok, true);
|
|
assert.equal(runs.options.runs, 5);
|
|
});
|
|
|
|
test("benchmark args: usage errors cover unknown flags, missing refs, bad modes and unsafe refs", () => {
|
|
assert.match(parseArgs(["--bogus"]).error, /Unknown flag: --bogus/);
|
|
assert.match(parseArgs(["--mode", "cold-npx"]).error, /At least one of --baseline or --candidate/);
|
|
assert.match(parseArgs(["--baseline", "main"]).error, /Missing required --mode/);
|
|
assert.match(parseArgs(["--baseline", "main", "--mode", "tepid"]).error, /Unknown mode/);
|
|
assert.match(parseArgs(["--baseline", "main", "--mode", "cold-npx", "--runs", "0"]).error, /--runs/);
|
|
assert.match(parseArgs(["--baseline", "bad;ref", "--mode", "cold-npx"]).error, /Unsafe or unsupported baseline ref/);
|
|
assert.equal(parseArgs(["--help"]).help, true);
|
|
assert.match(usage(), /--mode cold-npx\|warm-npx\|warm-canonical/);
|
|
});
|
|
|
|
test("benchmark CLI: unknown flags print usage and exit 2 before doing any work", () => {
|
|
const result = spawnSync(process.execPath, [BENCH, "--definitely-unknown"], { encoding: "utf8" });
|
|
assert.equal(result.status, 2);
|
|
assert.match(result.stderr, /Usage: node scripts\/bench-install-update\.mjs/);
|
|
assert.match(result.stderr, /Unknown flag: --definitely-unknown/);
|
|
});
|
|
|
|
function fakeRealPaths(root) {
|
|
return {
|
|
home: [path.join(root, "real-home")],
|
|
npmPrefix: [path.join(root, "real-prefix")],
|
|
npmCache: [path.join(root, "real-cache")],
|
|
consoleHome: [path.join(root, "real-console")],
|
|
appData: [path.join(root, "real-appdata")],
|
|
};
|
|
}
|
|
|
|
test("benchmark isolation: a created environment is contained and passes validation", () => {
|
|
const root = tempDir();
|
|
const isolated = createIsolatedEnvironment({ root: path.join(root, "run") });
|
|
const errors = isolationErrors({ ...isolated.env, PLAN2CODE_BENCH_MODE: "cold-npx" }, fakeRealPaths(root), { boundaryRoot: root });
|
|
assert.deepEqual(errors, []);
|
|
for (const key of ["HOME", "USERPROFILE", "npm_config_prefix", "npm_config_cache", "PLAN2CODE_CONSOLE_HOME", "PLAN2CODE_BENCH_JSON", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME"]) {
|
|
assert.ok(path.isAbsolute(isolated.env[key]), key);
|
|
}
|
|
assert.equal(isolated.env.HOME, isolated.env.USERPROFILE);
|
|
assert.ok(fs.existsSync(isolated.paths.npmCache));
|
|
});
|
|
|
|
test("benchmark isolation: equality with real home, npm paths or console home fails closed", () => {
|
|
const root = tempDir();
|
|
const isolated = createIsolatedEnvironment({ root: path.join(root, "run") });
|
|
const real = fakeRealPaths(root);
|
|
for (const [key, realKey] of [
|
|
["HOME", "home"],
|
|
["npm_config_prefix", "npmPrefix"],
|
|
["npm_config_cache", "npmCache"],
|
|
["PLAN2CODE_CONSOLE_HOME", "consoleHome"],
|
|
]) {
|
|
const env = { ...isolated.env, [key]: real[realKey][0] };
|
|
const errors = isolationErrors(env, real, { boundaryRoot: root });
|
|
assert.ok(errors.some((line) => line.includes(key) && line.includes("equals")), `${key}: ${errors.join("; ")}`);
|
|
assert.throws(() => assertIsolatedEnvironment(env, real, { boundaryRoot: root }), /Refusing to benchmark/);
|
|
}
|
|
});
|
|
|
|
test("benchmark isolation: paths outside the work root are rejected and controlled inherited env is replaced", () => {
|
|
const root = tempDir();
|
|
const isolated = createIsolatedEnvironment({ root: path.join(root, "run") });
|
|
const outside = path.join(os.tmpdir(), `outside-${process.pid}`);
|
|
const errors = isolationErrors({ ...isolated.env, HOME: outside, USERPROFILE: outside }, fakeRealPaths(root), { boundaryRoot: root });
|
|
assert.ok(errors.some((line) => line.includes("outside the benchmark work root")));
|
|
|
|
const merged = childProcessEnvironment(isolated.env, {
|
|
PATH: "safe-path",
|
|
HOME: "real-home",
|
|
userprofile: "real-profile",
|
|
NPM_CONFIG_CACHE: "real-cache",
|
|
PLAN2CODE_CONSOLE_HOME: "real-console",
|
|
APPDATA: "real-appdata",
|
|
GIT_DIR: "real-git-dir",
|
|
GIT_WORK_TREE: "real-work-tree",
|
|
GIT_INDEX_FILE: "real-index",
|
|
GIT_CONFIG_COUNT: "1",
|
|
GIT_CONFIG_KEY_0: "core.hooksPath",
|
|
GIT_CONFIG_VALUE_0: "real-hooks",
|
|
npm_config_userconfig: "real-userconfig",
|
|
SSH_AUTH_SOCK: "auth-socket-stays",
|
|
});
|
|
assert.equal(merged.PATH, "safe-path");
|
|
assert.equal(merged.HOME, isolated.env.HOME);
|
|
assert.equal(merged.npm_config_cache, isolated.env.npm_config_cache);
|
|
assert.equal(merged.PLAN2CODE_CONSOLE_HOME, isolated.env.PLAN2CODE_CONSOLE_HOME);
|
|
assert.equal("userprofile" in merged, false);
|
|
assert.equal("NPM_CONFIG_CACHE" in merged, false);
|
|
assert.equal("GIT_DIR" in merged, false);
|
|
assert.equal("GIT_WORK_TREE" in merged, false);
|
|
assert.equal("GIT_INDEX_FILE" in merged, false);
|
|
assert.equal("GIT_CONFIG_COUNT" in merged, false);
|
|
assert.equal("GIT_CONFIG_KEY_0" in merged, false);
|
|
assert.equal("GIT_CONFIG_VALUE_0" in merged, false);
|
|
assert.equal("npm_config_userconfig" in merged, false);
|
|
assert.equal(merged.SSH_AUTH_SOCK, "auth-socket-stays");
|
|
});
|
|
|
|
test("benchmark events: durations and pieces are summarized with median-ready phase values", () => {
|
|
const start = Date.parse("2026-01-01T00:00:00.000Z");
|
|
const at = (ms) => new Date(start + ms).toISOString();
|
|
const events = [
|
|
{ event: "bootstrap-start", at: at(9000), mode: "cold-npx" },
|
|
{ event: "installer-start", at: at(9100), mode: "cold-npx" },
|
|
{ event: "skills-built", at: at(10100), durationMs: 800, mode: "cold-npx" },
|
|
{ event: "console-staged", at: at(10200), mode: "cold-npx" },
|
|
{ event: "console-committed", at: at(11200), durationMs: 950, mode: "cold-npx" },
|
|
{ event: "canonical-staged", at: at(11300), mode: "cold-npx" },
|
|
{ event: "canonical-committed", at: at(12300), durationMs: 850, mode: "cold-npx" },
|
|
{ event: "retired-removed", at: at(12400), durationMs: 50, mode: "cold-npx" },
|
|
{ event: "links-refreshed", at: at(14300), durationMs: 1800, mode: "cold-npx" },
|
|
{ event: "piece-installed", at: at(14400), durationMs: 4200, piece: "skills", result: "updated", mode: "cold-npx" },
|
|
{ event: "piece-installed", at: at(14500), durationMs: 100, piece: "launcher", result: "updated", mode: "cold-npx" },
|
|
{ event: "installer-end", at: at(15000), durationMs: 5900, mode: "cold-npx" },
|
|
];
|
|
const summary = summarizeEvents(events, { startedAt: start });
|
|
assert.equal(summary.phases.bootstrap, 9000);
|
|
assert.equal(summary.phases.skills, 800);
|
|
assert.equal(summary.phases.console, 950);
|
|
assert.equal(summary.phases.canonical, 850);
|
|
assert.equal(summary.phases["link-refresh"], 1800);
|
|
assert.equal(summary.phases.pieces, 4300);
|
|
assert.equal(summary.pieces.skills.totalMs, 4200);
|
|
assert.equal(summary.pieces.launcher.totalMs, 100);
|
|
assert.equal(summary.installerMs, 5900);
|
|
assert.equal(summary.eventCount, events.length);
|
|
assert.deepEqual(summary.missingEvents, []);
|
|
});
|
|
|
|
test("benchmark events: missing JSONL events are empty report data, not an error", () => {
|
|
const summary = summarizeEvents([], { startedAt: Date.now() });
|
|
assert.equal(summary.eventCount, 0);
|
|
assert.equal(summary.phases.bootstrap, null);
|
|
assert.equal(summary.phases.skills, null);
|
|
assert.ok(summary.missingEvents.includes("installer-start"));
|
|
assert.ok(summary.missingEvents.includes("piece-installed"));
|
|
});
|
|
|
|
test("benchmark summary: groups by ref and mode with median/min/max", () => {
|
|
const rows = [10, 30, 20].map((totalMs, index) => ({
|
|
label: "baseline",
|
|
ref: "main",
|
|
mode: "cold-npx",
|
|
exitCode: 0,
|
|
hasTimingJson: true,
|
|
totalMs,
|
|
installerMs: totalMs - 2,
|
|
eventCount: 10 + index,
|
|
phases: { bootstrap: index + 1, skills: 5, console: 6, canonical: null, "link-refresh": 8, pieces: 9 },
|
|
pieceTotals: { skills: { totalMs: 100 + index }, launcher: { totalMs: 10 } },
|
|
}));
|
|
const [summary] = summarizeRuns(rows);
|
|
assert.equal(summary.ref, "main");
|
|
assert.equal(summary.mode, "cold-npx");
|
|
assert.deepEqual(summary.totalMs, { median: 20, min: 10, max: 30, count: 3 });
|
|
assert.deepEqual(summary.phases.bootstrap, { median: 2, min: 1, max: 3, count: 3 });
|
|
assert.equal(summary.phases.canonical, null);
|
|
assert.equal(summary.pieces.skills.median, 101);
|
|
assert.equal(summary.nonZeroExitRuns, 0);
|
|
assert.deepEqual(stats([]), null);
|
|
});
|
|
|
|
test("benchmark output: common credential shapes and provided secrets are redacted", () => {
|
|
const secret = "super-secret-value-123";
|
|
const text = [
|
|
"password=ghp_abcdefgh123456",
|
|
"token=abc123",
|
|
"https://user:pass@example.com/repo",
|
|
"x-access-token:secret@github.com",
|
|
"Authorization: Bearer abcdef",
|
|
`saw ${secret} here`,
|
|
].join("\n");
|
|
const redacted = redactSecrets(text, [secret]);
|
|
assert.equal(redacted.includes(secret), false);
|
|
assert.equal(redacted.includes("ghp_abcdefgh123456"), false);
|
|
assert.equal(redacted.includes("user:pass"), false);
|
|
assert.equal(redacted.includes("Bearer abcdef"), false);
|
|
assert.match(redacted, /<redacted/);
|
|
});
|
|
|
|
test("benchmark execution: executeNpx uses the platform-appropriate npx launch shape without a real child", async () => {
|
|
const dir = tempDir();
|
|
const seen = {};
|
|
const child = new EventEmitter();
|
|
child.stdout = new EventEmitter();
|
|
child.stderr = new EventEmitter();
|
|
const spawnImpl = (command, args, options) => {
|
|
seen.command = command;
|
|
seen.args = args;
|
|
seen.options = options;
|
|
queueMicrotask(() => child.emit("close", 0, null));
|
|
return child;
|
|
};
|
|
const result = await executeNpx(
|
|
{
|
|
command: process.platform === "win32" ? "npx.cmd" : "npx",
|
|
args: ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#main", "--update", "--force"],
|
|
shell: false,
|
|
cwd: dir,
|
|
env: {},
|
|
stdoutLog: path.join(dir, "stdout.log"),
|
|
stderrLog: path.join(dir, "stderr.log"),
|
|
},
|
|
spawnImpl
|
|
);
|
|
assert.equal(result.exitCode, 0);
|
|
if (process.platform === "win32") {
|
|
assert.equal(seen.command, process.env.ComSpec || "cmd.exe");
|
|
assert.deepEqual(seen.args.slice(0, 4), ["/d", "/s", "/c", "npx.cmd"]);
|
|
assert.deepEqual(seen.args.slice(4), ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#main", "--update", "--force"]);
|
|
} else {
|
|
assert.equal(seen.command, "npx");
|
|
assert.equal(seen.args[0], "--yes");
|
|
}
|
|
assert.equal(seen.options.shell, false);
|
|
assert.equal(fs.readFileSync(path.join(dir, "stdout.log"), "utf8"), "");
|
|
});
|
|
|
|
function writeTimingEvents(file, env) {
|
|
const start = Date.now();
|
|
const at = (ms) => new Date(start + ms).toISOString();
|
|
const base = { ref: env.PLAN2CODE_INSTALL_REF, version: "0.0.0-test", mode: env.PLAN2CODE_BENCH_MODE };
|
|
const events = [
|
|
{ event: "bootstrap-start", at: at(5), ...base },
|
|
{ event: "installer-start", at: at(10), ...base },
|
|
{ event: "skills-built", at: at(90), durationMs: 80, ...base },
|
|
{ event: "console-staged", at: at(95), ...base },
|
|
{ event: "console-committed", at: at(140), durationMs: 45, ...base },
|
|
{ event: "canonical-staged", at: at(150), ...base },
|
|
{ event: "canonical-committed", at: at(190), durationMs: 40, ...base },
|
|
{ event: "retired-removed", at: at(200), durationMs: 10, ...base },
|
|
{ event: "links-refreshed", at: at(260), durationMs: 60, ...base },
|
|
{ event: "piece-installed", at: at(270), durationMs: 300, piece: "skills", result: "updated", ...base },
|
|
{ event: "piece-installed", at: at(280), durationMs: 50, piece: "launcher", result: "updated", ...base },
|
|
{ event: "installer-end", at: at(300), durationMs: 290, ...base },
|
|
];
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
fs.writeFileSync(file, `${events.map((event) => JSON.stringify(event)).join("\n")}\n`, "utf8");
|
|
}
|
|
|
|
async function fakeExecute(call, calls) {
|
|
calls.push({
|
|
args: call.args,
|
|
cwd: call.cwd,
|
|
env: { ...call.env },
|
|
stdoutLog: call.stdoutLog,
|
|
stderrLog: call.stderrLog,
|
|
timingPath: call.timingPath,
|
|
});
|
|
writeTimingEvents(call.timingPath, call.env);
|
|
fs.mkdirSync(path.dirname(call.stdoutLog), { recursive: true });
|
|
fs.writeFileSync(call.stdoutLog, "installer stdout\n", "utf8");
|
|
fs.writeFileSync(call.stderrLog, "", "utf8");
|
|
return { exitCode: 0, signal: null };
|
|
}
|
|
|
|
test("benchmark execution: warm-npx primes one per-ref cache but keeps each timed HOME fresh", async () => {
|
|
const workspaceRoot = tempDir();
|
|
const calls = [];
|
|
const { report } = await runBenchmark(
|
|
{ refs: [{ label: "baseline", ref: "main" }], mode: "warm-npx", runs: 2, workdir: workspaceRoot, keepWorkdirs: true },
|
|
{ execute: (call) => fakeExecute(call, calls) }
|
|
);
|
|
|
|
assert.equal(calls.length, 3, "one warm-up plus two timed runs");
|
|
const [warmup, timed, secondTimed] = calls;
|
|
assert.equal(warmup.env.npm_config_cache, timed.env.npm_config_cache, "the warm-up primes the shared cache");
|
|
assert.equal(secondTimed.env.npm_config_cache, timed.env.npm_config_cache, "timed runs reuse the warmed cache");
|
|
assert.notEqual(warmup.env.HOME, timed.env.HOME, "warm-npx deliberately does not reuse the warm-up HOME");
|
|
assert.notEqual(warmup.env.HOME, secondTimed.env.HOME);
|
|
assert.notEqual(timed.env.HOME, secondTimed.env.HOME, "each timed run still gets a fresh HOME");
|
|
assert.notEqual(warmup.env.PLAN2CODE_CONSOLE_HOME, timed.env.PLAN2CODE_CONSOLE_HOME);
|
|
assert.equal(timed.env.PLAN2CODE_BENCH_MODE, "warm-npx");
|
|
assert.equal(timed.env.PLAN2CODE_INSTALL_REF, "main");
|
|
assert.deepEqual(timed.args.slice(0, 2), ["--yes", "--allow-git=all"]);
|
|
assert.equal(timed.args[2], "git+https://github.com/jparkerweb/plan2code.git#main");
|
|
assert.deepEqual(timed.args.slice(3), ["--update", "--force"]);
|
|
|
|
assert.equal(report.warmups.length, 1);
|
|
assert.equal(report.runs.length, 2);
|
|
assert.equal(report.environments.length, 3);
|
|
const timedEnvironments = report.environments.filter((env) => env.kind === "timed");
|
|
assert.equal(timedEnvironments.length, 2);
|
|
assert.equal(timedEnvironments[0].reuse.npmCacheFromWarmup, true);
|
|
assert.equal(timedEnvironments[0].reuse.homeFromWarmup, false);
|
|
assert.equal(timedEnvironments[0].reuse.cacheSharedAcrossTimedRuns, true);
|
|
assert.equal(report.runs[0].hasTimingJson, true);
|
|
assert.equal(report.runs[0].modeCounts.matching, 12);
|
|
assert.equal(report.runs[0].modeCounts.missing, 0);
|
|
assert.equal(report.runs[0].exitCode, 0);
|
|
assert.equal(report.runs[0].phases.skills, 80);
|
|
assert.equal(report.runs[0].phases.canonical, 40);
|
|
assert.equal(report.runs[0].phases["link-refresh"], 60);
|
|
assert.equal(report.runs[0].phases.pieces, 350);
|
|
assert.equal(report.summary[0].runs, 2);
|
|
assert.equal(report.summary[0].pieces.skills.median, 300);
|
|
});
|
|
|
|
test("benchmark execution: warm-canonical reuses the same isolated HOME and cache across repetitions", async () => {
|
|
const workspaceRoot = tempDir();
|
|
const calls = [];
|
|
const { report } = await runBenchmark(
|
|
{ refs: [{ label: "candidate", ref: "v3.2.1" }], mode: "warm-canonical", runs: 2, workdir: workspaceRoot, keepWorkdirs: true },
|
|
{ execute: (call) => fakeExecute(call, calls) }
|
|
);
|
|
|
|
assert.equal(calls.length, 3, "one warm-up plus two timed repetitions");
|
|
const [warmup, timed, secondTimed] = calls;
|
|
assert.equal(warmup.env.HOME, timed.env.HOME);
|
|
assert.equal(warmup.env.npm_config_cache, timed.env.npm_config_cache);
|
|
assert.equal(secondTimed.env.HOME, timed.env.HOME);
|
|
assert.equal(secondTimed.env.npm_config_cache, timed.env.npm_config_cache);
|
|
assert.notEqual(warmup.env.PLAN2CODE_BENCH_JSON, timed.env.PLAN2CODE_BENCH_JSON, "warm-up events stay out of timed JSONL files");
|
|
assert.notEqual(secondTimed.env.PLAN2CODE_BENCH_JSON, timed.env.PLAN2CODE_BENCH_JSON, "each timed run gets its own JSONL");
|
|
const timedEnvironments = report.environments.filter((env) => env.kind === "timed");
|
|
assert.equal(timedEnvironments.length, 2);
|
|
assert.equal(timedEnvironments[0].reuse.homeFromWarmup, true);
|
|
assert.equal(timedEnvironments[0].reuse.npmCacheFromWarmup, true);
|
|
assert.equal(timedEnvironments[0].reuse.homeSharedAcrossTimedRuns, true);
|
|
});
|
|
|
|
test("benchmark execution: non-zero exits and missing JSONL are report data, not failures", async () => {
|
|
const workspaceRoot = tempDir();
|
|
const { report, workspace } = await runBenchmark(
|
|
{ refs: [{ label: "baseline", ref: "main" }], mode: "cold-npx", runs: 1, workdir: workspaceRoot, keepWorkdirs: true },
|
|
{
|
|
execute: async () => ({ exitCode: 7, signal: null }),
|
|
}
|
|
);
|
|
|
|
assert.equal(report.runs.length, 1);
|
|
assert.equal(report.runs[0].exitCode, 7);
|
|
assert.equal(report.runs[0].hasTimingJson, false);
|
|
assert.equal(report.runs[0].eventCount, 0);
|
|
assert.equal(report.runs[0].phases.bootstrap, null);
|
|
assert.equal(report.summary[0].nonZeroExitRuns, 1);
|
|
assert.equal(report.summary[0].missingJsonlRuns, 1);
|
|
assert.ok(fs.existsSync(path.join(workspace.root, report.runs[0].runId)));
|
|
});
|
|
|
|
test("benchmark execution: cold-npx runs once, and report JSON is reproducible without secrets", async () => {
|
|
const workspaceRoot = tempDir();
|
|
const calls = [];
|
|
const { report, workspace } = await runBenchmark(
|
|
{ refs: [{ label: "baseline", ref: "main" }], mode: "cold-npx", runs: 1, workdir: workspaceRoot, keepWorkdirs: true },
|
|
{ execute: (call) => fakeExecute(call, calls) }
|
|
);
|
|
|
|
assert.equal(calls.length, 1, "cold mode has no warm-up");
|
|
assert.equal(report.warmups.length, 0);
|
|
assert.equal(report.environments.length, 1);
|
|
assert.ok(workspace.root.startsWith(path.resolve(workspaceRoot)));
|
|
assert.deepEqual(Object.keys(report).sort(), ["environments", "generatedAt", "mode", "modeBehavior", "repoUrl", "runs", "summary", "warmups"].sort());
|
|
assert.equal(report.runs[0].eventCount, 12);
|
|
assert.equal(report.runs[0].missingEvents.length, 0);
|
|
assert.equal(report.summary[0].phases.skills.median, 80);
|
|
|
|
const jsonPath = path.join(tempDir(), "report", "bench.json");
|
|
writeJsonReport(jsonPath, report);
|
|
const written = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
|
|
assert.ok(Array.isArray(written.runs));
|
|
assert.ok(Array.isArray(written.summary));
|
|
assert.ok(Array.isArray(written.environments));
|
|
assert.equal(written.runs[0].ref, "main");
|
|
assert.equal(written.runs[0].mode, "cold-npx");
|
|
assert.ok(Array.isArray(written.runs[0].argv));
|
|
assert.equal(written.runs[0].exitCode, 0);
|
|
assert.equal(typeof written.runs[0].eventCount, "number");
|
|
assert.equal(typeof written.environments[0].tempRoot, "string");
|
|
assert.equal(typeof written.environments[0].layout.home, "string");
|
|
assert.equal(fs.readFileSync(jsonPath, "utf8").includes("password="), false);
|
|
});
|
|
|
|
test("each ref's summary shows its slowest run against the desktop app's 300-second update timeout", () => {
|
|
assert.equal(DESKTOP_APP_TIMEOUT_MS, 300000);
|
|
assert.deepEqual(desktopTimeoutHeadroom({ median: 120000, min: 100000, max: 130500, count: 3 }), { limitMs: 300000, maxTotalMs: 130500, headroomMs: 169500, exceeded: false });
|
|
assert.equal(desktopTimeoutHeadroom({ median: 400000, min: 390000, max: 411543, count: 3 }).exceeded, true);
|
|
assert.deepEqual(desktopTimeoutHeadroom(null), { limitMs: 300000, maxTotalMs: null, headroomMs: null, exceeded: null });
|
|
const [summary] = summarizeRuns([{ ref: "r", mode: "cold-npx", label: "candidate", exitCode: 0, totalMs: 1000, hasTimingJson: true }]);
|
|
assert.equal(summary.desktopTimeout.maxTotalMs, 1000);
|
|
assert.equal(summary.desktopTimeout.exceeded, false);
|
|
});
|