mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-04 00:15:41 -08:00
Sync upstream v3.2.4: slim install refs, a crash-safe installer, Change project restarts the agent (v3.2.4)
AI Assisted
This commit is contained in:
1 parent
50319aa332
commit
f997a82c4d
45 files changed
+7851
-306
No files matched your search
@@ -0,0 +1,837 @@
|
||||
#!/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();
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// Compact installable end-to-end fixtures: real installer code in a local
|
||||
// git-ref fixture, but a deliberately small stand-in web console so automated
|
||||
// tests do not clone and copy tens of megabytes of media for every case. The
|
||||
// installer/build inputs outside src/web-console are the repository's real
|
||||
// files, including binary runtime files. Everything here is dev-only.
|
||||
//
|
||||
// Limit: the slim payload is assembled here by hand, not by
|
||||
// scripts/publish-install-refs.mjs, so a file the real publisher's allowlist
|
||||
// leaves out would not show up in these tests. The publisher's own required-file
|
||||
// validation is covered in scripts/test-publish-install-refs.mjs.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
|
||||
import { assertIsolatedEnvironment, childProcessEnvironment, createIsolatedEnvironment } from "./bench-install-update.mjs";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { selectSkillsCliVersion } = require("../src/installer/skills-cli.js");
|
||||
|
||||
export const INSTALL_E2E_VERSIONS = Object.freeze(["1.0.0", "2.0.0", "3.1.2"]);
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
function readRepo(rel, buffer = false) {
|
||||
const data = fs.readFileSync(path.join(ROOT, ...rel.split("/")));
|
||||
return buffer ? data : data.toString("utf8");
|
||||
}
|
||||
|
||||
function walkFiles(dir, base = dir, out = []) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) walkFiles(full, base, out);
|
||||
else if (entry.isFile()) out.push(path.relative(base, full).split(path.sep).join("/"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The runtime payload of one fixture release. Everything under src/ except the
|
||||
* web console is the real repository tree. The web console is reduced to the
|
||||
* files the installer and launcher directly require plus the contract docs the
|
||||
* skills copy; end-to-end installer tests validate staging and completion
|
||||
* markers, not the console UI's media bundle.
|
||||
*/
|
||||
export function compactRuntimeFiles(version) {
|
||||
const pkg = JSON.parse(readRepo("package.json"));
|
||||
pkg.version = version;
|
||||
const versionJson = JSON.parse(readRepo("version.json"));
|
||||
versionJson.version = version;
|
||||
const files = {
|
||||
"install.js": readRepo("install.js"),
|
||||
"package.json": `${JSON.stringify(pkg, null, 2)}\n`,
|
||||
"version.json": `${JSON.stringify(versionJson, null, 2)}\n`,
|
||||
};
|
||||
|
||||
for (const rel of walkFiles(path.join(ROOT, "src"), path.join(ROOT, "src"))) {
|
||||
if (rel.startsWith("web-console/")) continue;
|
||||
files[`src/${rel}`] = fs.readFileSync(path.join(ROOT, "src", ...rel.split("/")));
|
||||
}
|
||||
|
||||
for (const rel of [
|
||||
"console.mjs",
|
||||
"console.md",
|
||||
"building.md",
|
||||
"console-docs.md",
|
||||
"update-check.mjs",
|
||||
"agent-lookup.mjs",
|
||||
]) {
|
||||
files[`src/web-console/${rel}`] = fs.readFileSync(path.join(ROOT, "src", "web-console", rel));
|
||||
}
|
||||
files["src/web-console/public/favicon.png"] = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "favicon.png"));
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* The full local repository shape with installable plain release trees and
|
||||
* slim synthetic trees. Plain tags carry `docs/promo.md`; install tags do not,
|
||||
* and carry the binding manifest the publisher writes.
|
||||
*/
|
||||
export function createInstallE2EFixture(options = {}) {
|
||||
const releases = INSTALL_E2E_VERSIONS.map((version) => {
|
||||
const runtime = compactRuntimeFiles(version);
|
||||
const installFiles = {
|
||||
...runtime,
|
||||
".plan2code-install-ref.json": `${JSON.stringify({ kind: "install-ref", version, sourceTag: `v${version}`, sourceCommit: `fixture-v${version}`, files: Object.fromEntries(Object.entries(runtime).map(([name, content]) => [name, crypto.createHash("sha256").update(content).digest("hex")])) }, null, 2)}\n`,
|
||||
};
|
||||
return {
|
||||
version,
|
||||
annotated: version === "3.1.2",
|
||||
installTag: version !== "1.0.0",
|
||||
files: { ...runtime, "docs/promo.md": `# heavy fixture docs for v${version}\n` },
|
||||
installFiles,
|
||||
};
|
||||
});
|
||||
return createInstallRefFixture({ releases, ...options });
|
||||
}
|
||||
|
||||
/** A temp root for one or more installer runs against one logical machine. */
|
||||
export function makeInstallE2ERunRoot() {
|
||||
return fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-install-e2e-run-"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed the exact pinned skills CLI in npm's private cache shape. The tiny CLI
|
||||
* records each invocation as JSONL and exits successfully, so installs exercise
|
||||
* resolveSkillsCli's cached path and never touch the npm registry.
|
||||
*/
|
||||
export function seedCachedSkillsCli(npmCache) {
|
||||
const pin = selectSkillsCliVersion(process.versions.node);
|
||||
const packageDir = path.join(npmCache, "_npx", "install-e2e-fixture", "node_modules", "skills");
|
||||
fs.mkdirSync(path.join(packageDir, "bin"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(packageDir, "package.json"),
|
||||
`${JSON.stringify({ name: "skills", version: pin, type: "module", bin: { skills: "bin/cli.mjs" }, dependencies: {} }, null, 2)}\n`
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(packageDir, "bin", "cli.mjs"),
|
||||
[
|
||||
'import fs from "node:fs";',
|
||||
'import path from "node:path";',
|
||||
"const log = process.env.PLAN2CODE_SKILLS_CLI_LOG;",
|
||||
"const argv = process.argv.slice(2);",
|
||||
"if (log) {",
|
||||
" fs.mkdirSync(path.dirname(log), { recursive: true });",
|
||||
" fs.appendFileSync(log, JSON.stringify({ argv, cwd: process.cwd() }) + '\\n');",
|
||||
"}",
|
||||
"if (argv[0] === 'remove') {",
|
||||
" const store = path.join(process.env.HOME || '', '.agents', 'skills');",
|
||||
" for (const name of argv.slice(1).filter((arg) => !arg.startsWith('-'))) {",
|
||||
" if (name === 'plan2code' || name.startsWith('plan2code-')) fs.rmSync(path.join(store, name), { recursive: true, force: true });",
|
||||
" }",
|
||||
"}",
|
||||
"process.exit(0);",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
return { pin };
|
||||
}
|
||||
|
||||
/** JSONL records written by the seeded skills CLI, or [] when it never ran. */
|
||||
export function readSkillsCliLog(file) {
|
||||
try {
|
||||
return fs
|
||||
.readFileSync(file, "utf8")
|
||||
.split(/\r?\n/)
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch `ref` from the fixture with real git and run its install.js as a child
|
||||
* inside one fully isolated machine image. Pass the same `root` again to model
|
||||
* an update or uninstall on the same machine; omit it for a fresh machine.
|
||||
* `planted` variables are set after the credential scrub, so a test can plant
|
||||
* a sentinel secret and check that it never reaches an artifact.
|
||||
*/
|
||||
export function runFixtureInstaller(
|
||||
fixture,
|
||||
{
|
||||
ref,
|
||||
releaseRef = null,
|
||||
root = makeInstallE2ERunRoot(),
|
||||
planted = {},
|
||||
} = {}
|
||||
) {
|
||||
const isolated = createIsolatedEnvironment({ root: path.join(root, "isolated") });
|
||||
assertIsolatedEnvironment(isolated.env, undefined, { boundaryRoot: root });
|
||||
seedCachedSkillsCli(isolated.paths.npmCache);
|
||||
const cliLog = path.join(root, "skills-cli.jsonl");
|
||||
const checkout = path.join(root, "payload");
|
||||
fixture.checkout(ref, checkout);
|
||||
|
||||
const env = childProcessEnvironment({
|
||||
...isolated.env,
|
||||
PLAN2CODE_INSTALL_REF: ref,
|
||||
PLAN2CODE_SKILLS_CLI_LOG: cliLog,
|
||||
PLAN2CODE_RELEASE_BASE: "http://127.0.0.1:9/",
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GCM_INTERACTIVE: "never",
|
||||
});
|
||||
if (releaseRef) env.PLAN2CODE_RELEASE_REF = releaseRef;
|
||||
else delete env.PLAN2CODE_RELEASE_REF;
|
||||
// Automated end-to-end runs must not inherit app-loop state, user git
|
||||
// credential configuration or hosted credentials. They use local-path git
|
||||
// only; sensitive inherited variables are removed too so a typo can never
|
||||
// turn into a credential-backed network fetch.
|
||||
const emptyGitConfig = path.join(root, "empty-gitconfig");
|
||||
fs.writeFileSync(emptyGitConfig, "");
|
||||
env.GIT_CONFIG_NOSYSTEM = "1";
|
||||
env.GIT_CONFIG_GLOBAL = emptyGitConfig;
|
||||
for (const key of Object.keys(env)) {
|
||||
if (/(?:TOKEN|SECRET|PASSWORD|CREDENTIAL|ASKPASS|^SSH_AUTH_SOCK$|^SSH_AGENT_PID$|^GIT_SSH|^PLAN2CODE_LS_REMOTE_FILE$)/i.test(key)) delete env[key];
|
||||
if (/^PLAN2CODE_(?:IN_APP|EMBED_ORIGIN|CONSOLE_SID|LOOP_STRENGTH)/i.test(key)) delete env[key];
|
||||
}
|
||||
Object.assign(env, planted);
|
||||
|
||||
const result = spawnSync(process.execPath, [path.join(checkout, "install.js"), "--update", "--force"], {
|
||||
cwd: checkout,
|
||||
env,
|
||||
encoding: "utf8",
|
||||
input: "",
|
||||
timeout: 180000,
|
||||
windowsHide: true,
|
||||
});
|
||||
return {
|
||||
root,
|
||||
ref,
|
||||
releaseRef,
|
||||
checkout,
|
||||
isolated,
|
||||
cliLog,
|
||||
env,
|
||||
result,
|
||||
stdout: result.stdout || "",
|
||||
stderr: result.stderr || "",
|
||||
cleanup: () => fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A local npx stand-in for launcher-driven end-to-end runs. It accepts the real
|
||||
* launcher's `git+https://github.com/...#ref` argument, but fetches that ref
|
||||
* from the bare local fixture and runs its install.js. This keeps the launcher's
|
||||
* production argument shape under test without any network use.
|
||||
*/
|
||||
export function installLocalNpxShim(root, fixture) {
|
||||
const bin = path.join(root, "local-npx-bin");
|
||||
fs.mkdirSync(bin, { recursive: true });
|
||||
const driver = path.join(bin, "local-npx.mjs");
|
||||
fs.writeFileSync(
|
||||
driver,
|
||||
[
|
||||
'import fs from "node:fs";',
|
||||
'import os from "node:os";',
|
||||
'import path from "node:path";',
|
||||
'import { execFileSync, spawnSync } from "node:child_process";',
|
||||
`const origin = ${JSON.stringify(fixture.dir)};`,
|
||||
'const args = process.argv.slice(2);',
|
||||
'const at = args.findIndex((arg) => arg.startsWith("git+"));',
|
||||
'if (at === -1) { console.error("local npx fixture: no git package spec"); process.exit(2); }',
|
||||
'const spec = args[at];',
|
||||
'const ref = spec.includes("#") ? spec.slice(spec.indexOf("#") + 1) : "main";',
|
||||
'const rest = args.slice(at + 1);',
|
||||
'const checkout = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-local-npx-payload-"));',
|
||||
'try {',
|
||||
' execFileSync("git", ["clone", "--quiet", "--depth", "1", "--branch", ref, origin, checkout], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" } });',
|
||||
' fs.rmSync(path.join(checkout, ".git"), { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });',
|
||||
' if (process.env.PLAN2CODE_LOCAL_NPX_LOG) {',
|
||||
' fs.mkdirSync(path.dirname(process.env.PLAN2CODE_LOCAL_NPX_LOG), { recursive: true });',
|
||||
' fs.appendFileSync(process.env.PLAN2CODE_LOCAL_NPX_LOG, JSON.stringify({ spec, ref, rest, synthetic: fs.existsSync(path.join(checkout, ".plan2code-install-ref.json")), docs: fs.existsSync(path.join(checkout, "docs", "promo.md")) }) + "\\n");',
|
||||
' }',
|
||||
' const run = spawnSync(process.execPath, [path.join(checkout, "install.js"), ...rest], { stdio: "inherit", env: process.env });',
|
||||
' process.exitCode = run.status ?? 1;',
|
||||
'} finally {',
|
||||
' fs.rmSync(checkout, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });',
|
||||
'}',
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
if (process.platform === "win32") {
|
||||
fs.writeFileSync(path.join(bin, "npx.cmd"), `@echo off\r\n"${process.execPath}" "${driver}" %*\r\nexit /b %errorlevel%\r\n`);
|
||||
} else {
|
||||
fs.writeFileSync(path.join(bin, "npx"), `#!/bin/sh\nexec "${process.execPath}" "${driver}" "$@"\n`);
|
||||
fs.chmodSync(path.join(bin, "npx"), 0o755);
|
||||
}
|
||||
return { bin, driver };
|
||||
}
|
||||
|
||||
/** The fixture snapshot as a file for PLAN2CODE_LS_REMOTE_FILE. */
|
||||
export function writeFixtureSnapshot(fixture, root) {
|
||||
const file = path.join(root, "ls-remote.txt");
|
||||
fs.writeFileSync(file, fixture.lsRemote(), "utf8");
|
||||
return file;
|
||||
}
|
||||
|
||||
/** Environment for invoking the installed launcher inside one isolated run image. */
|
||||
export function launcherRunEnvironment(run, { bin, lsRemoteFile }) {
|
||||
const env = { ...run.env, PLAN2CODE_LS_REMOTE_FILE: lsRemoteFile };
|
||||
const pathKey = Object.keys(env).find((key) => key.toUpperCase() === "PATH") || "PATH";
|
||||
env[pathKey] = bin + path.delimiter + (env[pathKey] || "");
|
||||
return env;
|
||||
}
|
||||
|
||||
/** Convenience readers for the isolated machine image returned above. */
|
||||
export function installE2EJson(run, ...parts) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path.join(run.isolated.paths.home, ...parts), "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function installE2EExists(run, ...parts) {
|
||||
return fs.existsSync(path.join(run.isolated.paths.home, ...parts));
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
// Local git-ref fixtures for the install/update tests: bare repositories in
|
||||
// temp dirs, built with one `git fast-import` stream each, so no network, no
|
||||
// working tree and no dozens of slow per-object git spawns are ever involved.
|
||||
// A fixture carries the ref shape the installer and launcher reason about:
|
||||
//
|
||||
// - lightweight and annotated `vX.Y.Z` release tags on `main` commits
|
||||
// (annotated ones produce peeled `^{}` lines in ls-remote output),
|
||||
// - synthetic `install-vX.Y.Z` tags on slim payload commits, the shape the
|
||||
// release workflow publishes (phase 5 builds the real publisher),
|
||||
// - a `release` branch at the newest synthetic tip, or absent,
|
||||
// - feature branches and a non-release tag the parsers must ignore,
|
||||
// - older rollback versions, with and without a synthetic ref.
|
||||
//
|
||||
// Everything runs under the scrubbed git environment of
|
||||
// scripts/skill-script-helpers.mjs (importing it here is what the failure log
|
||||
// requires of fixture-building tests), and Node built-ins only.
|
||||
//
|
||||
// import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
|
||||
// const fx = createInstallRefFixture();
|
||||
// fx.snapshotText(); // `git ls-remote --tags --heads`-style text
|
||||
// fx.refs.tags["v3.1.2"]; // shas, per ref name
|
||||
// fx.cleanup(); // idempotent
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import { scrubbedEnv } from "./skill-script-helpers.mjs";
|
||||
import { compareVersions } from "../src/web-console/update-check.mjs";
|
||||
|
||||
/**
|
||||
* The default release ladder: a lightweight rollback with no synthetic ref, a
|
||||
* rollback with one, and an annotated newest release with one. Exactly the
|
||||
* matrix the rollback and fallback tests need; pass `releases` to vary it.
|
||||
* Per release: `annotated` makes the v* tag annotated, `installTag` adds a
|
||||
* synthetic `install-v*` ref, `files` replaces the full-source tree, and
|
||||
* `installFiles` replaces the slim synthetic tree.
|
||||
*/
|
||||
export const DEFAULT_RELEASES = [
|
||||
{ version: "1.0.0" },
|
||||
{ version: "2.0.0", installTag: true },
|
||||
{ version: "3.1.2", annotated: true, installTag: true },
|
||||
];
|
||||
|
||||
/** The files of one full-source commit on main for `version` (docs/ included: the heavy tree). */
|
||||
function fullTreeFiles(version) {
|
||||
return {
|
||||
"install.js": `// install.js for v${version}\n`,
|
||||
"package.json": `${JSON.stringify({ name: "plan2code", version }, null, 2)}\n`,
|
||||
"version.json": `${JSON.stringify({ version, releaseDate: "2026-01-01" }, null, 2)}\n`,
|
||||
"src/web-console/update-check.mjs": `// update-check for v${version}\n`,
|
||||
"docs/promo.md": `# heavy docs for v${version}\n`,
|
||||
};
|
||||
}
|
||||
|
||||
/** The slim runtime payload of a synthetic install commit: the full tree minus what the spec excludes. */
|
||||
function slimTreeFiles(version, sourceCommitMark) {
|
||||
const files = fullTreeFiles(version);
|
||||
delete files["docs/promo.md"];
|
||||
files[".plan2code-install-ref.json"] = `${JSON.stringify({ releaseRef: `v${version}`, sourceCommit: `mark-${sourceCommitMark}` }, null, 2)}\n`;
|
||||
return files;
|
||||
}
|
||||
|
||||
// fast-import streams are length-delimited: `data <n>` plus exactly n bytes.
|
||||
// Strings are UTF-8; Buffers stay byte-exact, so a real binary runtime file can
|
||||
// ride in a fixture without being corrupted.
|
||||
function dataBlock(content) {
|
||||
const body = Buffer.isBuffer(content) ? content : Buffer.from(String(content), "utf8");
|
||||
return Buffer.concat([Buffer.from(`data ${body.length}\n`, "utf8"), body]);
|
||||
}
|
||||
const textBlock = (text) => Buffer.from(String(text), "utf8");
|
||||
const person = (who, ts) => `${who} Fixture <fixture@example.com> ${ts} +0000`;
|
||||
|
||||
/** One commit command with its whole tree inline (`M ... inline` needs no blob commands or index), as byte parts. */
|
||||
function commitCommand(ref, mark, message, files, ts, fromMark) {
|
||||
const parts = [textBlock(`commit ${ref}\nmark :${mark}\n${person("author", ts)}\n${person("committer", ts)}\n`), dataBlock(message)];
|
||||
if (fromMark) parts.push(textBlock(`from :${fromMark}\n`));
|
||||
for (const [name, content] of Object.entries(files)) parts.push(textBlock(`M 100644 inline ${name}\n`), dataBlock(content));
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function createInstallRefFixture({
|
||||
releases = DEFAULT_RELEASES,
|
||||
releaseBranch = true,
|
||||
releaseVersion = null,
|
||||
featureBranches = ["feature/demo"],
|
||||
extraTags = ["nightly"],
|
||||
mainBranch = "main",
|
||||
} = {}) {
|
||||
if (!Array.isArray(releases) || releases.length === 0) throw new Error("createInstallRefFixture: releases must be a non-empty array");
|
||||
const root = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-install-refs-"));
|
||||
const dir = path.join(root, "origin.git");
|
||||
|
||||
const env = scrubbedEnv();
|
||||
const git = (args, options = {}) => execFileSync("git", ["--git-dir", dir, ...args], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], env, ...options }).trim();
|
||||
|
||||
execFileSync("git", ["init", "-q", "--bare", "-b", mainBranch, dir], { env, stdio: "pipe" });
|
||||
|
||||
// Newest-first ordering is derived numerically, never lexically: 3.10.0
|
||||
// must outrank 3.9.0 for the release branch and `newest` to be right.
|
||||
const ordered = [...releases].sort((a, b) => compareVersions(a.version, b.version) ?? 0);
|
||||
|
||||
// The whole repository as one stream: main commits auto-parent per ref, the
|
||||
// synthetic chain rides on refs/heads/release for the same reason, and
|
||||
// resets pin the lightweight tags, feature branches and extra tags. Three
|
||||
// git processes build a fixture (init, fast-import, for-each-ref) where the
|
||||
// plumbing equivalent needs dozens — on Windows that is seconds each.
|
||||
const stream = [];
|
||||
const push = (text) => stream.push(textBlock(text));
|
||||
const pushCommit = (...args) => stream.push(...commitCommand(...args));
|
||||
let mark = 0;
|
||||
let ts = 1700000000;
|
||||
const versions = [];
|
||||
let mainMark = null;
|
||||
let syntheticMark = null;
|
||||
for (const release of ordered) {
|
||||
const { version, annotated = false, installTag = false } = release;
|
||||
mainMark = ++mark;
|
||||
ts += 60;
|
||||
const fullFiles = release.files || fullTreeFiles(version);
|
||||
pushCommit(`refs/heads/${mainBranch}`, mainMark, `release ${version}\n`, fullFiles, ts);
|
||||
const entry = { version, annotated, install: null, mainMark };
|
||||
|
||||
if (annotated) {
|
||||
push(`tag v${version}\nfrom :${mainMark}\n${person("tagger", ts)}\n`);
|
||||
stream.push(dataBlock(`release ${version}\n`));
|
||||
} else {
|
||||
push(`reset refs/tags/v${version}\nfrom :${mainMark}\n`);
|
||||
}
|
||||
|
||||
if (installTag) {
|
||||
syntheticMark = ++mark;
|
||||
entry.install = { mark: syntheticMark };
|
||||
pushCommit("refs/heads/release", syntheticMark, `install payload ${version}\n`, release.installFiles || slimTreeFiles(version, mainMark), ts);
|
||||
push(`reset refs/tags/install-v${version}\nfrom :${syntheticMark}\n`);
|
||||
}
|
||||
versions.push(entry);
|
||||
}
|
||||
|
||||
const newest = ordered[ordered.length - 1].version;
|
||||
for (const branch of featureBranches) push(`reset refs/heads/${branch}\nfrom :${mainMark}\n`);
|
||||
for (const name of extraTags) push(`reset refs/tags/${name}\nfrom :${mainMark}\n`);
|
||||
|
||||
// The published shape: the release branch tip is a synthetic slim commit.
|
||||
// It already is (the chain built it there) unless the fixture pins a stale
|
||||
// tip or no synthetic ref exists at all, where it is a legacy full-source
|
||||
// tip on main instead.
|
||||
let releaseTipMark = null;
|
||||
if (releaseBranch) {
|
||||
const pinned = releaseVersion ? versions.find((v) => v.version === releaseVersion) : null;
|
||||
if (releaseVersion && !pinned) throw new Error(`createInstallRefFixture: releaseVersion ${releaseVersion} is not one of the releases`);
|
||||
if (pinned) releaseTipMark = pinned.install ? pinned.install.mark : pinned.mainMark;
|
||||
else if (!syntheticMark) releaseTipMark = mainMark;
|
||||
if (releaseTipMark) push(`reset refs/heads/release\nfrom :${releaseTipMark}\n`);
|
||||
}
|
||||
|
||||
git(["fast-import", "--quiet"], { input: Buffer.concat(stream) });
|
||||
if (!releaseBranch) git(["update-ref", "-d", "refs/heads/release"]);
|
||||
|
||||
// The shas fast-import wrote, in one process: objecttype names the annotated
|
||||
// tag objects, and %(*objectname) peels them to their commits.
|
||||
const listing = git(["for-each-ref", "--format", "%(refname) %(objectname) %(objecttype) %(*objectname)"]);
|
||||
const refs = { heads: {}, tags: {}, peeled: {} };
|
||||
for (const line of listing.split("\n")) {
|
||||
if (!line) continue;
|
||||
const [ref, sha, type, peeled] = line.split(" ");
|
||||
if (ref.startsWith("refs/heads/")) refs.heads[ref.slice("refs/heads/".length)] = sha;
|
||||
else if (ref.startsWith("refs/tags/")) {
|
||||
refs.tags[ref.slice("refs/tags/".length)] = sha;
|
||||
if (type === "tag" && peeled) refs.peeled[ref.slice("refs/tags/".length)] = peeled;
|
||||
}
|
||||
}
|
||||
for (const entry of versions) {
|
||||
// The commit a release tag names: its peeled target when annotated, the ref target otherwise.
|
||||
entry.commit = refs.peeled[`v${entry.version}`] || refs.tags[`v${entry.version}`];
|
||||
if (entry.install) entry.install.commit = refs.tags[`install-v${entry.version}`];
|
||||
}
|
||||
|
||||
/**
|
||||
* `git ls-remote`-style snapshot text, derived from the refs recorded at
|
||||
* build time: one `<sha>\t<ref>` line per ref, sorted by ref name the way
|
||||
* git sorts them, with a peeled `^{}` line immediately after each annotated
|
||||
* tag. Matches real ls-remote output byte for byte for these fixtures (the
|
||||
* test file asserts exactly that), so it can seed PLAN2CODE_LS_REMOTE_FILE
|
||||
* without spawning anything.
|
||||
*/
|
||||
function snapshotText({ tags = true, heads = true } = {}) {
|
||||
const entries = [];
|
||||
if (heads) for (const [name, sha] of Object.entries(refs.heads)) entries.push([`refs/heads/${name}`, sha, null]);
|
||||
if (tags) {
|
||||
for (const [name, sha] of Object.entries(refs.tags)) entries.push([`refs/tags/${name}`, sha, refs.peeled[name] || null]);
|
||||
}
|
||||
entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
||||
let out = "";
|
||||
for (const [ref, sha, peel] of entries) {
|
||||
out += `${sha}\t${ref}\n`;
|
||||
if (peel) out += `${peel}\t${ref}^{}\n`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The real thing: `git ls-remote` against the bare repo on disk. Local-path transport, so offline. */
|
||||
function lsRemote({ tags = true, heads = true } = {}) {
|
||||
const args = ["ls-remote"];
|
||||
if (tags) args.push("--tags");
|
||||
if (heads) args.push("--heads");
|
||||
return execFileSync("git", [...args, dir], { encoding: "utf8", env });
|
||||
}
|
||||
|
||||
/**
|
||||
* A real local fetch of one ref into `dest`, laid out like an npx package
|
||||
* rather than a working clone: the payload is complete, and `.git` is gone.
|
||||
* The transport is the fixture's local path, so no network or credentials.
|
||||
*/
|
||||
function checkout(ref, dest) {
|
||||
fs.rmSync(dest, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||||
execFileSync("git", ["clone", "--quiet", "--depth", "1", "--branch", ref, dir, dest], { encoding: "utf8", env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
fs.rmSync(path.join(dest, ".git"), { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
return dest;
|
||||
}
|
||||
|
||||
let cleaned = false;
|
||||
function cleanup() {
|
||||
if (cleaned) return;
|
||||
cleaned = true;
|
||||
// maxRetries for Windows, where a just-exited git can hold a pack file
|
||||
// for a beat; read-only object files are chmodded away by rm itself.
|
||||
fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
|
||||
return { dir, root, refs, versions, newest, mainBranch, snapshotText, lsRemote, checkout, cleanup };
|
||||
}
|
||||
@@ -0,0 +1,638 @@
|
||||
#!/usr/bin/env node
|
||||
// Publishes the slim install refs of one release: a synthetic commit whose tree
|
||||
// holds only the runtime payload (install.js, package.json, version.json and
|
||||
// src/) plus a binding manifest, pushed once as the immutable
|
||||
// `refs/tags/install-vX.Y.Z` and as the new fast-forward tip of
|
||||
// `refs/heads/release`. Dev-only: lives in scripts/ so it never ships inside a
|
||||
// skill or the runtime payload it assembles.
|
||||
//
|
||||
// node scripts/publish-install-refs.mjs --tag v3.2.3 --repo "$GITHUB_WORKSPACE"
|
||||
//
|
||||
// Runs in the full release checkout of .github/workflows/release-app.yml,
|
||||
// after the GitHub release is public. The payload is read from the source
|
||||
// tag's own git tree, never from the working tree, and the commit is built
|
||||
// with a temporary index, so the checkout and its normal index are never
|
||||
// touched. Zero dependencies: Node built-ins and the git on PATH.
|
||||
//
|
||||
// Exit codes: 0 published (or a dry run that would publish), 1 refused or
|
||||
// failed (nothing pushed), 2 bad arguments.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const INSTALL_REF_MANIFEST = ".plan2code-install-ref.json";
|
||||
// The package scripts that make npm prepare a git dependency with a full dev install (pacote).
|
||||
const GIT_DEP_LIFECYCLE = new Set(["prepare", "build", "install", "preinstall", "postinstall", "prepack"]);
|
||||
export const RELEASE_BRANCH_REF = "refs/heads/release";
|
||||
export const REMOTE = "origin";
|
||||
const TAG_SHAPE = /^v(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/**
|
||||
* The runtime payload, as data: exactly these top-level files plus the
|
||||
* recursive trees under `prefixes`, minus any path with an `excludedSegments`
|
||||
* folder in it. `forbiddenTopLevel` names what must never appear (reported on
|
||||
* its own when it does), and `required` the files an install cannot run
|
||||
* without; the workflow skill sources install.js's SOURCE_PROMPTS names are
|
||||
* required on top of these (`workflowSkillSources()`).
|
||||
*/
|
||||
export const RUNTIME_PAYLOAD = Object.freeze({
|
||||
files: Object.freeze(["install.js", "package.json", "version.json"]),
|
||||
prefixes: Object.freeze(["src/"]),
|
||||
excludedSegments: Object.freeze(["node_modules", ".git", "fixtures", "__fixtures__"]),
|
||||
forbiddenTopLevel: Object.freeze([
|
||||
".git",
|
||||
".github",
|
||||
"docs",
|
||||
"scripts",
|
||||
"specs",
|
||||
"skills",
|
||||
"plan2code-app",
|
||||
"plan2code-metrics",
|
||||
"plan2code-bot",
|
||||
]),
|
||||
required: Object.freeze([
|
||||
"install.js",
|
||||
"package.json",
|
||||
"version.json",
|
||||
"src/launcher/plan2code.js",
|
||||
"src/web-console/update-check.mjs",
|
||||
"src/web-console/console.mjs",
|
||||
"src/installer/timing.js",
|
||||
"src/installer/skills-cli.js",
|
||||
"src/installer/canonical-skills.js",
|
||||
"src/installer/console-stage.js",
|
||||
// Read by install.js at runtime too: the skills' forwarding stub, the status line, the
|
||||
// launcher's model menu, agent list and lookup, and the desktop shortcut's icons.
|
||||
"src/web-console-stub/console.mjs",
|
||||
"src/statusline-claude/statusline.js",
|
||||
"src/launcher/models.json",
|
||||
"src/launcher/agents.json",
|
||||
"src/web-console/agent-lookup.mjs",
|
||||
"src/launcher/plan2code.ico",
|
||||
"src/web-console/public/favicon.png",
|
||||
]),
|
||||
});
|
||||
|
||||
/** The allowlist the payload is assembled and validated against. */
|
||||
export function runtimePayloadAllowlist() {
|
||||
return RUNTIME_PAYLOAD;
|
||||
}
|
||||
|
||||
/** Whether a `/`-separated path relative to the payload root belongs in the payload. */
|
||||
export function isAllowedPayloadPath(rel, allowlist = RUNTIME_PAYLOAD) {
|
||||
if (typeof rel !== "string" || rel === "" || rel.startsWith("/") || rel.includes("\\")) return false;
|
||||
const parts = rel.split("/");
|
||||
if (parts.some((p) => p === "" || p === "." || p === "..")) return false;
|
||||
if (allowlist.forbiddenTopLevel.includes(parts[0])) return false;
|
||||
if (allowlist.files.includes(rel)) return true;
|
||||
if (!allowlist.prefixes.some((prefix) => rel.startsWith(prefix) && rel.length > prefix.length)) return false;
|
||||
return !parts.slice(0, -1).some((p) => allowlist.excludedSegments.includes(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* What install.js builds the skills from, read from its SOURCE_PROMPTS array:
|
||||
* each top-level `source: '<name>.md'` as `src/<name>.md`, each shared script
|
||||
* a `scripts: [...]` list names (plus SHARED_SCRIPTS_ALWAYS) as
|
||||
* `src/skill-scripts/<name>`, and each `additionalReferences` `{ source: ... }`
|
||||
* as `src/<source>` (a file or a folder). An empty list means the array could
|
||||
* not be read, which validation reports.
|
||||
*/
|
||||
export function workflowSkillSources(installJsText) {
|
||||
const start = installJsText.indexOf("const SOURCE_PROMPTS = [");
|
||||
if (start === -1) return [];
|
||||
const end = installJsText.indexOf("\n];", start);
|
||||
const block = installJsText.slice(start, end === -1 ? undefined : end);
|
||||
const names = (list) => [...list.matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
|
||||
const sources = [...block.matchAll(/^ {4}source: ['"]([^'"]+\.md)['"]/gm)].map((m) => `src/${m[1]}`);
|
||||
if (!sources.length) return [];
|
||||
const shared = [...block.matchAll(/^ {4}scripts: \[([^\]]*)\]/gm)].flatMap((m) => names(m[1]));
|
||||
const always = /^const SHARED_SCRIPTS_ALWAYS = \[([^\]]*)\]/m.exec(installJsText);
|
||||
if (shared.length && always) shared.push(...names(always[1]));
|
||||
const references = [...block.matchAll(/\{ source: ['"]([^'"]+)['"]/g)].map((m) => `src/${m[1]}`);
|
||||
return [...new Set([...sources, ...shared.map((name) => `src/skill-scripts/${name}`), ...references])];
|
||||
}
|
||||
|
||||
export class PublishError extends Error {
|
||||
constructor(message, details = null) {
|
||||
super(message);
|
||||
this.name = "PublishError";
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
// Credentials can ride in a remote URL (https://user:token@host); git echoes
|
||||
// URLs in its errors, so every message that leaves this script goes through this.
|
||||
const redact = (text) => String(text).replace(/(\/\/)[^/\s@]+@/g, "$1***@");
|
||||
|
||||
function git(repo, args, { input, env, allowFail = false, encoding = "utf8" } = {}) {
|
||||
const r = spawnSync("git", ["-C", repo, ...args], {
|
||||
input,
|
||||
env: env || process.env,
|
||||
encoding: encoding === "buffer" ? undefined : encoding,
|
||||
maxBuffer: 1024 * 1024 * 1024,
|
||||
windowsHide: true,
|
||||
});
|
||||
if (r.error) throw new PublishError(`git ${args[0]} could not run: ${redact(r.error.message)}`);
|
||||
if (r.status !== 0 && !allowFail) {
|
||||
const stderr = Buffer.isBuffer(r.stderr) ? r.stderr.toString("utf8") : r.stderr || "";
|
||||
throw new PublishError(`git ${args[0]} failed: ${redact(stderr.trim() || `exit ${r.status}`)}`);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
const gitText = (repo, args, options) => git(repo, args, options).stdout.trim();
|
||||
|
||||
/** The commit a ref names, or null when it does not exist (annotated tags peel to their commit). */
|
||||
function commitOf(repo, ref) {
|
||||
const r = git(repo, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFail: true });
|
||||
return r.status === 0 ? r.stdout.trim() : null;
|
||||
}
|
||||
|
||||
function readJsonAt(repo, commit, file) {
|
||||
const r = git(repo, ["show", `${commit}:${file}`], { allowFail: true });
|
||||
if (r.status !== 0) throw new PublishError(`${file} is missing from the source commit ${commit}`);
|
||||
try {
|
||||
return JSON.parse(r.stdout);
|
||||
} catch (err) {
|
||||
throw new PublishError(`${file} in the source commit is not valid JSON: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the source tag and checks that the tag, its version.json, its root
|
||||
* package.json and the checkout agree before anything is written. The tag may
|
||||
* be annotated or lightweight. `sourceCommit`, when given, stands in for HEAD.
|
||||
*/
|
||||
export function verifySource({ repo, tag, sourceCommit = null }) {
|
||||
const shape = TAG_SHAPE.exec(tag || "");
|
||||
if (!shape) throw new PublishError(`the source tag must be an exact vX.Y.Z release tag, not "${tag}"`);
|
||||
const version = shape[1];
|
||||
const tagCommit = commitOf(repo, `refs/tags/${tag}`);
|
||||
if (!tagCommit) throw new PublishError(`the tag ${tag} does not exist in ${repo}; fetch it first`);
|
||||
const checkout = sourceCommit ? commitOf(repo, sourceCommit) : commitOf(repo, "HEAD");
|
||||
if (!checkout) throw new PublishError(`the source commit ${sourceCommit || "HEAD"} cannot be resolved`);
|
||||
if (checkout !== tagCommit) {
|
||||
throw new PublishError(`${sourceCommit ? "the supplied source commit" : "the checkout's HEAD"} ${checkout} is not the commit ${tag} names (${tagCommit})`);
|
||||
}
|
||||
const versionJson = readJsonAt(repo, tagCommit, "version.json");
|
||||
const packageJson = readJsonAt(repo, tagCommit, "package.json");
|
||||
const mismatches = [];
|
||||
if (versionJson.version !== version) mismatches.push(`version.json says ${versionJson.version}`);
|
||||
if (packageJson.version !== version) mismatches.push(`package.json says ${packageJson.version}`);
|
||||
if (mismatches.length) throw new PublishError(`the versions do not match the tag ${tag}: ${mismatches.join(", ")}`);
|
||||
// npm runs a full dev-dependency install for a git package that has one of these scripts, so
|
||||
// every user's npx would download the dev tools (Playwright and the rest) before installing.
|
||||
const lifecycle = Object.keys(packageJson.scripts || {}).filter((name) => GIT_DEP_LIFECYCLE.has(name));
|
||||
if (lifecycle.length) {
|
||||
throw new PublishError(`package.json has ${lifecycle.join(", ")}: npm would install every dev dependency on each user's machine before the installer runs; remove the script or rename it`);
|
||||
}
|
||||
return { version, sourceTag: tag, sourceCommit: tagCommit };
|
||||
}
|
||||
|
||||
/** Every `{ mode, type, sha, path }` in a commit's tree, recursively. */
|
||||
function treeEntries(repo, commit) {
|
||||
const out = gitText(repo, ["ls-tree", "-r", "-z", "--full-tree", commit]).split("\0");
|
||||
const entries = [];
|
||||
for (const line of out) {
|
||||
if (!line) continue;
|
||||
const tab = line.indexOf("\t");
|
||||
const [mode, type, sha] = line.slice(0, tab).split(" ");
|
||||
entries.push({ mode, type, sha, path: line.slice(tab + 1) });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** The contents of many blobs from one `git cat-file --batch`, in order. */
|
||||
function readBlobs(repo, shas) {
|
||||
if (!shas.length) return [];
|
||||
const out = git(repo, ["cat-file", "--batch"], { input: `${shas.join("\n")}\n`, encoding: "buffer" }).stdout;
|
||||
const blobs = [];
|
||||
let at = 0;
|
||||
for (const sha of shas) {
|
||||
const nl = out.indexOf(0x0a, at);
|
||||
const header = out.subarray(at, nl).toString("utf8").split(" ");
|
||||
if (header[0] !== sha || header[1] !== "blob") throw new PublishError(`git cat-file could not read blob ${sha}`);
|
||||
const size = Number(header[2]);
|
||||
blobs.push(out.subarray(nl + 1, nl + 1 + size));
|
||||
at = nl + 1 + size + 1;
|
||||
}
|
||||
return blobs;
|
||||
}
|
||||
|
||||
function ensureEmptyDir(dir) {
|
||||
if (fs.existsSync(dir)) {
|
||||
if (!fs.statSync(dir).isDirectory()) throw new PublishError(`the output ${dir} is not a folder`);
|
||||
if (fs.readdirSync(dir).length) throw new PublishError(`the output folder ${dir} is not empty`);
|
||||
} else {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the allowlisted files of `commit`'s tree into the clean folder
|
||||
* `output`, keeping each file's git mode (an executable 100755 stays one).
|
||||
* Returns `{ output, modes, excluded }`: `modes` maps each payload path to its
|
||||
* mode, `excluded` counts the tree's files left out.
|
||||
*/
|
||||
export function assemblePayload({ repo, commit, output, allowlist = RUNTIME_PAYLOAD }) {
|
||||
ensureEmptyDir(output);
|
||||
const picked = [];
|
||||
let excluded = 0;
|
||||
for (const entry of treeEntries(repo, commit)) {
|
||||
if (!isAllowedPayloadPath(entry.path, allowlist)) {
|
||||
excluded++;
|
||||
continue;
|
||||
}
|
||||
if (entry.type !== "blob" || (entry.mode !== "100644" && entry.mode !== "100755")) {
|
||||
throw new PublishError(`${entry.path} is a ${entry.mode === "120000" ? "symlink" : entry.type} (mode ${entry.mode}); the payload holds regular files only`);
|
||||
}
|
||||
picked.push(entry);
|
||||
}
|
||||
const blobs = readBlobs(
|
||||
repo,
|
||||
picked.map((e) => e.sha),
|
||||
);
|
||||
const modes = {};
|
||||
picked.forEach((entry, i) => {
|
||||
const dest = path.join(output, ...entry.path.split("/"));
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||||
fs.writeFileSync(dest, blobs[i]);
|
||||
if (entry.mode === "100755") fs.chmodSync(dest, 0o755);
|
||||
modes[entry.path] = entry.mode;
|
||||
});
|
||||
return { output, modes, excluded };
|
||||
}
|
||||
|
||||
/** Every file under `dir`, as sorted `/`-separated relative paths; symlinks are listed in `links`. */
|
||||
function walk(dir) {
|
||||
const files = [];
|
||||
const links = [];
|
||||
const visit = (abs, rel) => {
|
||||
for (const name of fs.readdirSync(abs)) {
|
||||
const childAbs = path.join(abs, name);
|
||||
const childRel = rel ? `${rel}/${name}` : name;
|
||||
const st = fs.lstatSync(childAbs);
|
||||
if (st.isSymbolicLink()) links.push(childRel);
|
||||
else if (st.isDirectory()) visit(childAbs, childRel);
|
||||
else files.push(childRel);
|
||||
}
|
||||
};
|
||||
visit(dir, "");
|
||||
return { files: files.sort(), links: links.sort() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks an assembled payload folder: every required file present (including
|
||||
* every skill build input its install.js names), nothing outside the
|
||||
* allowlist and no forbidden top-level entry. `report` is a diff-like list:
|
||||
* `- path` missing, `+ path` unexpected.
|
||||
*/
|
||||
export function validatePayload(dir, { allowlist = RUNTIME_PAYLOAD } = {}) {
|
||||
const { files, links } = walk(dir);
|
||||
const present = new Set(files);
|
||||
const required = [...allowlist.required];
|
||||
if (present.has("install.js")) {
|
||||
const sources = workflowSkillSources(fs.readFileSync(path.join(dir, "install.js"), "utf8"));
|
||||
if (!sources.length) required.push("install.js SOURCE_PROMPTS (no workflow skill sources found)");
|
||||
required.push(...sources);
|
||||
}
|
||||
// A required folder (a reference such as src/web-console) is present when it holds a file.
|
||||
const has = (rel) => present.has(rel) || files.some((f) => f.startsWith(`${rel}/`));
|
||||
const missing = [...new Set(required)].filter((rel) => !has(rel)).sort();
|
||||
const unexpected = [...files.filter((rel) => rel !== INSTALL_REF_MANIFEST && !isAllowedPayloadPath(rel, allowlist)), ...links.map((rel) => `${rel} (symlink)`)].sort();
|
||||
const topLevel = new Set([...files, ...links].map((rel) => rel.split("/")[0]));
|
||||
const forbidden = allowlist.forbiddenTopLevel.filter((name) => topLevel.has(name));
|
||||
const bytes = files.reduce((sum, rel) => sum + fs.statSync(path.join(dir, ...rel.split("/"))).size, 0);
|
||||
const report = [...missing.map((rel) => `- ${rel}`), ...unexpected.map((rel) => `+ ${rel}`), ...forbidden.map((name) => `+ ${name}/ (forbidden top-level entry)`)];
|
||||
return {
|
||||
ok: !missing.length && !unexpected.length && !forbidden.length,
|
||||
files: files.length,
|
||||
bytes,
|
||||
manifest: present.has(INSTALL_REF_MANIFEST),
|
||||
missing,
|
||||
unexpected,
|
||||
forbidden,
|
||||
report,
|
||||
};
|
||||
}
|
||||
|
||||
const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
|
||||
|
||||
/**
|
||||
* Writes `.plan2code-install-ref.json` at the payload root, binding it to
|
||||
* its release: `{ kind, version, sourceTag, sourceCommit, files }`, `files`
|
||||
* mapping every other payload path to its sha256. Hashed first, written last.
|
||||
*/
|
||||
export function writeInstallRefManifest(dir, { version, sourceTag, sourceCommit }) {
|
||||
const files = {};
|
||||
for (const rel of walk(dir).files) {
|
||||
if (rel === INSTALL_REF_MANIFEST) continue;
|
||||
files[rel] = sha256(fs.readFileSync(path.join(dir, ...rel.split("/"))));
|
||||
}
|
||||
const manifest = { kind: "install-ref", version, sourceTag, sourceCommit, files };
|
||||
fs.writeFileSync(path.join(dir, INSTALL_REF_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
// commit-tree needs an author and committer. A release runner has none
|
||||
// configured, so the GitHub Actions bot stands in unless git or the
|
||||
// environment already names one.
|
||||
const BOT = { name: "github-actions[bot]", email: "41898099+github-actions[bot]@users.noreply.github.com" };
|
||||
|
||||
function identityEnv(repo, base) {
|
||||
const env = { ...base };
|
||||
const configured = (key) => git(repo, ["config", "--get", key], { allowFail: true }).stdout.trim();
|
||||
const name = configured("user.name");
|
||||
const email = configured("user.email");
|
||||
for (const role of ["AUTHOR", "COMMITTER"]) {
|
||||
if (!env[`GIT_${role}_NAME`] && !name) env[`GIT_${role}_NAME`] = BOT.name;
|
||||
if (!env[`GIT_${role}_EMAIL`] && !email) env[`GIT_${role}_EMAIL`] = BOT.email;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
// Windows caps a command line near 32K characters; stay far below it.
|
||||
const MAX_ARGS_CHARS = 8000;
|
||||
|
||||
/**
|
||||
* Builds the synthetic commit from the payload folder with a temporary
|
||||
* GIT_INDEX_FILE inside the repository's git dir: an empty index, blobs
|
||||
* written with `hash-object -w`, entries added with `update-index --cacheinfo`,
|
||||
* `write-tree`, then `commit-tree` on `parent`. The checkout's working tree
|
||||
* and normal index are never touched. Returns `{ tree, commit }`.
|
||||
*/
|
||||
export function createSyntheticCommit({ repo, dir, modes, parent, message }) {
|
||||
const gitDir = gitText(repo, ["rev-parse", "--absolute-git-dir"]);
|
||||
const indexFile = path.join(gitDir, `p2c-install-index-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
|
||||
const env = { ...process.env, GIT_INDEX_FILE: indexFile };
|
||||
const removeIndex = () => {
|
||||
fs.rmSync(indexFile, { force: true });
|
||||
fs.rmSync(`${indexFile}.lock`, { force: true });
|
||||
};
|
||||
removeIndex();
|
||||
try {
|
||||
const files = walk(dir).files;
|
||||
const abs = files.map((rel) => path.join(dir, ...rel.split("/")));
|
||||
const shas = gitText(repo, ["hash-object", "-w", "--no-filters", "--stdin-paths"], { input: `${abs.join("\n")}\n`, env }).split(/\r?\n/);
|
||||
if (shas.length !== files.length) throw new PublishError(`git hash-object returned ${shas.length} ids for ${files.length} files`);
|
||||
let batch = [];
|
||||
let chars = 0;
|
||||
const flush = () => {
|
||||
if (!batch.length) return;
|
||||
git(repo, ["update-index", "--add", ...batch], { env });
|
||||
batch = [];
|
||||
chars = 0;
|
||||
};
|
||||
files.forEach((rel, i) => {
|
||||
const info = `${modes[rel] || "100644"},${shas[i]},${rel}`;
|
||||
if (chars + info.length > MAX_ARGS_CHARS) flush();
|
||||
batch.push("--cacheinfo", info);
|
||||
chars += info.length + 13;
|
||||
});
|
||||
flush();
|
||||
const tree = gitText(repo, ["write-tree"], { env });
|
||||
const commit = gitText(repo, ["commit-tree", tree, "-p", parent, "-F", "-"], { input: message, env: identityEnv(repo, env) });
|
||||
return { tree, commit };
|
||||
} finally {
|
||||
removeIndex();
|
||||
}
|
||||
}
|
||||
|
||||
/** The remote's sha for each ref asked about, from one `git ls-remote`; absent refs are left out. */
|
||||
function remoteRefs(repo, remote, refs) {
|
||||
const r = git(repo, ["ls-remote", remote, ...refs], { allowFail: true });
|
||||
if (r.status !== 0) throw new PublishError(`git ls-remote ${remote} failed: ${redact(r.stderr.trim() || `exit ${r.status}`)}`);
|
||||
const found = {};
|
||||
for (const line of r.stdout.split(/\r?\n/)) {
|
||||
const [sha, ref] = line.split("\t");
|
||||
if (sha && ref && refs.includes(ref)) found[ref] = sha;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The parent of the new synthetic commit: the remote release branch's tip when
|
||||
* it exists (the first migration parents the legacy full-source tip only so
|
||||
* the push stays a fast-forward); with no release branch, the source tag's
|
||||
* commit, but only when `allowMissingReleaseBranch` says so.
|
||||
*/
|
||||
export function selectParent({ repo, releaseTip, sourceCommit, allowMissingReleaseBranch }) {
|
||||
if (releaseTip) {
|
||||
if (!commitOf(repo, releaseTip)) {
|
||||
throw new PublishError(`the release branch tip ${releaseTip} is not in this checkout; fetch ${RELEASE_BRANCH_REF} first`);
|
||||
}
|
||||
return { parent: releaseTip, parentKind: "release" };
|
||||
}
|
||||
if (allowMissingReleaseBranch) return { parent: sourceCommit, parentKind: "source-tag" };
|
||||
throw new PublishError(`${RELEASE_BRANCH_REF} does not exist on ${REMOTE}; pass --allow-missing-release-branch for a first publication`);
|
||||
}
|
||||
|
||||
/** Refuses an install tag that already exists here or on the remote: install tags are never overwritten. */
|
||||
export function checkInstallTagFree({ repo, installTagRef, remoteHas }) {
|
||||
const local = git(repo, ["rev-parse", "--verify", "--quiet", installTagRef], { allowFail: true }).status === 0;
|
||||
if (local || remoteHas) {
|
||||
throw new PublishError(`${installTagRef} already exists ${local && remoteHas ? "here and on the remote" : local ? "in this checkout" : "on the remote"}; install tags are immutable and are never overwritten`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Negative, zero or positive as `a` (X.Y.Z) is below, equal to or above `b`. */
|
||||
function compareReleaseVersions(a, b) {
|
||||
const pa = a.split(".").map(Number);
|
||||
const pb = b.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i];
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** readJsonAt, or null when the file is not in that commit or does not parse. */
|
||||
function readJsonAtOrNull(repo, commit, file) {
|
||||
try {
|
||||
return readJsonAt(repo, commit, file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The version the release branch tip installs: its install-ref manifest's, else its version.json
|
||||
* (a legacy full-source tip), else null when neither can be read.
|
||||
*/
|
||||
export function releaseTipVersion(repo, releaseTip) {
|
||||
if (!releaseTip) return null;
|
||||
const manifest = readJsonAtOrNull(repo, releaseTip, INSTALL_REF_MANIFEST);
|
||||
if (manifest && typeof manifest.version === "string") return manifest.version;
|
||||
const versionJson = readJsonAtOrNull(repo, releaseTip, "version.json");
|
||||
return versionJson && typeof versionJson.version === "string" ? versionJson.version : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to point the release branch at a version that is not newer than the one it installs
|
||||
* now: a hotfix tagged from a maintenance branch, or two publications finishing out of order,
|
||||
* would otherwise send every README install back to an older release. `allowOlder` is the
|
||||
* explicit override for a deliberate rollback.
|
||||
*/
|
||||
export function checkNewerThanRelease({ repo, releaseTip, version, allowOlder = false }) {
|
||||
if (allowOlder || !releaseTip) return;
|
||||
const current = releaseTipVersion(repo, releaseTip);
|
||||
if (current && compareReleaseVersions(version, current) <= 0) {
|
||||
throw new PublishError(`the release branch already installs ${current}; refusing to move it to ${version}, which is not newer (pass --allow-older for a deliberate rollback)`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this release is already fully published: the install tag exists on the remote, the
|
||||
* release branch points at it, and its manifest names this release's source commit. A second run
|
||||
* for the same tag (the workflow has more than one trigger) then has nothing to do.
|
||||
*/
|
||||
export function alreadyPublished({ repo, remoteTag, releaseTip, sourceCommit }) {
|
||||
if (!remoteTag || remoteTag !== releaseTip) return false;
|
||||
const manifest = readJsonAtOrNull(repo, remoteTag, INSTALL_REF_MANIFEST);
|
||||
return Boolean(manifest && manifest.sourceCommit === sourceCommit);
|
||||
}
|
||||
|
||||
/** Refuses a release branch move that would not be a fast-forward. */
|
||||
export function checkFastForward({ repo, priorTip, commit }) {
|
||||
if (!priorTip) return;
|
||||
const r = git(repo, ["merge-base", "--is-ancestor", priorTip, commit], { allowFail: true });
|
||||
if (r.status !== 0) throw new PublishError(`the release branch tip ${priorTip} is not an ancestor of ${commit}; refusing a non-fast-forward move`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes one release's slim install refs: verify the source, assemble and
|
||||
* validate the payload, write the manifest, build one synthetic commit, check
|
||||
* collision and fast-forward, then push that commit to both refs in one
|
||||
* command (unless `dryRun`). Returns the summary the CLI prints as JSON.
|
||||
*/
|
||||
export function publishInstallRefs({ tag, version = null, repo, dryRun = false, output = null, allowMissingReleaseBranch = false, sourceCommit = null, allowOlder = false }) {
|
||||
repo = path.resolve(repo || process.cwd());
|
||||
const source = verifySource({ repo, tag, sourceCommit });
|
||||
if (version && version !== source.version) throw new PublishError(`the version ${version} does not match the tag ${tag}`);
|
||||
const installTagRef = `refs/tags/install-${tag}`;
|
||||
const remote = remoteRefs(repo, REMOTE, [installTagRef, RELEASE_BRANCH_REF]);
|
||||
const releaseTip = remote[RELEASE_BRANCH_REF] || null;
|
||||
if (alreadyPublished({ repo, remoteTag: remote[installTagRef] || null, releaseTip, sourceCommit: source.sourceCommit })) {
|
||||
return { ok: true, dryRun, pushed: false, alreadyPublished: true, tag, version: source.version, sourceCommit: source.sourceCommit, commit: releaseTip, refs: { tag: installTagRef, branch: RELEASE_BRANCH_REF } };
|
||||
}
|
||||
checkInstallTagFree({ repo, installTagRef, remoteHas: Boolean(remote[installTagRef]) });
|
||||
checkNewerThanRelease({ repo, releaseTip, version: source.version, allowOlder });
|
||||
const { parent, parentKind } = selectParent({ repo, releaseTip, sourceCommit: source.sourceCommit, allowMissingReleaseBranch });
|
||||
|
||||
const keep = Boolean(output);
|
||||
const dir = keep ? path.resolve(output) : fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-payload-"));
|
||||
try {
|
||||
const { modes, excluded } = assemblePayload({ repo, commit: source.sourceCommit, output: dir });
|
||||
const before = validatePayload(dir);
|
||||
if (!before.ok) throw new PublishError(`the runtime payload of ${tag} is not valid`, before.report);
|
||||
writeInstallRefManifest(dir, source);
|
||||
const validation = validatePayload(dir);
|
||||
if (!validation.ok || !validation.manifest) throw new PublishError(`the runtime payload of ${tag} is not valid after the manifest was written`, validation.report);
|
||||
|
||||
const message = `Install payload for ${tag}\n\nSource commit: ${source.sourceCommit}\n`;
|
||||
const { tree, commit } = createSyntheticCommit({ repo, dir, modes, parent, message });
|
||||
checkFastForward({ repo, priorTip: releaseTip, commit });
|
||||
|
||||
if (!dryRun) git(repo, ["push", "--atomic", REMOTE, `${commit}:${installTagRef}`, `${commit}:${RELEASE_BRANCH_REF}`]);
|
||||
return {
|
||||
ok: true,
|
||||
dryRun,
|
||||
pushed: !dryRun,
|
||||
tag,
|
||||
version: source.version,
|
||||
sourceCommit: source.sourceCommit,
|
||||
commit,
|
||||
tree,
|
||||
parent,
|
||||
parentKind,
|
||||
files: validation.files,
|
||||
bytes: validation.bytes,
|
||||
excluded,
|
||||
manifest: INSTALL_REF_MANIFEST,
|
||||
refs: { tag: installTagRef, branch: RELEASE_BRANCH_REF },
|
||||
payload: keep ? dir : null,
|
||||
validation: { missing: validation.missing, unexpected: validation.unexpected, forbidden: validation.forbidden },
|
||||
};
|
||||
} finally {
|
||||
if (!keep) fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export const USAGE = `Usage: node scripts/publish-install-refs.mjs --tag vX.Y.Z [options]
|
||||
|
||||
Publishes the slim runtime payload of a release as refs/tags/install-vX.Y.Z and
|
||||
the new fast-forward tip of refs/heads/release, in one push to origin.
|
||||
|
||||
--tag <vX.Y.Z> the release tag (required, exact vX.Y.Z)
|
||||
--repo <checkout> the full release checkout (default: the current folder)
|
||||
--output <dir> assemble the payload into this empty folder and keep it
|
||||
--dry-run build and check everything, push nothing
|
||||
--json <path> also write the result as JSON to this file
|
||||
--allow-missing-release-branch first publication: parent the source tag's commit
|
||||
when refs/heads/release does not exist yet
|
||||
--allow-older move refs/heads/release even when it already installs
|
||||
this version or a newer one (a deliberate rollback)
|
||||
`;
|
||||
|
||||
/** `{ options }` from argv, or `{ error }` for anything unknown, missing or malformed. */
|
||||
export function parseArgs(argv) {
|
||||
const options = { tag: null, repo: null, output: null, dryRun: false, json: null, allowMissingReleaseBranch: false, allowOlder: false };
|
||||
const valued = { "--tag": "tag", "--repo": "repo", "--output": "output", "--json": "json" };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg in valued) {
|
||||
const value = argv[++i];
|
||||
if (value === undefined || value.startsWith("--")) return { error: `${arg} needs a value` };
|
||||
options[valued[arg]] = value;
|
||||
} else if (arg === "--dry-run") options.dryRun = true;
|
||||
else if (arg === "--allow-missing-release-branch") options.allowMissingReleaseBranch = true;
|
||||
else if (arg === "--allow-older") options.allowOlder = true;
|
||||
else return { error: `unknown argument: ${arg}` };
|
||||
}
|
||||
if (!options.tag) return { error: "--tag is required" };
|
||||
if (!TAG_SHAPE.test(options.tag)) return { error: `--tag must be an exact vX.Y.Z release tag, not "${options.tag}"` };
|
||||
return { options };
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const parsed = parseArgs(argv);
|
||||
if (parsed.error) {
|
||||
process.stderr.write(`${parsed.error}\n\n${USAGE}`);
|
||||
return 2;
|
||||
}
|
||||
const { options } = parsed;
|
||||
const writeJson = (value) => {
|
||||
if (options.json) fs.writeFileSync(options.json, `${JSON.stringify(value, null, 2)}\n`);
|
||||
};
|
||||
try {
|
||||
const result = publishInstallRefs({
|
||||
tag: options.tag,
|
||||
repo: options.repo || process.cwd(),
|
||||
dryRun: options.dryRun,
|
||||
output: options.output,
|
||||
allowMissingReleaseBranch: options.allowMissingReleaseBranch,
|
||||
allowOlder: options.allowOlder,
|
||||
});
|
||||
writeJson(result);
|
||||
if (result.alreadyPublished) {
|
||||
process.stdout.write(`${result.tag} is already published: ${result.refs.tag} and ${result.refs.branch} point at ${result.commit}\n`);
|
||||
return 0;
|
||||
}
|
||||
const verb = result.dryRun ? "Would publish" : "Published";
|
||||
process.stdout.write(
|
||||
`${verb} ${result.commit} (tree ${result.tree}) to ${result.refs.tag} and ${result.refs.branch}\n` +
|
||||
` parent ${result.parent} (${result.parentKind}), ${result.files} files, ${result.bytes} bytes, ${result.excluded} source files left out\n`,
|
||||
);
|
||||
return 0;
|
||||
} catch (err) {
|
||||
if (!(err instanceof PublishError)) throw err;
|
||||
writeJson({ ok: false, error: err.message, details: err.details });
|
||||
process.stderr.write(`publish-install-refs: ${err.message}\n${err.details ? `${err.details.join("\n")}\n` : ""}Nothing was pushed.\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
// 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);
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
// End-to-end installer validation against real local git refs. The fetches are
|
||||
// real `git clone`s from a bare fixture, the installer is the repository's real
|
||||
// install.js, and every write lands in an isolated HOME/npm/console/app-data
|
||||
// tree. The only stand-ins are a cached no-op skills CLI (the seam production
|
||||
// uses for an already-warm npx cache); release app assets are deliberately
|
||||
// unreachable here, while their successful checksum path stays in
|
||||
// test-install-update.mjs. Nothing here contacts GitHub or the npm registry.
|
||||
|
||||
import "./skill-script-helpers.mjs";
|
||||
|
||||
import test, { after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { installRefForRelease, chooseReleaseRef, parseLsRemoteSnapshot } from "../src/web-console/update-check.mjs";
|
||||
import {
|
||||
createInstallE2EFixture,
|
||||
installE2EExists,
|
||||
installE2EJson,
|
||||
installLocalNpxShim,
|
||||
launcherRunEnvironment,
|
||||
makeInstallE2ERunRoot,
|
||||
readSkillsCliLog,
|
||||
runFixtureInstaller,
|
||||
writeFixtureSnapshot,
|
||||
} from "./install-e2e-fixture.mjs";
|
||||
|
||||
let fixtureInstance = null;
|
||||
function fixture() {
|
||||
if (!fixtureInstance) fixtureInstance = createInstallE2EFixture();
|
||||
return fixtureInstance;
|
||||
}
|
||||
after(() => fixtureInstance?.cleanup());
|
||||
|
||||
function readJson(file) {
|
||||
return JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
}
|
||||
|
||||
function timingEvents(run) {
|
||||
try {
|
||||
return fs
|
||||
.readFileSync(run.isolated.paths.benchJson, "utf8")
|
||||
.split(/\r?\n/)
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function assertInstallerSucceeded(run) {
|
||||
assert.equal(run.result.error, undefined, run.result.error?.message || "");
|
||||
assert.equal(run.result.status, 0, `stdout:\n${run.stdout}\nstderr:\n${run.stderr}`);
|
||||
}
|
||||
|
||||
function runInstalledLauncher(run, env, args) {
|
||||
const launcher = path.join(run.isolated.paths.home, ".plan2code", "bin", "plan2code.js");
|
||||
const result = spawnSync(process.execPath, [launcher, ...args], { env, encoding: "utf8", input: "", timeout: 240000, windowsHide: true });
|
||||
return { result, stdout: result.stdout || "", stderr: result.stderr || "" };
|
||||
}
|
||||
|
||||
function assertLauncherSucceeded(run) {
|
||||
assert.equal(run.result.error, undefined, run.result.error?.message || "");
|
||||
assert.equal(run.result.status, 0, `stdout:\n${run.stdout}\nstderr:\n${run.stderr}`);
|
||||
}
|
||||
|
||||
function readJsonLines(file) {
|
||||
try {
|
||||
return fs
|
||||
.readFileSync(file, "utf8")
|
||||
.split(/\r?\n/)
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function canonicalManifest(run) {
|
||||
return installE2EJson(run, ".agents", "skills", ".plan2code-canonical.json");
|
||||
}
|
||||
|
||||
function consoleMarker(run, version) {
|
||||
return readJson(path.join(run.isolated.paths.consoleHome, version, ".complete"));
|
||||
}
|
||||
|
||||
test("fixture: local refs carry installable full-source releases and slim synthetic payloads", (t) => {
|
||||
const fx = fixture();
|
||||
const full = path.join(fx.root, "check-full");
|
||||
const slim = path.join(fx.root, "check-slim");
|
||||
fx.checkout("v1.0.0", full);
|
||||
fx.checkout("install-v3.1.2", slim);
|
||||
t.after(() => {
|
||||
fs.rmSync(full, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
fs.rmSync(slim, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
});
|
||||
|
||||
for (const required of [
|
||||
"install.js",
|
||||
"package.json",
|
||||
"version.json",
|
||||
"src/launcher/plan2code.js",
|
||||
"src/web-console/console.mjs",
|
||||
"src/web-console/update-check.mjs",
|
||||
"src/installer/timing.js",
|
||||
"src/installer/skills-cli.js",
|
||||
"src/installer/canonical-skills.js",
|
||||
"src/installer/console-stage.js",
|
||||
]) {
|
||||
assert.ok(fs.existsSync(path.join(slim, ...required.split("/"))), required);
|
||||
}
|
||||
assert.ok(fs.existsSync(path.join(full, "docs", "promo.md")), "the plain heavy tag carries documentation");
|
||||
assert.ok(!fs.existsSync(path.join(slim, "docs", "promo.md")), "the synthetic payload drops documentation");
|
||||
assert.ok(fs.existsSync(path.join(slim, ".plan2code-install-ref.json")), "the synthetic payload is bound by its manifest");
|
||||
assert.ok(!fs.existsSync(path.join(full, ".plan2code-install-ref.json")), "the plain source tag is not mistaken for a synthetic payload");
|
||||
assert.ok(fs.existsSync(path.join(slim, "src", "launcher", "plan2code.ico")), "binary runtime files survive the fixture byte-for-byte path");
|
||||
});
|
||||
|
||||
// Launcher-style fetch: the launcher sets PLAN2CODE_INSTALL_REF and PLAN2CODE_RELEASE_REF, a bare
|
||||
// README `npx ...#release` run sets neither. The old-launcher redirect is covered in
|
||||
// scripts/test-install-update.mjs ("release redirect: ..."), against a stand-in npx.
|
||||
test("e2e: a launcher-style first install through #release installs the newest slim payload completely", async (t) => {
|
||||
const fx = fixture();
|
||||
const root = makeInstallE2ERunRoot();
|
||||
const run = runFixtureInstaller(fx, { ref: "release", releaseRef: "v3.1.2", root });
|
||||
t.after(run.cleanup);
|
||||
|
||||
assertInstallerSucceeded(run);
|
||||
assert.match(run.stdout, /Updating to 3\.1\.2/);
|
||||
assert.match(run.stdout, /Installing desktop app…/, "compact unattended progress names the long app phase before it runs");
|
||||
assert.match(run.stdout, /Plan2Code is up to date \(v3\.1\.2\)/);
|
||||
assert.ok(!fs.existsSync(path.join(run.checkout, "docs")), "the fetched release payload is slim");
|
||||
assert.ok(fs.existsSync(path.join(run.checkout, ".plan2code-install-ref.json")), "the fetched payload is synthetic");
|
||||
|
||||
const record = installE2EJson(run, ".plan2code", "install.json");
|
||||
assert.equal(record.version, "3.1.2");
|
||||
assert.equal(record.scope, "global");
|
||||
assert.deepEqual(record.pieces, ["launcher", "skills"]);
|
||||
assert.equal(installE2EJson(run, ".plan2code", "bin", "version.json").version, "3.1.2");
|
||||
assert.ok(!installE2EExists(run, ".plan2code", "app", process.platform === "win32" ? "plan2code-app.exe" : "plan2code-app"), "the deliberately unreachable app asset did not stop the required pieces");
|
||||
|
||||
const canonical = canonicalManifest(run);
|
||||
assert.equal(canonical.version, "3.1.2");
|
||||
assert.equal(canonical.sourceRef, "v3.1.2");
|
||||
assert.equal(canonical.complete, true);
|
||||
assert.equal(canonical.journal, null);
|
||||
assert.ok(Object.keys(canonical.skills).length >= 20, "every workflow skill is in the canonical manifest");
|
||||
assert.equal(consoleMarker(run, "3.1.2").version, "3.1.2");
|
||||
assert.ok(fs.existsSync(path.join(run.isolated.paths.consoleHome, "3.1.2", ".plan2code-console-manifest.json")), "the console manifest is present");
|
||||
assert.equal(fs.readFileSync(path.join(run.isolated.paths.consoleHome, "console-dir"), "utf8").trim(), path.join(run.isolated.paths.consoleHome, "3.1.2"), "console-dir names the complete version folder");
|
||||
});
|
||||
|
||||
test("e2e: exact updates roll back through install tags and fall back to a plain heavy tag", async (t) => {
|
||||
const fx = fixture();
|
||||
const root = makeInstallE2ERunRoot();
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
|
||||
|
||||
const snapshot = parseLsRemoteSnapshot(fx.lsRemote());
|
||||
assert.deepEqual(chooseReleaseRef(snapshot), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true, version: "3.1.2" });
|
||||
assert.deepEqual(installRefForRelease("v2.0.0", snapshot), { releaseRef: "v2.0.0", fetchRef: "install-v2.0.0", synthetic: true });
|
||||
assert.deepEqual(installRefForRelease("v1.0.0", snapshot), { releaseRef: "v1.0.0", fetchRef: "v1.0.0", synthetic: false });
|
||||
|
||||
const newest = runFixtureInstaller(fx, { ref: "install-v3.1.2", releaseRef: "v3.1.2", root });
|
||||
assertInstallerSucceeded(newest);
|
||||
assert.equal(installE2EJson(newest, ".plan2code", "install.json").version, "3.1.2");
|
||||
assert.equal(canonicalManifest(newest).version, "3.1.2");
|
||||
assert.ok(fs.existsSync(path.join(newest.checkout, ".plan2code-install-ref.json")));
|
||||
|
||||
const shim = installLocalNpxShim(root, fx);
|
||||
const lsRemoteFile = writeFixtureSnapshot(fx, root);
|
||||
const launcherEnv = launcherRunEnvironment(newest, { bin: shim.bin, lsRemoteFile });
|
||||
const npxLogFile = path.join(root, "local-npx.jsonl");
|
||||
launcherEnv.PLAN2CODE_LOCAL_NPX_LOG = npxLogFile;
|
||||
|
||||
const rollback = runInstalledLauncher(newest, launcherEnv, ["update", "--tag", "v2.0.0"]);
|
||||
assertLauncherSucceeded(rollback);
|
||||
assert.match(rollback.stdout, /Updating 3\.1\.2 -> 2\.0\.0/);
|
||||
assert.equal(installE2EJson(newest, ".plan2code", "install.json").version, "2.0.0");
|
||||
assert.equal(canonicalManifest(newest).version, "2.0.0");
|
||||
assert.equal(consoleMarker(newest, "2.0.0").version, "2.0.0");
|
||||
let npxLog = readJsonLines(npxLogFile);
|
||||
assert.equal(npxLog.length, 1);
|
||||
assert.equal(npxLog[0].ref, "install-v2.0.0", "the launcher mapped the logical rollback to its slim immutable tag");
|
||||
assert.equal(npxLog[0].synthetic, true);
|
||||
assert.equal(npxLog[0].docs, false);
|
||||
assert.deepEqual(npxLog[0].rest, ["--update"]);
|
||||
|
||||
const plain = runInstalledLauncher(newest, launcherEnv, ["update", "--tag", "v1.0.0"]);
|
||||
assertLauncherSucceeded(plain);
|
||||
assert.match(plain.stdout, /Updating 2\.0\.0 -> 1\.0\.0/);
|
||||
assert.equal(installE2EJson(newest, ".plan2code", "install.json").version, "1.0.0");
|
||||
assert.equal(canonicalManifest(newest).version, "1.0.0");
|
||||
npxLog = readJsonLines(npxLogFile);
|
||||
assert.equal(npxLog.length, 2);
|
||||
assert.equal(npxLog[1].ref, "v1.0.0", "the no-synthetic rollback stayed on the plain tag");
|
||||
assert.equal(npxLog[1].synthetic, false);
|
||||
assert.equal(npxLog[1].docs, true, "the fallback fetched the heavy full-source tree");
|
||||
|
||||
fs.mkdirSync(path.join(newest.isolated.paths.home, ".plan2code", "notepads"), { recursive: true });
|
||||
fs.writeFileSync(path.join(newest.isolated.paths.home, ".plan2code", "notepads", "keep.txt"), "personal data stays\n");
|
||||
const uninstall = runInstalledLauncher(newest, launcherEnv, ["uninstall", "--yes"]);
|
||||
assertLauncherSucceeded(uninstall);
|
||||
assert.match(uninstall.stdout, /Plan2Code is uninstalled/);
|
||||
npxLog = readJsonLines(npxLogFile);
|
||||
assert.equal(npxLog.length, 3);
|
||||
assert.equal(npxLog[2].ref, "install-v3.1.2", "uninstall used the newest release's slim installer, not the installed rollback");
|
||||
assert.deepEqual(npxLog[2].rest, ["--uninstall", "--yes"]);
|
||||
assert.equal(installE2EJson(newest, ".plan2code", "install.json"), null, "the install record is removed");
|
||||
assert.ok(!installE2EExists(newest, ".plan2code", "bin", "plan2code.js"), "the launcher copy is removed");
|
||||
assert.ok(!installE2EExists(newest, ".plan2code", "app", process.platform === "win32" ? "plan2code-app.exe" : "plan2code-app"), "the desktop app file is removed");
|
||||
assert.ok(!installE2EExists(newest, ".agents", "skills", "plan2code"), "the canonical skills are removed");
|
||||
assert.equal(fs.readFileSync(path.join(newest.isolated.paths.home, ".plan2code", "notepads", "keep.txt"), "utf8"), "personal data stays\n");
|
||||
});
|
||||
|
||||
test("e2e: --main and a branch --tag stay on the intentional refs the launcher was given", async (t) => {
|
||||
const fx = fixture();
|
||||
const root = makeInstallE2ERunRoot();
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
|
||||
const initial = runFixtureInstaller(fx, { ref: "release", releaseRef: "v3.1.2", root });
|
||||
assertInstallerSucceeded(initial);
|
||||
|
||||
const shim = installLocalNpxShim(root, fx);
|
||||
const launcherEnv = launcherRunEnvironment(initial, { bin: shim.bin, lsRemoteFile: writeFixtureSnapshot(fx, root) });
|
||||
const npxLogFile = path.join(root, "local-npx.jsonl");
|
||||
launcherEnv.PLAN2CODE_LOCAL_NPX_LOG = npxLogFile;
|
||||
|
||||
const main = runInstalledLauncher(initial, launcherEnv, ["update", "--main", "--force"]);
|
||||
assertLauncherSucceeded(main);
|
||||
assert.equal(canonicalManifest(initial).sourceRef, "main", "main is stamped as main, never redirected onto a release");
|
||||
let npxLog = readJsonLines(npxLogFile);
|
||||
assert.equal(npxLog.length, 1);
|
||||
assert.equal(npxLog[0].ref, "main");
|
||||
assert.equal(npxLog[0].synthetic, false);
|
||||
assert.equal(npxLog[0].docs, true, "main intentionally fetches the full-source tree");
|
||||
assert.deepEqual(npxLog[0].rest, ["--update", "--force"]);
|
||||
|
||||
const branch = runInstalledLauncher(initial, launcherEnv, ["update", "--tag", "feature/demo", "--force"]);
|
||||
assertLauncherSucceeded(branch);
|
||||
assert.equal(canonicalManifest(initial).sourceRef, "feature/demo", "a branch tag is stamped as that branch");
|
||||
npxLog = readJsonLines(npxLogFile);
|
||||
assert.equal(npxLog.length, 2);
|
||||
assert.equal(npxLog[1].ref, "feature/demo");
|
||||
assert.equal(npxLog[1].synthetic, false);
|
||||
assert.equal(npxLog[1].docs, true);
|
||||
assert.deepEqual(npxLog[1].rest, ["--update", "--force"]);
|
||||
});
|
||||
|
||||
test("e2e: canonical link refresh and benchmark events carry the selected ref without secrets", async (t) => {
|
||||
const fx = fixture();
|
||||
const root = makeInstallE2ERunRoot();
|
||||
// A sentinel the installer can read (install.js takes GH_TOKEN for release assets) must never
|
||||
// reach stdout, stderr or the timing JSONL.
|
||||
const sentinel = "p2c-e2e-sentinel-6f1d0c9a";
|
||||
const run = runFixtureInstaller(fx, { ref: "install-v2.0.0", releaseRef: "v2.0.0", root, planted: { GH_TOKEN: sentinel } });
|
||||
assert.equal(run.env.GH_TOKEN, sentinel, "the sentinel reached the installer's environment");
|
||||
t.after(run.cleanup);
|
||||
assertInstallerSucceeded(run);
|
||||
|
||||
const cli = readSkillsCliLog(run.cliLog);
|
||||
assert.equal(cli.length, 1, "one canonical-source link refresh, not one CLI add per skill");
|
||||
assert.equal(cli[0].argv[0], "add");
|
||||
assert.equal(cli[0].argv[1], path.join(run.isolated.paths.home, ".agents", "skills"));
|
||||
assert.ok(cli[0].argv.includes("-g"));
|
||||
assert.ok(cli[0].argv.includes("plan2code-3-implement-review"));
|
||||
|
||||
const events = timingEvents(run);
|
||||
const names = events.map((event) => event.event);
|
||||
for (const required of ["installer-start", "skills-built", "console-committed", "canonical-committed", "links-refreshed", "installer-end"]) {
|
||||
assert.ok(names.includes(required), `missing ${required}: ${names.join(",")}`);
|
||||
}
|
||||
assert.equal(events.find((event) => event.event === "installer-start").ref, "install-v2.0.0");
|
||||
assert.equal(canonicalManifest(run).sourceRef, "v2.0.0", "the logical release ref is stamped separately from the fetch ref");
|
||||
const artifact = fs.readFileSync(run.isolated.paths.benchJson, "utf8") + run.stdout + run.stderr;
|
||||
assert.ok(!artifact.includes(sentinel), "a token the installer can read is never copied into its output or timing events");
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
// Tests for the local git-ref fixtures of scripts/install-ref-fixtures.mjs,
|
||||
// which later phases reuse to test ref resolution, redirect classification and
|
||||
// rollback without network access. Run with: node --test scripts/test-install-refs.mjs
|
||||
//
|
||||
// skill-script-helpers.mjs is imported first on purpose: it scrubs the whole
|
||||
// test process's git config, so the fixtures, the modules they use and any
|
||||
// spawned git agree (the AGENTS.md failure-log rule). The fixtures themselves
|
||||
// are real bare repositories in the OS temp dir; `git ls-remote` against a
|
||||
// local path never touches the network.
|
||||
|
||||
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 { execFileSync, spawnSync } from "node:child_process";
|
||||
|
||||
import "./skill-script-helpers.mjs";
|
||||
import { createInstallRefFixture, DEFAULT_RELEASES } from "./install-ref-fixtures.mjs";
|
||||
import { latestTag } from "../src/web-console/update-check.mjs";
|
||||
|
||||
/** `git <args>` inside a fixture's bare repo, for type/sha checks. */
|
||||
const gitIn = (dir, args) => execFileSync("git", ["--git-dir", dir, ...args], { encoding: "utf8" }).trim();
|
||||
|
||||
const SHA = /^[0-9a-f]{40}$/;
|
||||
|
||||
test("fixture: a bare repository in a temp dir, no working tree", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.ok(fx.root.startsWith(fs.realpathSync.native(os.tmpdir())), "the fixture lives in the OS temp dir");
|
||||
assert.ok(fs.existsSync(path.join(fx.dir, "HEAD")), "a git dir");
|
||||
assert.equal(gitIn(fx.dir, ["rev-parse", "--is-bare-repository"]), "true");
|
||||
assert.equal(fs.existsSync(path.join(fx.root, "install.js")), false, "nothing is checked out beside it");
|
||||
});
|
||||
|
||||
test("fixture: main and feature branches exist and point at real commits", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.match(fx.refs.heads.main, SHA);
|
||||
assert.match(fx.refs.heads["feature/demo"], SHA);
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/heads/main"]), "commit");
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/heads/feature/demo"]), "commit");
|
||||
// A custom branch set is honored.
|
||||
const custom = createInstallRefFixture({ featureBranches: ["feature/one", "bugfix/two"] });
|
||||
t.after(custom.cleanup);
|
||||
assert.deepEqual(Object.keys(custom.refs.heads).sort(), ["bugfix/two", "feature/one", "main", "release"].sort());
|
||||
});
|
||||
|
||||
test("fixture: lightweight v* tags point straight at commits", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v1.0.0"]), "commit");
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v2.0.0"]), "commit", "the default v2.0.0 is lightweight");
|
||||
assert.equal(fx.refs.peeled["v1.0.0"], undefined, "no peeled line for a lightweight tag");
|
||||
});
|
||||
|
||||
test("fixture: annotated v* tags are tag objects and produce peeled ^{} lines", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v3.1.2"]), "tag", "the ref names a tag object");
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v3.1.2^{commit}"]), "commit");
|
||||
// The tag object sha and the peeled commit sha differ, and both are recorded.
|
||||
assert.notEqual(fx.refs.tags["v3.1.2"], fx.refs.peeled["v3.1.2"]);
|
||||
assert.match(fx.refs.tags["v3.1.2"], SHA);
|
||||
assert.match(fx.refs.peeled["v3.1.2"], SHA);
|
||||
// Peeled lines are in the real ls-remote output and in the derived snapshot.
|
||||
const peeledLine = `${fx.refs.peeled["v3.1.2"]}\trefs/tags/v3.1.2^{}`;
|
||||
assert.ok(fx.lsRemote().includes(peeledLine), "real output");
|
||||
assert.ok(fx.snapshotText().includes(peeledLine), "derived output");
|
||||
// Exactly one peeled line: lightweight tags never grow one.
|
||||
assert.equal(fx.snapshotText().split("^{}").length - 1, 1);
|
||||
});
|
||||
|
||||
test("fixture: synthetic install-v* tags exist for the configured versions only", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.match(fx.refs.tags["install-v3.1.2"], SHA);
|
||||
assert.match(fx.refs.tags["install-v2.0.0"], SHA);
|
||||
assert.equal(fx.refs.tags["install-v1.0.0"], undefined, "v1.0.0 has no synthetic ref: the rollback fallback case");
|
||||
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/install-v3.1.2"]), "commit");
|
||||
// The slim payload carries its binding manifest and none of the heavy docs.
|
||||
const listing = gitIn(fx.dir, ["ls-tree", "-r", "--name-only", "refs/tags/install-v3.1.2"]);
|
||||
assert.ok(listing.split("\n").includes(".plan2code-install-ref.json"));
|
||||
assert.ok(!listing.split("\n").some((n) => n.startsWith("docs/")), "the synthetic tree is slim");
|
||||
assert.ok(gitIn(fx.dir, ["ls-tree", "-r", "--name-only", "refs/tags/v3.1.2^{commit}"]).split("\n").some((n) => n.startsWith("docs/")), "the full tree is not");
|
||||
});
|
||||
|
||||
test("fixture: rollback versions exist, oldest to newest, and numeric ordering beats lexical", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const versions = fx.versions.map((v) => v.version);
|
||||
assert.deepEqual(versions, ["1.0.0", "2.0.0", "3.1.2"]);
|
||||
assert.equal(fx.newest, "3.1.2");
|
||||
// Every rollback target resolves to its own commit on main.
|
||||
for (const v of fx.versions) assert.equal(gitIn(fx.dir, ["rev-parse", `refs/tags/v${v.version}^{commit}`]), v.commit);
|
||||
// A 3.10.0 release outranks 3.9.0 numerically (lexical order would pick 3.9.0).
|
||||
const numeric = createInstallRefFixture({ releases: [{ version: "3.10.0" }, { version: "3.9.0" }] });
|
||||
t.after(numeric.cleanup);
|
||||
assert.equal(numeric.newest, "3.10.0");
|
||||
assert.deepEqual(numeric.versions.map((v) => v.version), ["3.9.0", "3.10.0"]);
|
||||
});
|
||||
|
||||
test("fixture: the release branch is present by default at the newest synthetic tip, or absent", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.match(fx.refs.heads.release, SHA);
|
||||
assert.equal(fx.refs.heads.release, fx.refs.tags["install-v3.1.2"], "the published shape: release is the slim tip");
|
||||
|
||||
const absent = createInstallRefFixture({ releaseBranch: false });
|
||||
t.after(absent.cleanup);
|
||||
assert.equal(absent.refs.heads.release, undefined);
|
||||
assert.equal(absent.snapshotText().includes("refs/heads/release"), false);
|
||||
assert.equal(absent.lsRemote().includes("refs/heads/release"), false);
|
||||
const verify = spawnSync("git", ["--git-dir", absent.dir, "rev-parse", "--verify", "-q", "refs/heads/release"], { encoding: "utf8" });
|
||||
assert.notEqual(verify.status, 0, "git itself agrees the branch is absent");
|
||||
});
|
||||
|
||||
test("fixture: the release branch can pin a stale or legacy tip", (t) => {
|
||||
// A stale moving release: still on the older version's synthetic commit.
|
||||
const stale = createInstallRefFixture({ releaseVersion: "2.0.0" });
|
||||
t.after(stale.cleanup);
|
||||
assert.equal(stale.refs.heads.release, stale.refs.tags["install-v2.0.0"]);
|
||||
assert.notEqual(stale.refs.heads.release, stale.refs.tags["install-v3.1.2"]);
|
||||
// No synthetic refs at all: a legacy full-source release branch on main's tip.
|
||||
const legacy = createInstallRefFixture({ releases: [{ version: "1.0.0" }, { version: "2.0.0" }] });
|
||||
t.after(legacy.cleanup);
|
||||
assert.equal(legacy.refs.heads.release, legacy.refs.heads.main);
|
||||
assert.throws(() => createInstallRefFixture({ releaseVersion: "9.9.9" }), /not one of the releases/);
|
||||
});
|
||||
|
||||
test("fixture: the derived snapshot matches real git ls-remote output byte for byte", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
assert.equal(fx.snapshotText(), fx.lsRemote(), "--tags --heads");
|
||||
assert.equal(fx.snapshotText({ heads: false }), fx.lsRemote({ heads: false }), "tags only");
|
||||
assert.equal(fx.snapshotText({ tags: false }), fx.lsRemote({ tags: false }), "heads only");
|
||||
// Every line is a sha, a tab and a ref: the shape the installer parses.
|
||||
for (const line of fx.snapshotText().trimEnd().split("\n")) {
|
||||
assert.match(line, /^[0-9a-f]{40}\trefs\/(heads|tags)\/[^\s]+(\^\{\})?$/, line);
|
||||
}
|
||||
});
|
||||
|
||||
test("fixture: the shipped parser reads the snapshot as a consumer would", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
// update-check.mjs's latestTag is the plain-release compatibility API the
|
||||
// console notice uses; the snapshot must give it the newest plain release.
|
||||
assert.equal(latestTag(fx.snapshotText()), "3.1.2");
|
||||
assert.equal(latestTag(fx.snapshotText({ heads: false })), "3.1.2");
|
||||
// install-v* and nightly tags never count as plain releases.
|
||||
assert.ok(!fx.snapshotText().split("\n").some((l) => /refs\/tags\/v\d+\.\d+\.\d+$/.test(l) && l.includes("install-")));
|
||||
});
|
||||
|
||||
test("fixture: two fixtures are independent and a non-release tag is there to be ignored", (t) => {
|
||||
const a = createInstallRefFixture();
|
||||
const b = createInstallRefFixture();
|
||||
t.after(a.cleanup);
|
||||
t.after(b.cleanup);
|
||||
assert.notEqual(a.dir, b.dir);
|
||||
assert.ok(fs.existsSync(a.dir) && fs.existsSync(b.dir));
|
||||
// The default extra tag rides on main's tip and is not a release shape.
|
||||
assert.match(a.refs.tags.nightly, SHA);
|
||||
assert.equal(gitIn(a.dir, ["rev-parse", "refs/tags/nightly"]), a.refs.heads.main);
|
||||
assert.equal(latestTag(a.snapshotText().replace(/^.*refs\/tags\/v3\.1\.2.*$\n?/gm, "")), "2.0.0", "nightly never interferes");
|
||||
});
|
||||
|
||||
test("fixture: cleanup removes everything and is reliable when repeated", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
assert.ok(fs.existsSync(fx.dir));
|
||||
fx.cleanup();
|
||||
assert.equal(fs.existsSync(fx.root), false, "the temp root and every object in it are gone");
|
||||
fx.cleanup();
|
||||
fx.cleanup();
|
||||
assert.equal(fs.existsSync(fx.root), false, "repeated cleanup neither throws nor resurrects");
|
||||
// The temp dir is not littered when several fixtures cycle. Each fixture's own root is
|
||||
// checked, never a count of the whole temp dir: other test files build fixtures alongside.
|
||||
const ones = [createInstallRefFixture(), createInstallRefFixture(), createInstallRefFixture()];
|
||||
for (const one of ones) one.cleanup();
|
||||
for (const one of ones) assert.equal(fs.existsSync(one.root), false, one.root);
|
||||
t.after(() => {}); // nothing to sweep: cleanup already ran, and idempotently so
|
||||
});
|
||||
|
||||
test("fixture: default releases cover the rollback matrix the spec asks for", () => {
|
||||
// Documentation-by-test for later phases: what createInstallRefFixture()
|
||||
// builds with no options.
|
||||
const matrix = DEFAULT_RELEASES.map((r) => ({ version: r.version, annotated: !!r.annotated, installTag: !!r.installTag }));
|
||||
assert.deepEqual(matrix, [
|
||||
{ version: "1.0.0", annotated: false, installTag: false },
|
||||
{ version: "2.0.0", annotated: false, installTag: true },
|
||||
{ version: "3.1.2", annotated: true, installTag: true },
|
||||
]);
|
||||
});
|
||||
+1524
-32
File diff suppressed because it is too large.
Load diff
@@ -11,8 +11,11 @@
|
||||
"test-check-versions.mjs",
|
||||
"test-getting-started.mjs",
|
||||
"test-git-repo.mjs",
|
||||
"test-install-bench.mjs",
|
||||
"test-install-refs.mjs",
|
||||
"test-install-update.mjs",
|
||||
"test-line-endings.mjs",
|
||||
"test-publish-install-refs.mjs",
|
||||
"test-script-changelog.mjs",
|
||||
"test-script-changes.mjs",
|
||||
"test-script-coverage.mjs",
|
||||
@@ -52,6 +55,7 @@
|
||||
"test-console-stub.mjs",
|
||||
"test-console-wire-budgets.mjs",
|
||||
"test-fast.mjs",
|
||||
"test-install-e2e.mjs",
|
||||
"test-launcher.mjs",
|
||||
"test-standalone-check.mjs",
|
||||
"test-ui-prototype-page.mjs",
|
||||
|
||||
+130
-2
@@ -14,6 +14,11 @@ import { spawn, spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// Imported before anything builds a git fixture: it scrubs the whole test process's git config
|
||||
// (the AGENTS.md failure-log rule), so the ref fixtures below and git agree.
|
||||
import "./skill-script-helpers.mjs";
|
||||
import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
||||
@@ -60,6 +65,8 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
'require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".json"), JSON.stringify(process.argv.slice(3)));\n' +
|
||||
// The ref the launcher marks its installer runs with, so install.js never redirects them.
|
||||
'if (process.env.PLAN2CODE_INSTALL_REF) require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".ref"), process.env.PLAN2CODE_INSTALL_REF);\n' +
|
||||
// The logical release a fetch ref stands for (an install-vX.Y.Z fetch is still vX.Y.Z).
|
||||
'if (process.env.PLAN2CODE_RELEASE_REF) require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".release"), process.env.PLAN2CODE_RELEASE_REF);\n' +
|
||||
"process.exitCode = Number(process.env.P2C_TEST_EXIT || 0);\n"
|
||||
);
|
||||
for (const cli of clis) {
|
||||
@@ -536,16 +543,137 @@ test("launcher: update --tag reinstalls for a branch, and not for a release tag"
|
||||
assert.ok(args.includes(`${REPO}#v3.0.2`) && !args.includes("--force"), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --tag installs that ref without asking for the release list", (t) => {
|
||||
test("launcher: update --tag installs the plain release tag when the ref list cannot be read", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
// No tag list is available at all: --tag must not need one.
|
||||
// No tag list is available at all: --tag must not need one, and falls back to the plain tag.
|
||||
const result = box.run(["update", "--tag", "v3.0.2"], { PLAN2CODE_LS_REMOTE_FILE: path.join(box.dir, "missing.txt") });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.0\.2\.\.\./);
|
||||
assert.ok(box.argsOf("npx").includes(`${REPO}#v3.0.2`), box.argsOf("npx").join(" "));
|
||||
});
|
||||
|
||||
/** A fixture's `git ls-remote --tags --heads` answer, written where the launcher reads it in git's place. */
|
||||
function fixtureStub(box, text) {
|
||||
const file = path.join(box.dir, "ls-remote-fixture.txt");
|
||||
fs.writeFileSync(file, text);
|
||||
return { PLAN2CODE_LS_REMOTE_FILE: file };
|
||||
}
|
||||
|
||||
/** What the last npx run got (its arguments, the fetch ref and the release ref it was marked with), cleared for the next run. */
|
||||
function lastInstall(box) {
|
||||
const bin = path.join(box.dir, "bin");
|
||||
const read = (name) => {
|
||||
const file = path.join(bin, name);
|
||||
if (!fs.existsSync(file)) return null;
|
||||
const text = fs.readFileSync(file, "utf8");
|
||||
fs.rmSync(file);
|
||||
return text;
|
||||
};
|
||||
const args = read("npx.json");
|
||||
return { args: args && JSON.parse(args), ref: read("npx.ref"), releaseRef: read("npx.release") };
|
||||
}
|
||||
|
||||
test("launcher: update fetches the newest release's install tag and names the logical release", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"], fixtureStub(box, fx.snapshotText()));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.1\.2\.\.\./);
|
||||
assert.doesNotMatch(result.stdout, /install-v/, "the person reads the release, never the fetch ref");
|
||||
const { args, ref, releaseRef } = lastInstall(box);
|
||||
assert.deepEqual(args, ["--yes", "--allow-git=all", `${REPO}#install-v3.1.2`, "--update"]);
|
||||
assert.equal(ref, "install-v3.1.2");
|
||||
assert.equal(releaseRef, "v3.1.2");
|
||||
});
|
||||
|
||||
test("launcher: update ignores a stale moving release branch and falls back to plain tags when no install tag is advertised", (t) => {
|
||||
const stale = createInstallRefFixture({ releaseVersion: "2.0.0" });
|
||||
t.after(stale.cleanup);
|
||||
const legacy = createInstallRefFixture({ releases: [{ version: "1.0.0" }, { version: "2.0.0", annotated: true }] });
|
||||
t.after(legacy.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update"], fixtureStub(box, stale.snapshotText())).status, 0);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#install-v3.1.2`, "--update"], ref: "install-v3.1.2", releaseRef: "v3.1.2" });
|
||||
const result = box.run(["update"], fixtureStub(box, legacy.snapshotText()));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v2\.0\.0\.\.\./);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#v2.0.0`, "--update"], ref: "v2.0.0", releaseRef: "v2.0.0" });
|
||||
});
|
||||
|
||||
test("launcher: update --tag vX.Y.Z rolls back through the install tag when advertised, the plain tag otherwise", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const env = fixtureStub(box, fx.snapshotText());
|
||||
for (const [tag, fetchRef] of [
|
||||
["v2.0.0", "install-v2.0.0"],
|
||||
["v3.1.2", "install-v3.1.2"],
|
||||
["v1.0.0", "v1.0.0"],
|
||||
["v0.9.0", "v0.9.0"],
|
||||
]) {
|
||||
const result = box.run(["update", "--tag", tag], env);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, new RegExp(`Updating Plan2Code to ${tag.replace(/\./g, "\\.")}\\.\\.\\.`));
|
||||
// A release rollback never forces: the installer's own version check decides.
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#${fetchRef}`, "--update"], ref: fetchRef, releaseRef: tag }, tag);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: update --tag install-vX.Y.Z is read as its release, with a notice; a malformed install-v is refused", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const env = fixtureStub(box, fx.snapshotText());
|
||||
const result = box.run(["update", "--tag", "install-v2.0.0"], env);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /install-v2\.0\.0 is how release v2\.0\.0 is fetched; updating by its release name, v2\.0\.0\./);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v2\.0\.0\.\.\./);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#install-v2.0.0`, "--update"], ref: "install-v2.0.0", releaseRef: "v2.0.0" });
|
||||
for (const bad of ["install-v2", "install-v2.0.0-rc1", "install-vlatest", "install-v"]) {
|
||||
const refused = box.run(["update", "--tag", bad], env);
|
||||
assert.equal(refused.status, 2, bad);
|
||||
assert.match(refused.stderr, /is not a release install tag: use --tag with the release, for example --tag v3\.0\.2/, bad);
|
||||
assert.equal(lastInstall(box).args, null, bad);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: --main and branch tags force a reinstall and carry no release ref", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
// An inherited release ref must not leak into a run that is not a release.
|
||||
const env = { ...fixtureStub(box, fx.snapshotText()), PLAN2CODE_RELEASE_REF: "v9.9.9" };
|
||||
assert.equal(box.run(["update", "--main"], env).status, 0);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", REPO, "--update", "--force"], ref: "main", releaseRef: null });
|
||||
for (const branch of ["feature/demo", "release", "install-feature"]) {
|
||||
assert.equal(box.run(["update", "--tag", branch], env).status, 0, branch);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#${branch}`, "--update", "--force"], ref: branch, releaseRef: null }, branch);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: uninstall runs the newest release's installer through its install tag", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["uninstall", "--yes"], fixtureStub(box, fx.snapshotText())).status, 0);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#install-v3.1.2`, "--uninstall", "--yes"], ref: "install-v3.1.2", releaseRef: "v3.1.2" });
|
||||
});
|
||||
|
||||
test("launcher: normalizeUpdateTagInput maps only an exact install tag, refuses a malformed one, leaves the rest", () => {
|
||||
const { normalizeUpdateTagInput } = require(LAUNCHER);
|
||||
assert.deepEqual(normalizeUpdateTagInput("install-v3.10.0"), { ref: "v3.10.0", notice: "install-v3.10.0 is how release v3.10.0 is fetched; updating by its release name, v3.10.0." });
|
||||
assert.match(normalizeUpdateTagInput("install-v3.1").error, /install-v3\.1 is not a release install tag/);
|
||||
for (const ref of ["v3.0.2", "main", "release", "feature/install-v1.0.0", "install-feature"]) assert.deepEqual(normalizeUpdateTagInput(ref), { ref }, ref);
|
||||
});
|
||||
|
||||
test("launcher: update --force reaches the installer", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
|
||||
@@ -0,0 +1,584 @@
|
||||
// Tests for scripts/publish-install-refs.mjs, the release workflow's slim
|
||||
// install ref publisher, against local fixtures: a bare `origin.git` and a
|
||||
// full source checkout beside it in the OS temp dir. Every push goes to that
|
||||
// bare repository, never anywhere else. Also checks the shape of the
|
||||
// release-app workflow's publish job. Run with:
|
||||
// node --test scripts/test-publish-install-refs.mjs
|
||||
//
|
||||
// skill-script-helpers.mjs is imported first on purpose: it scrubs the whole
|
||||
// test process's git config, so the fixtures and the spawned publisher agree
|
||||
// (the AGENTS.md failure-log rule). The scrubbed config names no user, which
|
||||
// also exercises the publisher's stand-in commit identity.
|
||||
|
||||
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 crypto from "node:crypto";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
|
||||
import { ROOT, scrubbedEnv } from "./skill-script-helpers.mjs";
|
||||
import {
|
||||
INSTALL_REF_MANIFEST,
|
||||
RUNTIME_PAYLOAD,
|
||||
runtimePayloadAllowlist,
|
||||
isAllowedPayloadPath,
|
||||
workflowSkillSources,
|
||||
assemblePayload,
|
||||
validatePayload,
|
||||
parseArgs,
|
||||
} from "./publish-install-refs.mjs";
|
||||
|
||||
const SCRIPT = path.join(ROOT, "scripts", "publish-install-refs.mjs");
|
||||
const WORKFLOW = path.join(ROOT, ".github", "workflows", "release-app.yml");
|
||||
const env = scrubbedEnv();
|
||||
|
||||
const git = (dir, args, options = {}) => execFileSync("git", ["-C", dir, ...args], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], env, ...options }).trim();
|
||||
const gitOk = (dir, args) => spawnSync("git", ["-C", dir, ...args], { env, encoding: "utf8" }).status === 0;
|
||||
const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
|
||||
|
||||
const INSTALL_JS = `// fixture installer
|
||||
const SHARED_SCRIPTS_ALWAYS = ['common.mjs'];
|
||||
const SOURCE_PROMPTS = [
|
||||
{
|
||||
source: 'plan2code.md',
|
||||
scripts: ['lessons.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-3-implement.md',
|
||||
scripts: ['specs.mjs', 'lessons.mjs'],
|
||||
additionalReferences: [{ source: 'shared-references/test-runs.md', target: 'test-runs.md' }]
|
||||
}
|
||||
];
|
||||
module.exports = { SOURCE_PROMPTS };
|
||||
`;
|
||||
|
||||
// Bytes git must carry through unchanged: CRLF, a NUL and high bytes.
|
||||
const BINARY = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0xfe, 0x0d, 0x0a]);
|
||||
|
||||
/** The runtime files of a release commit, `{ path: { content, mode? } }`. */
|
||||
function runtimeTree(version) {
|
||||
return {
|
||||
"install.js": { content: INSTALL_JS },
|
||||
"package.json": { content: json({ name: "plan2code", version }) },
|
||||
"version.json": { content: json({ name: "Plan2Code", version, releaseDate: "2026-12-01" }) },
|
||||
"src/launcher/plan2code.js": { content: `#!/usr/bin/env node\n// launcher ${version}\n`, mode: "100755" },
|
||||
"src/web-console/update-check.mjs": { content: `// update-check ${version}\n` },
|
||||
"src/web-console/console.mjs": { content: `// console ${version}\n` },
|
||||
"src/web-console/public/logo.png": { content: BINARY },
|
||||
"src/installer/timing.js": { content: "// timing\n" },
|
||||
"src/installer/skills-cli.js": { content: "// skills-cli\n" },
|
||||
"src/installer/canonical-skills.js": { content: "// canonical-skills\n" },
|
||||
"src/installer/console-stage.js": { content: "// console-stage\n" },
|
||||
"src/web-console-stub/console.mjs": { content: "// stub\n" },
|
||||
"src/statusline-claude/statusline.js": { content: "// statusline\n" },
|
||||
"src/launcher/models.json": { content: "{}\n" },
|
||||
"src/launcher/agents.json": { content: "{}\n" },
|
||||
"src/web-console/agent-lookup.mjs": { content: "// agent-lookup\n" },
|
||||
"src/launcher/plan2code.ico": { content: BINARY },
|
||||
"src/web-console/public/favicon.png": { content: BINARY },
|
||||
"src/plan2code.md": { content: "# Dashboard\n" },
|
||||
"src/plan2code-3-implement.md": { content: "# Implement\r\nCRLF kept as committed\r\n" },
|
||||
"src/skill-scripts/common.mjs": { content: "// common\n" },
|
||||
"src/skill-scripts/lessons.mjs": { content: "// lessons\n" },
|
||||
"src/skill-scripts/specs.mjs": { content: "// specs\n" },
|
||||
"src/shared-references/lessons.md": { content: "# Lessons\n" },
|
||||
"src/shared-references/test-runs.md": { content: "# Test runs\n" },
|
||||
};
|
||||
}
|
||||
|
||||
/** What a full checkout also carries and the payload must leave out. */
|
||||
const HEAVY = {
|
||||
"README.md": { content: "# readme\n" },
|
||||
"CHANGELOG.md": { content: "# changelog\n" },
|
||||
"docs/promo.md": { content: "# heavy docs\n" },
|
||||
"scripts/publish-install-refs.mjs": { content: "// the publisher itself\n" },
|
||||
"specs/idea/overview.md": { content: "# spec\n" },
|
||||
"skills/plan2code/SKILL.md": { content: "# built skill\n" },
|
||||
"plan2code-app/package.json": { content: "{}\n" },
|
||||
"plan2code-metrics/index.js": { content: "// metrics\n" },
|
||||
"plan2code-bot/index.js": { content: "// bot\n" },
|
||||
".github/workflows/release-app.yml": { content: "name: release-app\n" },
|
||||
"src/node_modules/junk/index.js": { content: "// vendored junk\n" },
|
||||
"src/web-console/fixtures/sample.json": { content: "{}\n" },
|
||||
};
|
||||
|
||||
const fullTree = (version) => ({ ...runtimeTree(version), ...HEAVY });
|
||||
|
||||
const data = (content) => {
|
||||
const buf = Buffer.isBuffer(content) ? content : Buffer.from(content);
|
||||
return Buffer.concat([Buffer.from(`data ${buf.length}\n`), buf, Buffer.from("\n")]);
|
||||
};
|
||||
|
||||
/**
|
||||
* A source checkout `work/` whose origin is a bare `origin.git`, both in one
|
||||
* temp folder. `release: "legacy"` gives origin a full-source release branch
|
||||
* (the pre-migration shape); `"none"` gives it none.
|
||||
*/
|
||||
function createSource({ release = "legacy" } = {}) {
|
||||
const root = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-publish-refs-"));
|
||||
const work = path.join(root, "work");
|
||||
const origin = path.join(root, "origin.git");
|
||||
execFileSync("git", ["init", "-q", "--bare", "-b", "main", origin], { env, stdio: "pipe" });
|
||||
execFileSync("git", ["init", "-q", "-b", "main", work], { env, stdio: "pipe" });
|
||||
git(work, ["remote", "add", "origin", origin]);
|
||||
let ts = 1700000000;
|
||||
|
||||
/** Commits `files` as the whole tree of main (optionally tagging it), pushes, and checks it out. */
|
||||
function commit(files, { tag = null, annotated = false, message = "commit" } = {}) {
|
||||
ts += 60;
|
||||
const parent = gitOk(work, ["rev-parse", "--verify", "--quiet", "refs/heads/main"]) ? git(work, ["rev-parse", "refs/heads/main"]) : null;
|
||||
const who = `Fixture <fixture@example.com> ${ts} +0000`;
|
||||
const parts = [Buffer.from(`commit refs/heads/main\nauthor ${who}\ncommitter ${who}\n`), data(message)];
|
||||
if (parent) parts.push(Buffer.from(`from ${parent}\n`));
|
||||
parts.push(Buffer.from("deleteall\n"));
|
||||
for (const [name, { content, mode = "100644" }] of Object.entries(files)) parts.push(Buffer.from(`M ${mode} inline ${name}\n`), data(content));
|
||||
if (tag && annotated) parts.push(Buffer.from(`tag ${tag}\nfrom refs/heads/main\ntagger ${who}\n`), data(`release ${tag}\n`));
|
||||
git(work, ["fast-import", "--quiet"], { input: Buffer.concat(parts) });
|
||||
if (tag && !annotated) git(work, ["update-ref", `refs/tags/${tag}`, "refs/heads/main"]);
|
||||
git(work, ["checkout", "-q", "-f", "main"]);
|
||||
git(work, ["push", "-q", "origin", "main", ...(tag ? [`refs/tags/${tag}`] : [])]);
|
||||
return git(work, ["rev-parse", "HEAD"]);
|
||||
}
|
||||
|
||||
let legacyTip = null;
|
||||
if (release === "legacy") {
|
||||
legacyTip = commit(fullTree("1.0.0"), { tag: "v1.0.0", message: "legacy release 1.0.0" });
|
||||
git(work, ["push", "-q", "origin", `${legacyTip}:refs/heads/release`]);
|
||||
}
|
||||
|
||||
return {
|
||||
root,
|
||||
work,
|
||||
origin,
|
||||
legacyTip,
|
||||
commit,
|
||||
/** Commits a full tree for `version`, tagged `vX.Y.Z`; `mutate(files)` edits it first. */
|
||||
release(version, { annotated = false, mutate } = {}) {
|
||||
const files = fullTree(version);
|
||||
if (mutate) mutate(files);
|
||||
return commit(files, { tag: `v${version}`, annotated, message: `release ${version}` });
|
||||
},
|
||||
remoteRef: (ref) => {
|
||||
const out = git(origin, ["for-each-ref", "--format=%(objectname)", ref]);
|
||||
return out || null;
|
||||
},
|
||||
cleanup: () => fs.rmSync(root, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs the publisher CLI from the checkout; `result` is its --json output when it wrote one. */
|
||||
function publish(fx, args) {
|
||||
const jsonPath = path.join(fx.root, `result-${crypto.randomBytes(3).toString("hex")}.json`);
|
||||
const r = spawnSync(process.execPath, [SCRIPT, "--repo", fx.work, "--json", jsonPath, ...args], { cwd: fx.work, env, encoding: "utf8" });
|
||||
const result = fs.existsSync(jsonPath) ? JSON.parse(fs.readFileSync(jsonPath, "utf8")) : null;
|
||||
return { status: r.status, stdout: r.stdout, stderr: r.stderr, result };
|
||||
}
|
||||
|
||||
/** `{ path: mode }` of every file in a commit's tree in origin. */
|
||||
function remoteTree(fx, commit) {
|
||||
const out = git(fx.origin, ["ls-tree", "-r", "--full-tree", commit]);
|
||||
const files = {};
|
||||
for (const line of out.split("\n").filter(Boolean)) {
|
||||
const [meta, name] = line.split("\t");
|
||||
files[name] = meta.split(" ")[0];
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const indexHash = (fx) => crypto.createHash("sha256").update(fs.readFileSync(path.join(fx.work, ".git", "index"))).digest("hex");
|
||||
|
||||
test("allowlist: one constant-driven structure of explicit files and prefixes", () => {
|
||||
const allow = runtimePayloadAllowlist();
|
||||
assert.equal(allow, RUNTIME_PAYLOAD);
|
||||
assert.deepEqual([...allow.files], ["install.js", "package.json", "version.json"]);
|
||||
assert.deepEqual([...allow.prefixes], ["src/"]);
|
||||
assert.ok(Object.isFrozen(allow) && Object.isFrozen(allow.files) && Object.isFrozen(allow.required));
|
||||
for (const ok of ["install.js", "src/launcher/plan2code.js", "src/web-console/public/activities/snake.js"]) assert.equal(isAllowedPayloadPath(ok), true, ok);
|
||||
for (const bad of ["README.md", "docs/a.md", "scripts/publish-install-refs.mjs", "specs/x.md", "skills/a/SKILL.md", "plan2code-app/x", "plan2code-metrics/x", "plan2code-bot/x", ".github/x.yml", ".git/HEAD", "src/node_modules/a.js", "src/x/fixtures/a.json", "src/", "src/../install.js", "src\\a.js", ""]) {
|
||||
assert.equal(isAllowedPayloadPath(bad), false, bad);
|
||||
}
|
||||
});
|
||||
|
||||
test("allowlist: every skill build input comes from install.js's SOURCE_PROMPTS", () => {
|
||||
assert.deepEqual(workflowSkillSources(INSTALL_JS), [
|
||||
"src/plan2code.md",
|
||||
"src/plan2code-3-implement.md",
|
||||
"src/skill-scripts/lessons.mjs",
|
||||
"src/skill-scripts/specs.mjs",
|
||||
"src/skill-scripts/common.mjs",
|
||||
"src/web-console",
|
||||
"src/shared-references/lessons.md",
|
||||
"src/shared-references/test-runs.md",
|
||||
]);
|
||||
assert.deepEqual(workflowSkillSources("// no prompts here\n"), []);
|
||||
// The real installer: every input it names exists in this checkout's src/.
|
||||
const real = workflowSkillSources(fs.readFileSync(path.join(ROOT, "install.js"), "utf8"));
|
||||
assert.ok(real.includes("src/plan2code-3-implement-review.md") && real.includes("src/skill-scripts/specs.mjs") && real.includes("src/web-console"));
|
||||
for (const rel of real) assert.ok(fs.existsSync(path.join(ROOT, ...rel.split("/"))), rel);
|
||||
});
|
||||
|
||||
test("arguments: unknown, missing and malformed arguments print the usage and exit 2", () => {
|
||||
assert.equal(parseArgs(["--tag", "v1.2.3", "--dry-run"]).options.dryRun, true);
|
||||
assert.match(parseArgs(["--tag", "1.2.3"]).error, /exact vX\.Y\.Z/);
|
||||
assert.match(parseArgs(["--tag", "v1.2"]).error, /exact vX\.Y\.Z/);
|
||||
assert.match(parseArgs(["--tag", "install-v1.2.3"]).error, /exact vX\.Y\.Z/);
|
||||
assert.match(parseArgs([]).error, /--tag is required/);
|
||||
assert.match(parseArgs(["--tag"]).error, /needs a value/);
|
||||
for (const args of [["--tag", "v1.2.3", "--force"], ["--tag", "v1.2.3-rc.1"], ["--repo", "."]]) {
|
||||
const r = spawnSync(process.execPath, [SCRIPT, ...args], { env, encoding: "utf8" });
|
||||
assert.equal(r.status, 2, args.join(" "));
|
||||
assert.match(r.stderr, /Usage: node scripts\/publish-install-refs\.mjs/);
|
||||
}
|
||||
});
|
||||
|
||||
test("first publication: parents the legacy release tip, pushes one slim commit to both refs", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
const tagCommit = fx.release("1.2.0");
|
||||
const statusBefore = git(fx.work, ["status", "--porcelain"]);
|
||||
const indexBefore = indexHash(fx);
|
||||
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
const res = r.result;
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.pushed, true);
|
||||
assert.equal(res.parent, fx.legacyTip, "the first migration parents the legacy full-source tip");
|
||||
assert.equal(res.parentKind, "release");
|
||||
assert.equal(res.sourceCommit, tagCommit);
|
||||
assert.deepEqual(res.refs, { tag: "refs/tags/install-v1.2.0", branch: "refs/heads/release" });
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), res.commit);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), res.commit);
|
||||
assert.equal(git(fx.origin, ["rev-parse", `${res.commit}^{tree}`]), res.tree);
|
||||
assert.equal(git(fx.origin, ["rev-parse", `${res.commit}^1`]), fx.legacyTip);
|
||||
assert.equal(gitOk(fx.origin, ["rev-parse", "--verify", "--quiet", `${res.commit}^2`]), false, "exactly one parent");
|
||||
assert.match(r.stdout, /Published [0-9a-f]{40}/);
|
||||
|
||||
const files = remoteTree(fx, res.commit);
|
||||
const expected = [...Object.keys(runtimeTree("1.2.0")), INSTALL_REF_MANIFEST].sort();
|
||||
assert.deepEqual(Object.keys(files).sort(), expected, "exactly the runtime allowlist plus the manifest");
|
||||
assert.equal(files["src/launcher/plan2code.js"], "100755", "the executable bit survives");
|
||||
assert.equal(files["install.js"], "100644");
|
||||
assert.equal(res.files, expected.length);
|
||||
assert.ok(res.excluded >= Object.keys(HEAVY).length);
|
||||
|
||||
const blob = (name) => execFileSync("git", ["-C", fx.origin, "cat-file", "blob", `${res.commit}:${name}`], { env });
|
||||
assert.deepEqual(blob("src/web-console/public/logo.png"), BINARY, "binary bytes are carried unchanged");
|
||||
assert.equal(blob("src/plan2code-3-implement.md").toString(), "# Implement\r\nCRLF kept as committed\r\n");
|
||||
assert.equal(res.bytes, expected.reduce((sum, name) => sum + blob(name).length, 0));
|
||||
|
||||
const manifest = JSON.parse(blob(INSTALL_REF_MANIFEST).toString());
|
||||
assert.deepEqual(Object.keys(manifest), ["kind", "version", "sourceTag", "sourceCommit", "files"]);
|
||||
assert.equal(manifest.kind, "install-ref");
|
||||
assert.equal(manifest.version, "1.2.0");
|
||||
assert.equal(manifest.sourceTag, "v1.2.0");
|
||||
assert.equal(manifest.sourceCommit, tagCommit);
|
||||
assert.equal(manifest.files[INSTALL_REF_MANIFEST], undefined, "the manifest never lists itself");
|
||||
assert.deepEqual(Object.keys(manifest.files).sort(), Object.keys(runtimeTree("1.2.0")).sort());
|
||||
for (const [name, hash] of Object.entries(manifest.files)) {
|
||||
assert.equal(hash, crypto.createHash("sha256").update(blob(name)).digest("hex"), name);
|
||||
}
|
||||
|
||||
assert.equal(git(fx.work, ["status", "--porcelain"]), statusBefore, "the working tree is untouched");
|
||||
assert.equal(indexHash(fx), indexBefore, "the normal index is untouched");
|
||||
assert.deepEqual(fs.readdirSync(path.join(fx.work, ".git")).filter((n) => n.startsWith("p2c-install-index")), [], "the temporary index is removed");
|
||||
assert.equal(git(fx.origin, ["log", "-1", "--format=%an <%ae>", res.commit]), "github-actions[bot] <41898099+github-actions[bot]@users.noreply.github.com>");
|
||||
});
|
||||
|
||||
test("subsequent publication: parents the previous synthetic commit and fast-forwards release", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
const first = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(first.status, 0, first.stderr);
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
|
||||
const tagCommit = fx.release("1.3.0");
|
||||
const second = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(second.status, 0, second.stderr);
|
||||
assert.equal(second.result.parent, first.result.commit, "the synthetic chain, never the full-source commit");
|
||||
assert.notEqual(second.result.parent, tagCommit);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), second.result.commit);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), first.result.commit, "the older install tag stays where it was");
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.3.0"), second.result.commit);
|
||||
assert.equal(gitOk(fx.origin, ["merge-base", "--is-ancestor", first.result.commit, second.result.commit]), true);
|
||||
});
|
||||
|
||||
test("the release tip must be in the checkout: an unfetched tip fails before anything is pushed", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
// Another runner moved origin's release branch to a commit this checkout never fetched.
|
||||
const elsewhere = path.join(fx.root, "elsewhere");
|
||||
execFileSync("git", ["clone", "-q", fx.origin, elsewhere], { env, stdio: "pipe" });
|
||||
git(elsewhere, ["-c", "user.name=x", "-c", "user.email=x@example.com", "commit", "-q", "--allow-empty", "-m", "moved"]);
|
||||
git(elsewhere, ["push", "-q", "origin", "HEAD:refs/heads/release"]);
|
||||
const moved = fx.remoteRef("refs/heads/release");
|
||||
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /fetch refs\/heads\/release first/);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), moved);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
});
|
||||
|
||||
test("tag collision: an existing install tag, remote or local, is never overwritten", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
const first = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(first.status, 0, first.stderr);
|
||||
|
||||
// A second run for the same, fully published release (the workflow has more than one trigger)
|
||||
// succeeds and pushes nothing, rather than failing red after a good release.
|
||||
const again = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(again.status, 0, again.stderr);
|
||||
assert.equal(again.result.alreadyPublished, true);
|
||||
assert.equal(again.result.pushed, false);
|
||||
assert.match(again.stdout, /v1\.2\.0 is already published/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), first.result.commit);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), first.result.commit);
|
||||
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
fx.release("1.3.0");
|
||||
git(fx.work, ["tag", "install-v1.3.0", "HEAD"]);
|
||||
const local = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(local.status, 1);
|
||||
assert.match(local.stderr, /already exists in this checkout/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.3.0"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), first.result.commit);
|
||||
});
|
||||
|
||||
test("missing release branch: refused without the allowance, parents the source tag commit with it", (t) => {
|
||||
const fx = createSource({ release: "none" });
|
||||
t.after(fx.cleanup);
|
||||
const tagCommit = fx.release("1.2.0");
|
||||
|
||||
const refused = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(refused.status, 1);
|
||||
assert.match(refused.stderr, /refs\/heads\/release does not exist on origin; pass --allow-missing-release-branch/);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), null);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
|
||||
const allowed = publish(fx, ["--tag", "v1.2.0", "--allow-missing-release-branch"]);
|
||||
assert.equal(allowed.status, 0, allowed.stderr);
|
||||
assert.equal(allowed.result.parent, tagCommit);
|
||||
assert.equal(allowed.result.parentKind, "source-tag");
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), allowed.result.commit);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), allowed.result.commit);
|
||||
});
|
||||
|
||||
test("payload contamination: validation lists every unexpected path and forbidden top-level entry", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
const tagCommit = fx.release("1.2.0");
|
||||
const out = path.join(fx.root, "payload");
|
||||
const { modes, excluded } = assemblePayload({ repo: fx.work, commit: tagCommit, output: out });
|
||||
assert.equal(modes["src/launcher/plan2code.js"], "100755");
|
||||
assert.equal(excluded, Object.keys(HEAVY).length);
|
||||
const clean = validatePayload(out);
|
||||
assert.equal(clean.ok, true, clean.report.join("\n"));
|
||||
assert.equal(clean.manifest, false);
|
||||
|
||||
for (const name of ["docs/promo.md", "scripts/publish-install-refs.mjs", "README.md", "src/node_modules/junk/index.js", "plan2code-bot/index.js"]) {
|
||||
fs.mkdirSync(path.dirname(path.join(out, name)), { recursive: true });
|
||||
fs.writeFileSync(path.join(out, name), "contamination\n");
|
||||
}
|
||||
const dirty = validatePayload(out);
|
||||
assert.equal(dirty.ok, false);
|
||||
assert.deepEqual(dirty.unexpected, ["README.md", "docs/promo.md", "plan2code-bot/index.js", "scripts/publish-install-refs.mjs", "src/node_modules/junk/index.js"]);
|
||||
assert.deepEqual(dirty.forbidden, ["docs", "scripts", "plan2code-bot"]);
|
||||
assert.ok(dirty.report.includes("+ docs/promo.md"));
|
||||
assert.ok(dirty.report.includes("+ docs/ (forbidden top-level entry)"));
|
||||
|
||||
// An --output folder that already holds anything is refused before assembly.
|
||||
const r = publish(fx, ["--tag", "v1.2.0", "--output", out, "--dry-run"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /is not empty/);
|
||||
});
|
||||
|
||||
test("missing required runtime files: the diff-like report names each one and nothing is pushed", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0", {
|
||||
mutate: (files) => {
|
||||
delete files["src/installer/console-stage.js"];
|
||||
delete files["src/plan2code-3-implement.md"];
|
||||
delete files["src/skill-scripts/specs.mjs"];
|
||||
delete files["src/shared-references/test-runs.md"];
|
||||
// The whole src/web-console folder, a reference SOURCE_PROMPTS names.
|
||||
delete files["src/web-console/console.mjs"];
|
||||
delete files["src/web-console/update-check.mjs"];
|
||||
delete files["src/web-console/public/logo.png"];
|
||||
delete files["src/web-console/agent-lookup.mjs"];
|
||||
delete files["src/web-console/public/favicon.png"];
|
||||
},
|
||||
});
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /runtime payload of v1\.2\.0 is not valid/);
|
||||
const reported = [
|
||||
"src/installer/console-stage.js",
|
||||
"src/plan2code-3-implement.md",
|
||||
"src/shared-references/test-runs.md",
|
||||
"src/skill-scripts/specs.mjs",
|
||||
"src/web-console",
|
||||
"src/web-console/agent-lookup.mjs",
|
||||
"src/web-console/console.mjs",
|
||||
"src/web-console/public/favicon.png",
|
||||
"src/web-console/update-check.mjs",
|
||||
];
|
||||
for (const name of reported) {
|
||||
assert.match(r.stderr, new RegExp(`^- ${name.replace(/\./g, "\\.")}$`, "m"), name);
|
||||
}
|
||||
assert.deepEqual(
|
||||
r.result.details.filter((l) => l.startsWith("- ")),
|
||||
reported.map((name) => `- ${name}`),
|
||||
);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), fx.legacyTip);
|
||||
});
|
||||
|
||||
test("version mismatch: version.json, package.json and the checkout's HEAD must all agree with the tag", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0", { mutate: (files) => (files["package.json"] = { content: json({ name: "plan2code", version: "1.2.1" }) }) });
|
||||
const pkg = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(pkg.status, 1);
|
||||
assert.match(pkg.stderr, /do not match the tag v1\.2\.0: package\.json says 1\.2\.1/);
|
||||
|
||||
fx.release("1.3.0", { mutate: (files) => (files["version.json"] = { content: json({ version: "1.2.9" }) }) });
|
||||
const ver = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(ver.status, 1);
|
||||
assert.match(ver.stderr, /version\.json says 1\.2\.9/);
|
||||
|
||||
fx.release("1.4.0");
|
||||
fx.commit(fullTree("1.4.0"), { message: "work after the tag" });
|
||||
const head = publish(fx, ["--tag", "v1.4.0"]);
|
||||
assert.equal(head.status, 1);
|
||||
assert.match(head.stderr, /the checkout's HEAD [0-9a-f]{40} is not the commit v1\.4\.0 names/);
|
||||
|
||||
const missing = publish(fx, ["--tag", "v9.9.9"]);
|
||||
assert.equal(missing.status, 1);
|
||||
assert.match(missing.stderr, /the tag v9\.9\.9 does not exist/);
|
||||
|
||||
for (const ref of ["refs/tags/install-v1.2.0", "refs/tags/install-v1.3.0", "refs/tags/install-v1.4.0"]) assert.equal(fx.remoteRef(ref), null, ref);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), fx.legacyTip);
|
||||
});
|
||||
|
||||
test("annotated and lightweight source tags both resolve to their commit", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
const light = fx.release("1.2.0");
|
||||
assert.equal(git(fx.work, ["cat-file", "-t", "refs/tags/v1.2.0"]), "commit");
|
||||
const a = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(a.status, 0, a.stderr);
|
||||
assert.equal(a.result.sourceCommit, light);
|
||||
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
const annotatedCommit = fx.release("1.3.0", { annotated: true });
|
||||
assert.equal(git(fx.work, ["cat-file", "-t", "refs/tags/v1.3.0"]), "tag");
|
||||
const b = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(b.status, 0, b.stderr);
|
||||
assert.equal(b.result.sourceCommit, annotatedCommit, "the annotated tag peels to its commit");
|
||||
const manifest = JSON.parse(execFileSync("git", ["-C", fx.origin, "cat-file", "blob", `${b.result.commit}:${INSTALL_REF_MANIFEST}`], { env, encoding: "utf8" }));
|
||||
assert.equal(manifest.sourceCommit, annotatedCommit);
|
||||
});
|
||||
|
||||
test("dry run: builds and checks the commit, pushes nothing, keeps --output", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
const out = path.join(fx.root, "kept-payload");
|
||||
const r = publish(fx, ["--tag", "v1.2.0", "--dry-run", "--output", out]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.result.dryRun, true);
|
||||
assert.equal(r.result.pushed, false);
|
||||
assert.match(r.stdout, /^Would publish [0-9a-f]{40}/);
|
||||
assert.equal(r.result.payload, out);
|
||||
assert.equal(fs.existsSync(path.join(out, INSTALL_REF_MANIFEST)), true);
|
||||
assert.equal(git(fx.work, ["cat-file", "-t", r.result.commit]), "commit", "the commit exists locally");
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), fx.legacyTip);
|
||||
});
|
||||
|
||||
/** The publish job's steps from release-app.yml, `[{ name, text }]` in order. */
|
||||
function publishSteps() {
|
||||
const yml = fs.readFileSync(WORKFLOW, "utf8").replace(/\r\n/g, "\n");
|
||||
const job = yml.slice(yml.indexOf("\n publish:\n"));
|
||||
assert.ok(job.length > 1, "release-app.yml has a publish job");
|
||||
const steps = job.slice(job.indexOf("\n steps:\n")).split("\n - ").slice(1);
|
||||
return { yml, steps: steps.map((text) => ({ name: (/^(?:name:\s*(.+)|uses:\s*(.+))/.exec(text) || [])[1] || text.split("\n")[0], text })) };
|
||||
}
|
||||
|
||||
test("release workflow: synthetic-ref publication is the publish job's last step, after the release is public", () => {
|
||||
const { yml, steps } = publishSteps();
|
||||
const names = steps.map((s) => s.name.trim());
|
||||
const attach = names.indexOf("Attach to the release, creating it last");
|
||||
const pub = names.indexOf("Publish the slim install refs");
|
||||
assert.ok(attach !== -1, "the step that creates and publishes the release is there");
|
||||
assert.ok(pub > attach, "publication comes after the release is public");
|
||||
assert.equal(pub, steps.length - 1, "publication is the last step");
|
||||
assert.match(steps[attach].text, /gh release edit "\$TAG" --draft=false/);
|
||||
const run = steps[pub].text;
|
||||
assert.match(steps[0].text, /persist-credentials:\s*false/, "the publish checkout does not persist the workflow token in .git/config");
|
||||
assert.match(run, /GIT_ASKPASS="\$RUNNER_TEMP\/p2c-git-askpass\.sh"/);
|
||||
assert.match(run, /GIT_TERMINAL_PROMPT=0/);
|
||||
assert.match(run, /GCM_INTERACTIVE=never/);
|
||||
assert.match(run, /credential\.username x-access-token/);
|
||||
assert.doesNotMatch(run, /extraheader|credential-helper output/, "no token or credential-helper output is written or echoed");
|
||||
assert.match(run, /node scripts\/publish-install-refs\.mjs --tag "\$TAG" --repo "\$GITHUB_WORKSPACE"/);
|
||||
assert.match(run, /git fetch --no-tags --unshallow origin/);
|
||||
assert.match(run, /refs\/heads\/release:refs\/remotes\/origin\/release/);
|
||||
assert.match(run, /refs\/tags\/\$\{TAG\}:refs\/tags\/\$\{TAG\}/);
|
||||
assert.doesNotMatch(run, /continue-on-error|\|\| true/, "a failed publication fails the workflow");
|
||||
assert.equal(names.includes("Move the release branch to this tag"), false, "the old branch move is gone");
|
||||
const code = yml
|
||||
.split("\n")
|
||||
.filter((line) => !/^\s*#/.test(line))
|
||||
.join("\n");
|
||||
assert.doesNotMatch(code, /--force|git push[^\n]*\s-f\b|git push[^\n]*\s\+/, "no force push anywhere in the workflow");
|
||||
assert.doesNotMatch(code, /git push/, "the publisher does the only push");
|
||||
});
|
||||
|
||||
test("an older or equal release never moves the release branch back, unless --allow-older says so", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.3.0");
|
||||
const newer = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(newer.status, 0, newer.stderr);
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
|
||||
// A hotfix tagged after it, from an older line: refused, nothing pushed.
|
||||
fx.release("1.2.9");
|
||||
const older = publish(fx, ["--tag", "v1.2.9"]);
|
||||
assert.equal(older.status, 1);
|
||||
assert.match(older.stderr, /already installs 1\.3\.0; refusing to move it to 1\.2\.9/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.9"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), newer.result.commit);
|
||||
|
||||
// The deliberate override still works.
|
||||
const forced = publish(fx, ["--tag", "v1.2.9", "--allow-older"]);
|
||||
assert.equal(forced.status, 0, forced.stderr);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), forced.result.commit);
|
||||
});
|
||||
|
||||
test("a package.json script that makes npm do a full dev install of a git package refuses the publication", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0", {
|
||||
mutate: (files) => {
|
||||
files["package.json"] = { content: json({ name: "plan2code", version: "1.2.0", scripts: { prepare: "node build.js", test: "node --test" } }) };
|
||||
},
|
||||
});
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /package\.json has prepare/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
});
|
||||
@@ -14,12 +14,18 @@ const skillNames = () => fs.readdirSync(SKILLS).filter((name) => !name.startsWit
|
||||
|
||||
/* ================================================================ install */
|
||||
|
||||
test("npm test runs every scripts/test-*.mjs file, and names none that is missing", () => {
|
||||
const command = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts.test;
|
||||
const listed = [...command.matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]).sort();
|
||||
test("npm test and npm run test:games together run every scripts/test-*.mjs file once, games only in test:games", () => {
|
||||
const scripts = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts;
|
||||
const files = (command) => [...String(command || "").matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]);
|
||||
// The Activities games are an add-on: their tests run only on request (npm run test:games), never in npm test.
|
||||
const isGame = (f) => /^test-web-console-(activities[\w-]*|page-activities)\.mjs$/.test(f);
|
||||
const main = files(scripts.test);
|
||||
const games = files(scripts["test:games"]);
|
||||
assert.deepEqual(main.filter(isGame), [], "npm test runs no game tests");
|
||||
assert.deepEqual(games.filter((f) => !isGame(f)), [], "test:games runs only game tests");
|
||||
// test-fast.mjs runs the fast lane (npm run test:fast); it is a runner, not a test file.
|
||||
const onDisk = fs.readdirSync(path.join(ROOT, "scripts")).filter((f) => /^test-[\w-]+\.mjs$/.test(f) && f !== "test-fast.mjs").sort();
|
||||
assert.deepEqual(listed, onDisk);
|
||||
assert.deepEqual([...main, ...games].sort(), onDisk, "every test file is named once, in one of the two");
|
||||
});
|
||||
|
||||
test("every skill with scripts ships common.mjs and version.json; the dashboard ships only Learning's", () => {
|
||||
|
||||
@@ -97,6 +97,19 @@ test("wait's existing outcomes are pinned: submit, images, waiting, cancel, carr
|
||||
|
||||
/* --------------------------------------------- quick question: the channel */
|
||||
|
||||
// `chat` checks the server's /health with a 1.5 s limit, so on a machine loaded by the rest of the
|
||||
// suite a server this test just started, and knows is running, can be reported gone (20). Where the
|
||||
// server must be up, ask again a few times before judging the answer; a real 20 stays 20 when the
|
||||
// server has been stopped (those checks call cli directly).
|
||||
async function chatWhileUp(s) {
|
||||
let r = cli(["chat", "--session", s.sid]);
|
||||
for (let i = 0; i < 4 && r.status === 20; i++) {
|
||||
await sleep(500);
|
||||
r = cli(["chat", "--session", s.sid]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
test("a chat message and a card send can both be pending, in either order, and wait hands both over at once", async () => {
|
||||
const s = openSession();
|
||||
@@ -160,11 +173,11 @@ test("wait returns within 100 ms of a chat message landing", async () => {
|
||||
test("the chat command answers at once: 0 with entries, 10 with none, 20 when the server is gone, and never takes a card send", async () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
assert.equal(cli(["chat", "--session", s.sid]).status, 10, "a reset alone is nothing to hand over");
|
||||
assert.equal((await chatWhileUp(s)).status, 10, "a reset alone is nothing to hand over");
|
||||
assert.equal((await s.send("/submit", EXPORT_A)).status, 200);
|
||||
assert.equal((await ask(s, "Mid-build question")).status, 200);
|
||||
assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 1, "an uncollected question shows on the heartbeat");
|
||||
const got = cli(["chat", "--session", s.sid]);
|
||||
const got = await chatWhileUp(s);
|
||||
assert.equal(got.status, 0);
|
||||
assert.equal(got.json.chat.length, 1);
|
||||
assert.match(got.json.reply, /Quick question \(\d+\): Mid-build question/);
|
||||
@@ -172,7 +185,7 @@ test("the chat command answers at once: 0 with entries, 10 with none, 20 when th
|
||||
assert.equal(onDisk.consumedAt, undefined, "the card send is still waiting for wait");
|
||||
assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 0);
|
||||
|
||||
const none = cli(["chat", "--session", s.sid]);
|
||||
const none = await chatWhileUp(s);
|
||||
assert.equal(none.status, 10);
|
||||
assert.deepEqual(none.json, {});
|
||||
|
||||
@@ -197,10 +210,10 @@ test("a torn trailing inbox line is skipped, then collected once it is whole", a
|
||||
const line = JSON.stringify({ kind: "message", conversation: 1, text: "torn in two", seq, at: new Date().toISOString() });
|
||||
fs.appendFileSync(file, line.slice(0, 20));
|
||||
assert.equal(readChat(s.session).some((e) => e.seq === seq), false, "a half-written line is not parsed");
|
||||
assert.equal(cli(["chat", "--session", s.sid]).status, 10);
|
||||
assert.equal((await chatWhileUp(s)).status, 10);
|
||||
fs.appendFileSync(file, line.slice(20) + "\n");
|
||||
assert.ok(readChat(s.session).some((e) => e.seq === seq));
|
||||
const got = cli(["chat", "--session", s.sid]);
|
||||
const got = await chatWhileUp(s);
|
||||
assert.equal(got.status, 0);
|
||||
assert.match(got.json.reply, /Quick question \(\d+\): torn in two/);
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user