// 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)); }