// Tests for `node install.js --update` and the install record (~/.plan2code/install.json). // Run with: node --test scripts/test-install-update.mjs // // install.js reads the home directory once, at load, so HOME and USERPROFILE point at a temp // folder before it is required. update() takes its install steps as an argument: the tests // pass stand-ins that record their calls, so nothing reaches the skills CLI, npm or the network. import test from "node:test"; import assert from "node:assert/strict"; import crypto from "node:crypto"; import fs from "node:fs"; import http from "node:http"; import os from "node:os"; import path from "node:path"; import { 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"; import { parseLsRemoteSnapshot, installRefForRelease, chooseReleaseRef, latestTag } from "../src/web-console/update-check.mjs"; const require = createRequire(import.meta.url); const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const INSTALL = path.join(ROOT, "install.js"); const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version; const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-update-")); process.env.HOME = HOME; process.env.USERPROFILE = HOME; const installer = require(INSTALL); const { readTimingEvents } = require(path.join(ROOT, "src", "installer", "timing.js")); test.after(() => fs.rmSync(HOME, { recursive: true, force: true })); const RECORD = path.join(HOME, ".plan2code", "install.json"); function writeRecord(pieces) { fs.mkdirSync(path.dirname(RECORD), { recursive: true }); fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", pieces })); } function clearRecord() { fs.rmSync(RECORD, { force: true }); } /** Stand-in install steps: each logs its piece and options, then returns `codes[piece]` (default 0) or throws `throws[piece]`. */ function fakeSteps({ codes = {}, throws = {}, launcherWithSkills = true } = {}) { const calls = []; const steps = {}; for (const piece of installer.INSTALL_PIECES) { steps[piece] = async (options) => { calls.push({ piece, options }); if (throws[piece]) throw new Error(throws[piece]); let code = codes[piece] ?? 0; if (piece === "skills") { // As the real install(): the skills first, then the command, and 1 if either failed. options.outcome.skills = code === 0; options.outcome.launcher = code === 0 && launcherWithSkills; if (code === 0 && !launcherWithSkills) code = 1; } return code; }; } return { steps, calls, ran: () => calls.map((c) => c.piece) }; } /** Run update() with console output captured: `{ code, out }`. `options` go to update() as they are. */ async function runUpdate(steps, options = {}) { const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); try { // The canonical store and the console have their own tests below; here they count as in place unless a test says otherwise. const code = await installer.update({ steps, cleanShims: () => {}, skillsCurrent: () => true, consoleCurrent: () => true, progress: () => {}, ...options }); return { code, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") }; } finally { console.log = log; } } test("install record: recordInstalled and forgetInstalled round trip a sorted set", () => { clearRecord(); assert.equal(installer.INSTALL_RECORD, RECORD); assert.equal(installer.readInstallRecord(), null); installer.recordInstalled("metrics"); installer.recordInstalled("skills"); installer.recordInstalled("skills"); installer.recordInstalled("not-a-piece"); assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["metrics", "skills"] }); installer.forgetInstalled("metrics"); assert.deepEqual(installer.readInstallRecord().pieces, ["skills"]); installer.forgetInstalled("skills"); assert.deepEqual(installer.readInstallRecord().pieces, []); // No temp file is left beside the record. assert.deepEqual(fs.readdirSync(path.dirname(RECORD)), ["install.json"]); }); test("install record: a missing or unparsable record reads as null, and forgetting needs none", () => { clearRecord(); installer.forgetInstalled("skills"); assert.equal(fs.existsSync(RECORD), false); fs.writeFileSync(RECORD, "{ not json"); assert.equal(installer.readInstallRecord(), null); fs.writeFileSync(RECORD, JSON.stringify({ pieces: "skills" })); assert.equal(installer.readInstallRecord(), null); }); test("update: with no record it says so and updates the skills and the plan2code command", async () => { clearRecord(); const fake = fakeSteps(); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.match(out, /No install record found; updating the skills and the plan2code command\./); assert.doesNotMatch(out, /installed before v/); // install() covers the command with the skills, so the launcher step does not run again. assert.deepEqual(fake.ran(), ["skills"]); assert.match(out, /Skills: updated/); assert.match(out, /plan2code command: updated/); }); test("update: a partial record runs only the listed pieces, in order, unattended", async () => { writeRecord(["bot", "statusline"]); const fake = fakeSteps(); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.deepEqual(fake.ran(), ["statusline", "bot"]); for (const call of fake.calls) assert.equal(call.options.unattended, true, call.piece); assert.doesNotMatch(out, /No install record/); assert.doesNotMatch(out, /Skills:/); }); test("update: a failing piece exits 1 naming it, and the others still run", async () => { writeRecord(["skills", "launcher", "statusline", "metrics", "bot"]); const fake = fakeSteps({ codes: { statusline: 1 }, throws: { metrics: "npm exploded" } }); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 1, out); assert.deepEqual(fake.ran(), ["skills", "statusline", "metrics", "bot"]); assert.match(out, /Status line: failed: /); assert.match(out, /Metrics: failed: npm exploded/); assert.match(out, /Bot: updated/); assert.match(out, /Update failed for: Status line, Metrics/); }); test("update: when the skills install leaves the command out, the launcher step runs on its own", async () => { writeRecord(["skills", "launcher"]); const fake = fakeSteps({ launcherWithSkills: false }); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.deepEqual(fake.ran(), ["skills", "launcher"]); // install() returned 1 for the command alone: the skills still read as updated. assert.match(out, /Skills: updated/); assert.match(out, /plan2code command: updated/); }); test("update: a command that fails on the retry is the only piece named", async () => { writeRecord(["skills", "launcher"]); const fake = fakeSteps({ launcherWithSkills: false, codes: { launcher: 1 } }); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 1, out); assert.match(out, /Skills: updated/); assert.match(out, /Update failed for: plan2code command\b/); // A failed update says how to go back (the record's old version here). assert.match(out, /To go back to a release, run: plan2code update --tag v1\.0\.0/); }); test("update: piece timing events carry piece, result, duration, ref, version and mode", async (t) => { clearRecord(); writeRecord(["statusline", "metrics", "bot"]); const timingFile = path.join(HOME, "piece-timing.jsonl"); process.env.PLAN2CODE_BENCH_JSON = timingFile; process.env.PLAN2CODE_BENCH_MODE = "warm-npx"; process.env.PLAN2CODE_INSTALL_REF = "install-v9.9.9"; t.after(() => { delete process.env.PLAN2CODE_BENCH_JSON; delete process.env.PLAN2CODE_BENCH_MODE; delete process.env.PLAN2CODE_INSTALL_REF; }); const fake = fakeSteps(); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); const pieces = readTimingEvents(timingFile).filter((event) => event.event === "piece-installed"); assert.deepEqual(pieces.map((event) => event.piece), ["statusline", "metrics", "bot"]); for (const event of pieces) { assert.equal(event.result, "updated"); assert.equal(typeof event.durationMs, "number"); assert.ok(event.durationMs >= 0); assert.equal(event.ref, "install-v9.9.9"); assert.equal(event.version, VERSION); assert.equal(event.mode, "warm-npx"); } }); test("update: piece timing stays inactive without PLAN2CODE_BENCH_JSON", async () => { clearRecord(); writeRecord(["statusline"]); const timingFile = path.join(HOME, "inactive-timing.jsonl"); const fake = fakeSteps(); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.equal(fs.existsSync(timingFile), false); assert.deepEqual(readTimingEvents(timingFile), []); }); test("update: prints the version change, one line per piece by name, the release notes link and the restart hint", async () => { writeRecord(["skills", "launcher", "app", "statusline"]); const fake = fakeSteps(); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.match(out, new RegExp(`^Updating 1\\.0\\.0 -> ${VERSION.replace(/\./g, "\\.")}$`, "m")); // The compact summary: human names only, never the internal piece names. assert.match(out, /Skills: updated/); assert.match(out, /plan2code command: updated/); assert.match(out, /Desktop app: updated/); assert.match(out, /Status line: updated/); assert.doesNotMatch(out, /[✓✗] (skills|launcher|statusline|app|metrics|bot): /); assert.equal((out.match(/Update summary/g) || []).length, 1, "one summary"); assert.match(out, new RegExp(`^What's new: https://github\\.com/jparkerweb/plan2code/releases/tag/v${VERSION.replace(/\./g, "\\.")}$`, "m")); assert.match(out, /Close any open Plan2Code console or app and start `plan2code` again\./); assert.doesNotMatch(out, /Happy coding|PARAMETERS|To go back to a release/); }); const LAUNCHER_VERSION = path.join(HOME, ".plan2code", "bin", "version.json"); /** The installed plan2code command's version.json, as installLauncher() writes it. */ function writeLauncherVersion(version) { fs.mkdirSync(path.dirname(LAUNCHER_VERSION), { recursive: true }); fs.writeFileSync(LAUNCHER_VERSION, JSON.stringify({ name: "Plan2Code", version })); } test("update: already on the new version it says so and stops, until --force", async () => { fs.mkdirSync(path.dirname(RECORD), { recursive: true }); fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] })); writeLauncherVersion(VERSION); const idle = fakeSteps(); const stopped = await runUpdate(idle.steps); assert.equal(stopped.code, 0, stopped.out); assert.match(stopped.out, new RegExp(`Already on ${VERSION.replace(/\./g, "\\.")}`)); assert.match(stopped.out, /plan2code update --force/); assert.deepEqual(idle.ran(), [], "nothing was reinstalled"); assert.doesNotMatch(stopped.out, /Update summary/); const forced = fakeSteps(); const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); let code; try { code = await installer.update({ steps: forced.steps, cleanShims: () => {}, force: true }); } finally { console.log = log; } const out = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, ""); assert.equal(code, 0, out); assert.deepEqual(forced.ran(), ["skills"]); assert.match(out, new RegExp(`Updating ${VERSION.replace(/\./g, "\\.")} -> ${VERSION.replace(/\./g, "\\.")}`)); }); test("update: a record on the new version over an older plan2code command installs again, without --force", async () => { // An update stopped after the skills step: the record says new, the command is still old. fs.mkdirSync(path.dirname(RECORD), { recursive: true }); fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] })); for (const launcher of ["1.0.0", null]) { if (launcher) writeLauncherVersion(launcher); else fs.rmSync(LAUNCHER_VERSION, { force: true }); const fake = fakeSteps(); const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.doesNotMatch(out, /Already on/); assert.match(out, new RegExp(`The plan2code command is still on ${launcher ? "1\\.0\\.0" : "an unknown version"}`)); assert.deepEqual(fake.ran(), ["skills"]); assert.match(out, /plan2code command: updated/); } // A record without the command does not look at its version.json. fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["statusline"] })); const idle = fakeSteps(); assert.match((await runUpdate(idle.steps)).out, /Already on/); assert.deepEqual(idle.ran(), []); }); test("update: the record keeps the old version until every piece is in, so a stopped update retries", async () => { writeRecord(["skills", "launcher", "app"]); const seen = []; const fake = fakeSteps(); // As the real steps: each records its piece as it finishes. for (const piece of ["skills", "app"]) { const step = fake.steps[piece]; fake.steps[piece] = async (options) => { const code = await step(options); installer.recordInstalled(piece); seen.push(installer.readInstallRecord().version); return code; }; } const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.deepEqual(seen, ["1.0.0", "1.0.0"], "mid-update writes keep the old version"); assert.equal(installer.readInstallRecord().version, VERSION, "stamped once the update finished"); assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]); // Outside an update, a record write stamps the version being installed again. installer.recordInstalled("statusline"); assert.equal(installer.readInstallRecord().version, VERSION); }); test("update: a step's own output stays out of the summary, except its warnings and its failures", async () => { writeRecord(["skills", "statusline", "bot"]); const fake = fakeSteps(); fake.steps.skills = async (options) => { console.log("Installing skills"); console.log(" ✓ Built 23 skills from src/"); console.log(" ! heads up from the skills step"); options.outcome.skills = true; options.outcome.launcher = true; return 0; }; fake.steps.statusline = async () => { console.log(" ✗ could not write settings.json"); return 1; }; const { code, out } = await runUpdate(fake.steps); assert.equal(code, 1, out); assert.doesNotMatch(out, /Installing skills|Built 23 skills/); assert.match(out, /! heads up from the skills step/); assert.match(out, /✗ could not write settings\.json/); }); test("update: a failed update puts the old version back in the record, so a retry runs instead of stopping at Already on", async () => { writeRecord(["skills", "launcher"]); const fake = fakeSteps({ codes: { skills: 1 } }); // As the real launcher step: it works, and recording it stamps the version being installed. fake.steps.launcher = async () => { installer.recordInstalled("launcher"); return 0; }; const failed = await runUpdate(fake.steps); assert.equal(failed.code, 1, failed.out); assert.match(failed.out, /To try again, run: plan2code update/); assert.match(failed.out, /To go back to a release, run: plan2code update --tag v1\.0\.0/); assert.equal(installer.readInstallRecord().version, "1.0.0", "the record stays on the old version"); assert.deepEqual(installer.readInstallRecord().pieces, ["launcher", "skills"], "and keeps every piece"); const retry = await runUpdate(fakeSteps().steps); assert.equal(retry.code, 0, retry.out); assert.doesNotMatch(retry.out, /Already on/); assert.match(retry.out, /Plan2Code is up to date/); }); test("update: an app kept because the release has no app file yet leaves the old version on the record, so the next update fetches it", async () => { writeRecord(["skills", "launcher", "app"]); const fake = fakeSteps(); fake.steps.app = async (options) => { installer.recordInstalled("app"); options.outcome.appMissing = true; return 0; }; const kept = await runUpdate(fake.steps); assert.equal(kept.code, 0, kept.out); assert.match(kept.out, /Desktop app: kept \(no new desktop app file yet\)/); assert.equal(installer.readInstallRecord().version, "1.0.0", "the record stays on the old version"); const next = await runUpdate(fakeSteps().steps); assert.equal(next.code, 0, next.out); assert.doesNotMatch(next.out, /Already on/); assert.match(next.out, /Desktop app: updated/); }); test("update: a failed desktop app install inside the skills step is shown, and does not fail the update", async () => { writeRecord(["skills", "launcher"]); const fake = fakeSteps(); fake.steps.skills = async (options) => { console.log(" Built 23 skills from src/"); console.log(" ✗ The desktop app was not installed: the download did not match its checksum."); options.outcome.skills = true; options.outcome.launcher = true; options.outcome.app = false; return 0; }; const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.match(out, /✗ The desktop app was not installed: the download did not match its checksum\./); assert.doesNotMatch(out, /Built 23 skills/); }); test("update: the app's size is in its summary line when the skills step brought it in", async () => { writeRecord(["skills", "launcher"]); const fake = fakeSteps(); fake.steps.skills = async (options) => { options.outcome.skills = true; options.outcome.launcher = true; options.outcome.app = true; options.outcome.appSize = 3 * 1024 * 1024; return 0; }; const { code, out } = await runUpdate(fake.steps); assert.equal(code, 0, out); assert.match(out, /Desktop app: updated \(3\.0 MB\)/); }); test("uninstall: printKeptData names the folder and lists each entry with its size", async () => { const data = path.join(HOME, ".plan2code"); fs.mkdirSync(path.join(data, "handoffs"), { recursive: true }); fs.writeFileSync(path.join(data, "handoffs", "h.md"), "y".repeat(3000)); const { out } = await captured(() => installer.printKeptData()); assert.match(out, /Your data in .* was kept/); assert.match(out, /Handoffs: 3 KB/); fs.rmSync(path.join(data, "handoffs"), { recursive: true, force: true }); }); test("install.js --update: an option other than --force is refused", () => { const timingFile = path.join(HOME, "invalid-update-timing.jsonl"); fs.rmSync(timingFile, { force: true }); const refused = spawnSync(process.execPath, [INSTALL, "--update", "--nope"], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME, PLAN2CODE_BENCH_JSON: timingFile } }); assert.equal(refused.status, 1); assert.match(refused.stderr, /Unknown option\(s\): --update --nope/); assert.equal(readTimingEvents(timingFile).at(-1)?.event, "installer-end"); }); const SHA_RELEASE = "a".repeat(40); const SHA_OLD_RELEASE = "b".repeat(40); const SHA_MAIN = "c".repeat(40); const TAGS = [`${SHA_OLD_RELEASE}\trefs/tags/v3.0.2`, `${SHA_RELEASE}\trefs/tags/v3.1.2`, `${"d".repeat(40)}\trefs/tags/nightly`].join("\n"); /** releaseRedirectRef() as redirectToRelease() calls it: one snapshot for both newest and classification. */ function redirectFor(commit, text, env = {}) { const snapshot = parseLsRemoteSnapshot(text); return installer.releaseRedirectRef({ commit, snapshot, newest: chooseReleaseRef(snapshot), env }); } /** Snapshot text with main's head moved to `sha`: main's tip is unreleased work past every tag. */ const withMainAt = (text, sha) => text.replace(/^[0-9a-f]{40}(\trefs\/heads\/main)$/m, `${sha}$1`); test("ref snapshot: tags, install tags, peeled lines and heads parse from real fixture output", (t) => { const fx = createInstallRefFixture(); t.after(fx.cleanup); const snapshot = parseLsRemoteSnapshot(fx.lsRemote()); assert.deepEqual(snapshot.tags, { "1.0.0": fx.refs.tags["v1.0.0"], "2.0.0": fx.refs.tags["v2.0.0"], "3.1.2": fx.refs.tags["v3.1.2"] }); assert.deepEqual(snapshot.installTags, { "2.0.0": fx.refs.tags["install-v2.0.0"], "3.1.2": fx.refs.tags["install-v3.1.2"] }); assert.deepEqual(snapshot.peeledTags, { "v3.1.2": fx.refs.peeled["v3.1.2"] }, "only the annotated tag has a peeled line"); assert.deepEqual(snapshot.heads, fx.refs.heads); assert.equal(snapshot.tags.nightly, undefined, "a non-release tag is skipped"); }); test("ref snapshot: malformed lines and non-release names are skipped; shas are lowercased; CRLF reads the same", () => { const upper = "ABCDEF0123".repeat(4); const text = [ `${upper}\trefs/tags/v1.2.3`, `${"1".repeat(40)}\trefs/tags/install-v1.2.3^{}`, `${"2".repeat(39)}\trefs/tags/v9.9.9`, `${"3".repeat(40)}\trefs/tags/v9.9.9-rc1`, `${"4".repeat(40)}\trefs/tags/install-v9.9`, `${"5".repeat(40)}\trefs/tags/release-4`, `${"6".repeat(40)}\trefs/pull/1/head`, "not a line at all", `${"7".repeat(40)}\trefs/heads/feature/x`, ].join("\r\n"); assert.deepEqual(parseLsRemoteSnapshot(text), { tags: { "1.2.3": upper.toLowerCase() }, peeledTags: { "install-v1.2.3": "1".repeat(40) }, installTags: {}, heads: { "feature/x": "7".repeat(40) }, }); for (const nothing of [null, undefined, 42, ""]) { assert.deepEqual(parseLsRemoteSnapshot(nothing), { tags: {}, peeledTags: {}, installTags: {}, heads: {} }, String(nothing)); } }); test("ref mapping: a release maps to its install tag when advertised, its plain tag otherwise, or null", (t) => { const fx = createInstallRefFixture(); t.after(fx.cleanup); const snapshot = parseLsRemoteSnapshot(fx.snapshotText()); assert.deepEqual(installRefForRelease("v3.1.2", snapshot), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true }); assert.deepEqual(installRefForRelease("2.0.0", snapshot), { releaseRef: "v2.0.0", fetchRef: "install-v2.0.0", synthetic: true }, "X.Y.Z reads as vX.Y.Z"); assert.deepEqual(installRefForRelease("v1.0.0", snapshot), { releaseRef: "v1.0.0", fetchRef: "v1.0.0", synthetic: false }, "rollback with no synthetic ref"); assert.equal(installRefForRelease("v9.9.9", snapshot), null); for (const bad of ["main", "install-v3.1.2", "v3.1", "", null]) assert.equal(installRefForRelease(bad, snapshot), null, String(bad)); assert.equal(installRefForRelease("v3.1.2", null), null); // A peeled line is evidence of its tag, by name: the commit it names does not matter. const peeledOnly = parseLsRemoteSnapshot(`${"e".repeat(40)}\trefs/tags/v4.0.0^{}\n${"f".repeat(40)}\trefs/tags/install-v4.0.0^{}`); assert.deepEqual(installRefForRelease("v4.0.0", peeledOnly), { releaseRef: "v4.0.0", fetchRef: "install-v4.0.0", synthetic: true }); }); test("ref choice: always the numerically newest plain release, fetched through its install tag when it has one, else as itself; else null", (t) => { const fx = createInstallRefFixture(); t.after(fx.cleanup); assert.deepEqual(chooseReleaseRef(parseLsRemoteSnapshot(fx.snapshotText())), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true, version: "3.1.2" }); // A newer release published before its install tag (or whose ref publication failed): still the // newest release, fetched as its full plain tag. Never an older paired one, which would roll a // user back and disagree with the banner and the app, which both report the newest plain tag. const lagging = createInstallRefFixture({ releases: [{ version: "3.9.0", installTag: true }, { version: "3.10.0", installTag: true }, { version: "3.11.0" }] }); t.after(lagging.cleanup); assert.deepEqual(chooseReleaseRef(parseLsRemoteSnapshot(lagging.snapshotText())), { releaseRef: "v3.11.0", fetchRef: "v3.11.0", synthetic: false, version: "3.11.0" }); // Missing synthetic refs: the newest plain tag, fetched as itself. const legacy = createInstallRefFixture({ releases: [{ version: "2.0.0" }, { version: "2.10.0", annotated: true }, { version: "2.9.0" }] }); t.after(legacy.cleanup); assert.deepEqual(chooseReleaseRef(parseLsRemoteSnapshot(legacy.snapshotText())), { releaseRef: "v2.10.0", fetchRef: "v2.10.0", synthetic: false, version: "2.10.0" }); // An install tag with no plain release is not a release. assert.equal(chooseReleaseRef(parseLsRemoteSnapshot(`${"a".repeat(40)}\trefs/tags/install-v5.0.0\n${"b".repeat(40)}\trefs/heads/main`)), null); assert.equal(chooseReleaseRef(parseLsRemoteSnapshot("")), null); assert.equal(chooseReleaseRef(null), null); }); test("release redirect: unreleased work goes to the newest release; a release commit, a chosen ref or an unknown stays", () => { const plain = { releaseRef: "v3.1.2", fetchRef: "v3.1.2", synthetic: false }; assert.deepEqual(redirectFor(SHA_MAIN, TAGS), plain); assert.equal(redirectFor(SHA_RELEASE, TAGS), null, "the newest release stays"); assert.equal(redirectFor(SHA_OLD_RELEASE, TAGS), null, "an older launcher's update --tag v3.0.2 stays on v3.0.2"); assert.deepEqual(redirectFor("d".repeat(40), TAGS), plain, "a tag that is not vX.Y.Z is not a release"); assert.equal(redirectFor(SHA_MAIN, TAGS, { PLAN2CODE_INSTALL_REF: "main" }), null, "the current launcher's --main stays on main"); assert.equal(redirectFor(null, TAGS), null); assert.equal(redirectFor(SHA_MAIN, `${"9".repeat(40)}\trefs/heads/main`), null, "no release to go to"); assert.equal(installer.releaseRedirectRef({ commit: SHA_MAIN, snapshot: null, newest: plain, env: {} }), null); // An annotated tag's commit is on its peeled line. assert.equal(redirectFor(SHA_MAIN, `${"e".repeat(40)}\trefs/tags/v3.1.2\n${SHA_MAIN}\trefs/tags/v3.1.2^{}`), null); }); test("release redirect: every intentional ref in a real snapshot stays; only main's unreleased tip moves, onto the install tag", (t) => { const fx = createInstallRefFixture({ featureBranches: ["feature/demo"], releaseVersion: "2.0.0" }); t.after(fx.cleanup); const unreleased = "c".repeat(40); const text = withMainAt(fx.lsRemote(), unreleased); for (const [why, commit] of [ ["lightweight plain tag (rollback, no synthetic ref)", fx.refs.tags["v1.0.0"]], ["lightweight plain tag with a synthetic ref", fx.refs.tags["v2.0.0"]], ["annotated tag object", fx.refs.tags["v3.1.2"]], ["annotated tag's peeled commit", fx.refs.peeled["v3.1.2"]], ["synthetic install tag", fx.refs.tags["install-v3.1.2"]], ["stale moving release branch", fx.refs.heads.release], ["feature branch", fx.refs.heads["feature/demo"]], ]) { assert.equal(redirectFor(commit, text), null, why); assert.equal(redirectFor(commit.toUpperCase(), text), null, `${why}, uppercase`); } assert.deepEqual(redirectFor(unreleased, text), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true }, "never the heavier plain tag"); assert.deepEqual(redirectFor("f".repeat(40), text), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true }, "an unknown commit"); // A branch sitting on main's unreleased tip cannot be told from main: it does not keep the run. const sameTip = text.replace(/^[0-9a-f]{40}(\trefs\/heads\/feature\/demo)$/m, `${unreleased}$1`); assert.deepEqual(redirectFor(unreleased, sameTip), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true }); }); test("release redirect: with no synthetic refs advertised, unreleased work goes to the newest plain tag", (t) => { const fx = createInstallRefFixture({ releases: [{ version: "1.0.0" }, { version: "2.0.0", annotated: true }] }); t.after(fx.cleanup); const text = withMainAt(fx.snapshotText(), "c".repeat(40)); assert.deepEqual(redirectFor("c".repeat(40), text), { releaseRef: "v2.0.0", fetchRef: "v2.0.0", synthetic: false }); assert.equal(redirectFor(fx.refs.heads.release, fx.snapshotText()), null, "a legacy full-source release tip stays"); }); test("fetchedCommit: reads the exact lock key for unscoped and scoped npx layouts, null otherwise", (t) => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-fetched-")); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); const sha = "AbCdEf0123".repeat(4); const lockFor = (key, resolved = `git+ssh://git@github.com/jparkerweb/plan2code.git#${sha}`) => JSON.stringify({ packages: { [key]: { resolved } } }); const layout = (name, pkgPath, lock) => { const modules = path.join(dir, name, "node_modules"); const pkg = path.join(modules, ...pkgPath); fs.mkdirSync(pkg, { recursive: true }); if (lock !== undefined) fs.writeFileSync(path.join(modules, ".package-lock.json"), lock); return pkg; }; assert.equal(installer.fetchedCommit(layout("plain", ["plan2code"], lockFor("node_modules/plan2code"))), sha.toLowerCase()); assert.equal(installer.fetchedCommit(layout("scoped", ["@acme", "plan2code"], lockFor("node_modules/@acme/plan2code"))), sha.toLowerCase()); // The scoped package never reads the unscoped key, nor the other way round. assert.equal(installer.fetchedCommit(layout("wrong-key", ["@acme", "plan2code"], lockFor("node_modules/plan2code"))), null); assert.equal(installer.fetchedCommit(layout("wrong-key-2", ["plan2code"], lockFor("node_modules/@acme/plan2code"))), null); assert.equal(installer.fetchedCommit(layout("no-lock", ["plan2code"])), null); assert.equal(installer.fetchedCommit(layout("bad-json", ["plan2code"], "{not json")), null); assert.equal(installer.fetchedCommit(layout("no-sha", ["plan2code"], lockFor("node_modules/plan2code", "git+ssh://git@github.com/jparkerweb/plan2code.git"))), null); assert.equal(installer.fetchedCommit(path.join(dir, "checkout", "plan2code")), null, "a checkout is not under node_modules"); assert.equal(installer.fetchedCommit(path.join(dir, "@acme", "plan2code")), null, "a scope folder outside node_modules"); }); /** * install.js laid out as npx leaves a git package: node_modules/plan2code (or * node_modules/@acme/plan2code with `scoped`) beside npm's hidden lock file, and `lsRemote` * as the `git ls-remote` answer the run reads. */ function npxCopy(commit, { lsRemote = TAGS + "\n", scoped = false } = {}) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-npx-copy-")); const name = scoped ? "@acme/plan2code" : "plan2code"; const pkg = path.join(dir, "node_modules", ...name.split("/")); fs.mkdirSync(path.join(pkg, "src", "web-console"), { recursive: true }); fs.mkdirSync(path.join(pkg, "src", "installer"), { recursive: true }); fs.copyFileSync(INSTALL, path.join(pkg, "install.js")); fs.copyFileSync(path.join(ROOT, "version.json"), path.join(pkg, "version.json")); fs.copyFileSync(path.join(ROOT, "src", "web-console", "update-check.mjs"), path.join(pkg, "src", "web-console", "update-check.mjs")); for (const file of ["timing.js", "skills-cli.js", "canonical-skills.js", "console-stage.js"]) { fs.copyFileSync(path.join(ROOT, "src", "installer", file), path.join(pkg, "src", "installer", file)); } if (commit) { const resolved = `git+ssh://git@github.com/jparkerweb/plan2code.git#${commit}`; fs.writeFileSync(path.join(dir, "node_modules", ".package-lock.json"), JSON.stringify({ packages: { [`node_modules/${name}`]: { version: VERSION, resolved } } })); } fs.writeFileSync(path.join(dir, "ls-remote.txt"), lsRemote); // A stand-in npx that records its arguments and the refs the redirect handed it. const bin = path.join(dir, "bin"); fs.mkdirSync(bin); const recorder = path.join(bin, "record.js"); fs.writeFileSync( recorder, 'require("fs").writeFileSync(require("path").join(__dirname, "npx.json"), JSON.stringify({ args: process.argv.slice(2), ref: process.env.PLAN2CODE_INSTALL_REF, releaseRef: process.env.PLAN2CODE_RELEASE_REF }));\nprocess.exitCode = 5;\n' ); if (process.platform === "win32") fs.writeFileSync(path.join(bin, "npx.cmd"), `@"${process.execPath}" "${recorder}" %*\r\n`); else { fs.writeFileSync(path.join(bin, "npx"), `#!/bin/sh\nexec "${process.execPath}" "${recorder}" "$@"\n`); fs.chmodSync(path.join(bin, "npx"), 0o755); } const run = (args, env = {}) => { const runEnv = { ...process.env, HOME, USERPROFILE: HOME, PLAN2CODE_LS_REMOTE_FILE: path.join(dir, "ls-remote.txt"), ...env }; delete runEnv.PLAN2CODE_INSTALL_REF; delete runEnv.PLAN2CODE_RELEASE_REF; for (const key of Object.keys(runEnv)) if (key.toUpperCase() === "PATH") delete runEnv[key]; runEnv.PATH = bin + path.delimiter + (process.env.PATH || process.env.Path || ""); Object.assign(runEnv, env); return spawnSync(process.execPath, [path.join(pkg, "install.js"), ...args], { encoding: "utf8", env: runEnv, input: "" }); }; const npx = () => (fs.existsSync(path.join(bin, "npx.json")) ? JSON.parse(fs.readFileSync(path.join(bin, "npx.json"), "utf8")) : null); return { dir, run, npx, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) }; } test("release redirect: an old launcher's update from main runs the newest release's installer with the same options", (t) => { const copy = npxCopy(SHA_MAIN); t.after(copy.cleanup); const timingFile = path.join(copy.dir, "redirect-timing.jsonl"); const result = copy.run(["--update", "--force"], { PLAN2CODE_BENCH_JSON: timingFile, PLAN2CODE_BENCH_MODE: "cold-npx" }); assert.equal(result.status, 5, "the release installer's exit code is passed through\n" + result.stderr); assert.match(result.stdout, /switching to the newest release, v3\.1\.2/); const { args, ref, releaseRef } = copy.npx(); assert.deepEqual(args, ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#v3.1.2", "--update", "--force"]); assert.equal(ref, "v3.1.2", "the handed-off run is marked, so it never redirects again"); assert.equal(releaseRef, "v3.1.2"); const events = readTimingEvents(timingFile); assert.deepEqual(events.map((event) => event.event), ["bootstrap-start", "redirect-start", "redirect-end", "installer-end"]); assert.equal(events[2].redirected, true); assert.equal(events[2].mode, "cold-npx"); assert.equal(typeof events[2].durationMs, "number"); assert.equal(typeof events[3].durationMs, "number"); }); test("release redirect: unreleased work fetches the newest release's install tag, unscoped or scoped, and names the release", (t) => { const fx = createInstallRefFixture(); t.after(fx.cleanup); const unreleased = "c".repeat(40); for (const scoped of [false, true]) { const copy = npxCopy(unreleased, { lsRemote: withMainAt(fx.snapshotText(), unreleased), scoped }); t.after(copy.cleanup); const result = copy.run(["--uninstall", "--yes"]); assert.equal(result.status, 5, result.stdout + result.stderr); assert.match(result.stdout, /switching to the newest release, v3\.1\.2\./); assert.deepEqual( copy.npx(), { args: ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#install-v3.1.2", "--uninstall", "--yes"], ref: "install-v3.1.2", releaseRef: "v3.1.2", }, scoped ? "scoped" : "unscoped" ); } }); test("release redirect: a fetched slim release tip, an install tag or a rollback tag is never redirected", (t) => { const fx = createInstallRefFixture(); t.after(fx.cleanup); const text = withMainAt(fx.snapshotText(), "c".repeat(40)); for (const [commit, scoped] of [ [fx.refs.heads.release, false], [fx.refs.tags["install-v2.0.0"], true], [fx.refs.tags["v1.0.0"], true], ]) { const copy = npxCopy(commit, { lsRemote: text, scoped }); t.after(copy.cleanup); const result = copy.run(["--update", "--nope"]); assert.equal(result.status, 1, result.stdout + result.stderr); assert.match(result.stderr, /Unknown option\(s\)/); assert.equal(copy.npx(), null); } }); test("release redirect: a release copy, a run the launcher chose, or a copy with no lock file is not redirected", (t) => { for (const [commit, env] of [[SHA_RELEASE, {}], [SHA_MAIN, { PLAN2CODE_INSTALL_REF: "main" }], [null, {}]]) { const copy = npxCopy(commit); t.after(copy.cleanup); // An unknown option shows the run carried on here: the usage error, and no npx. const result = copy.run(["--update", "--nope"], env); assert.equal(result.status, 1, result.stdout + result.stderr); assert.match(result.stderr, /Unknown option\(s\)/); assert.equal(copy.npx(), null); } }); test("release redirect: an interactive install from main is handed to the newest release too", (t) => { const copy = npxCopy(SHA_MAIN); t.after(copy.cleanup); assert.equal(copy.run([]).status, 5); assert.deepEqual(copy.npx().args.slice(-1), ["git+https://github.com/jparkerweb/plan2code.git#v3.1.2"]); }); test("update: the real status line step keeps a custom statusLine without asking", async () => { const claudeDir = path.join(HOME, ".claude"); const settingsFile = path.join(claudeDir, "settings.json"); fs.mkdirSync(claudeDir, { recursive: true }); const settings = JSON.stringify({ statusLine: { type: "command", command: "my-own-status-line" } }, null, 2); fs.writeFileSync(settingsFile, settings); clearRecord(); // stdin is not a TTY here: a prompt would hang the test until it times out. const log = console.log; console.log = () => {}; let code; try { code = await installer.UPDATE_STEPS.statusline({ quiet: true, unattended: true }); } finally { console.log = log; } assert.equal(code, 0); assert.equal(fs.readFileSync(settingsFile, "utf8"), settings); assert.ok(fs.existsSync(path.join(claudeDir, "plan2code-statusline.js"))); assert.deepEqual(installer.readInstallRecord().pieces, ["statusline"]); }); test("update: every step is an install function, never an uninstall", () => { assert.deepEqual(Object.keys(installer.UPDATE_STEPS), installer.INSTALL_PIECES); for (const [piece, fn] of Object.entries(installer.UPDATE_STEPS)) { assert.match(fn.name, /^install/, piece); } }); test("install.js: --update and --uninstall are in the usage line, and an unknown option still exits 1", () => { const result = spawnSync(process.execPath, [INSTALL, "--bogus"], { encoding: "utf8" }); assert.equal(result.status, 1); assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update [--force] | --uninstall [--yes] [--purge]]"), result.stderr); }); // --------------------------------------------------------------------------------------------- // The desktop app: downloaded from a release, checked against its checksum list, placed in // ~/.plan2code/app/. A stand-in release server stands in for GitHub; PLAN2CODE_RELEASE_BASE // points the installer at it, and nothing here reaches the network. // --------------------------------------------------------------------------------------------- const ASSET = installer.appAssetName(VERSION); const SUMS = `plan2code-app-${VERSION}-SHA256SUMS.txt`; const APP_DIR = path.dirname(installer.APP_DEST); const sha = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex"); /** A release server for `files` (`{ path: Buffer | string }`); `hits` lists every path asked for. */ async function releaseServer(files) { const hits = []; const server = http.createServer((req, res) => { const name = decodeURIComponent(req.url.slice(1)); hits.push(name); if (name in files) { // As GitHub does, the size is sent, so the download can show it. res.writeHead(200, { "Content-Length": Buffer.byteLength(files[name]) }); res.end(files[name]); } else { res.writeHead(404); res.end("not found"); } }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); process.env.PLAN2CODE_RELEASE_BASE = `http://127.0.0.1:${server.address().port}/release`; return { hits, close: () => { delete process.env.PLAN2CODE_RELEASE_BASE; server.close(); }, }; } /** A release serving `bytes` as this system's app, listed under `listedHash` (default: its real hash). */ function goodRelease(bytes, listedHash = sha(bytes)) { return { [`release/${ASSET}`]: bytes, [`release/${SUMS}`]: `${listedHash} ${ASSET}\n${"0".repeat(64)} plan2code-app-other\n`, }; } /** Run `fn` with console output captured; resolves `{ result, out }`. */ async function captured(fn) { const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); try { const result = await fn(); return { result, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") }; } finally { console.log = log; } } function freshApp() { fs.rmSync(APP_DIR, { recursive: true, force: true }); clearRecord(); } test("app: the release file is named by system and cpu, and an unbuilt system has none", () => { assert.equal(installer.appAssetName("3.0.0", "win32", "x64"), "plan2code-app-3.0.0-windows-x64.exe"); assert.equal(installer.appAssetName("3.0.0", "darwin", "arm64"), "plan2code-app-3.0.0-macos-arm64"); assert.equal(installer.appAssetName("3.0.0", "darwin", "x64"), "plan2code-app-3.0.0-macos-x64"); assert.equal(installer.appAssetName("3.0.0", "linux", "x64"), "plan2code-app-3.0.0-linux-x64"); assert.equal(installer.appAssetName("3.0.0", "freebsd", "x64"), null); assert.equal(installer.appAssetName("3.0.0", "linux", "ia32"), null); }); test("app: checksumFor reads text and binary mode lines and wants the exact name", () => { const hex = "ab".repeat(32); const list = `${hex} plan2code-app-1-linux-x64\n${"cd".repeat(32)} *plan2code-app-1-macos-arm64\r\nnot a checksum line\n`; assert.equal(installer.checksumFor(list, "plan2code-app-1-linux-x64"), hex); assert.equal(installer.checksumFor(list, "plan2code-app-1-macos-arm64"), "cd".repeat(32)); assert.equal(installer.checksumFor(list, "plan2code-app-1-linux"), null); assert.equal(installer.checksumFor("", "x"), null); }); test("app installed: the file is downloaded, verified, placed and recorded", { skip: !ASSET }, async () => { freshApp(); writeRecord(["skills", "launcher"]); const bytes = Buffer.from("pretend this is an executable"); const server = await releaseServer(goodRelease(bytes)); try { const outcome = {}; const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome })); assert.equal(result, 0, out); assert.equal(outcome.app, true); assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes); assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]); assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)], "no temp or .old file is left"); assert.match(out, /Downloading the desktop app \(1 KB\)\.\.\./, "piped: the size, on one plain line"); assert.match(out, /not code-signed/); assert.ok(out.includes(`Installed: ${installer.APP_DEST}`), out); assert.ok(out.includes(installer.APP_GUIDE_URL), out); assert.deepEqual(server.hits, [`release/${SUMS}`, `release/${ASSET}`]); } finally { server.close(); } }); test("app checksum mismatch: the file is rejected, nothing is placed and the old app stays", { skip: !ASSET }, async () => { freshApp(); fs.mkdirSync(APP_DIR, { recursive: true }); fs.writeFileSync(installer.APP_DEST, "the app that was already here"); writeRecord(["skills", "launcher", "app"]); const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64))); try { const outcome = {}; const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome })); assert.equal(result, 1); assert.equal(outcome.app, false); assert.match(out, /does not match its checksum/); // Said plainly: the rest is installed and --classic is today's flow. assert.match(out, /skills and the plan2code command are installed/); assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the app that was already here"); assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]); } finally { server.close(); } }); test("app: a release without the file, or without a checksum entry, fails plainly and places nothing", { skip: !ASSET }, async () => { for (const files of [{}, { [`release/${SUMS}`]: `${"2".repeat(64)} some-other-file\n` }]) { freshApp(); writeRecord(["skills", "launcher"]); const server = await releaseServer(files); try { const outcome = {}; const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome })); assert.equal(result, 1, out); assert.equal(outcome.app, false); assert.match(out, /The desktop app was not installed: /); assert.equal(fs.existsSync(installer.APP_DEST), false); assert.deepEqual(installer.readInstallRecord().pieces, ["skills", "launcher"], "a failed install leaves the record as it was"); } finally { server.close(); } } }); test("app: a server that is not there fails plainly", { skip: !ASSET }, async () => { freshApp(); writeRecord(["skills", "launcher"]); process.env.PLAN2CODE_RELEASE_BASE = "http://127.0.0.1:1/release"; try { const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true })); assert.equal(result, 1); assert.match(out, /could not download it/); } finally { delete process.env.PLAN2CODE_RELEASE_BASE; } }); test("app update: plan2code update replaces an older app and reports it", { skip: !ASSET }, async () => { freshApp(); fs.mkdirSync(APP_DIR, { recursive: true }); fs.writeFileSync(installer.APP_DEST, "an older app"); writeRecord(["app"]); const bytes = Buffer.from("the newer app"); const server = await releaseServer(goodRelease(bytes)); try { // The real app step, in the real update loop; the record lists only the app. const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} })); assert.equal(result, 0, out); assert.match(out, /Desktop app: updated/); assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes); assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]); } finally { server.close(); } }); test("app update: a checksum mismatch fails the update naming the app, nothing else", { skip: !ASSET }, async () => { freshApp(); writeRecord(["app"]); const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64))); try { const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} })); assert.equal(result, 1); assert.match(out, /Update failed for: Desktop app/); } finally { server.close(); } }); test("app update: a release with no app file yet keeps the installed app and does not fail the update", { skip: !ASSET }, async () => { freshApp(); fs.mkdirSync(APP_DIR, { recursive: true }); fs.writeFileSync(installer.APP_DEST, "the installed app"); writeRecord(["app"]); // main moves to a new version before the release's files are attached: every file is a 404. const server = await releaseServer({}); try { const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} })); assert.equal(result, 0, out); assert.match(out, /Desktop app: kept/); assert.doesNotMatch(out, /Update failed/); assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the installed app"); } finally { server.close(); } }); test("app: interactively, a release with no app file is a plain failure, and a placement error is not called a download error", { skip: !ASSET }, async () => { freshApp(); writeRecord(["skills", "launcher"]); let server = await releaseServer({}); try { const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true })); assert.equal(result, 1); assert.match(out, /has no desktop app file for/); } finally { server.close(); } // The download is fine but the folder cannot be made: a file sits where the app folder goes. fs.mkdirSync(path.dirname(APP_DIR), { recursive: true }); fs.writeFileSync(APP_DIR, "in the way"); server = await releaseServer(goodRelease(Buffer.from("a good file"))); try { const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true })); assert.equal(result, 1); assert.match(out, /the file was verified but could not be put in/); assert.doesNotMatch(out, /could not download/); } finally { server.close(); fs.rmSync(APP_DIR, { force: true }); } }); test("app offered: a system with no build is never asked about, never downloaded for and says nothing red", { skip: !ASSET }, async () => { freshApp(); writeRecord(["skills", "launcher"]); const server = await releaseServer(goodRelease(Buffer.from("never fetched"))); const arch = Object.getOwnPropertyDescriptor(process, "arch"); Object.defineProperty(process, "arch", { value: "ia32", configurable: true }); try { for (const unattended of [true, false]) { const { out } = await captured(() => installer.offerDesktopApp({ unattended, outcome: {} })); assert.doesNotMatch(out, /was not installed/); } assert.deepEqual(server.hits, []); assert.equal(fs.existsSync(installer.APP_DEST), false); } finally { Object.defineProperty(process, "arch", arch); server.close(); } }); test("app offered: unattended with no app file in the release yet is a dim note, not a failure", { skip: !ASSET }, async () => { freshApp(); writeRecord(["skills", "launcher"]); const server = await releaseServer({}); try { const outcome = {}; const { out } = await captured(() => installer.offerDesktopApp({ unattended: true, outcome })); assert.match(out, /No desktop app update/); assert.doesNotMatch(out, /was not installed/); assert.equal(outcome.app, false); assert.equal(fs.existsSync(installer.APP_DEST), false); } finally { server.close(); } }); test("app skipped: an unattended offer downloads nothing when the app is recorded or was declined", { skip: !ASSET }, async () => { const server = await releaseServer(goodRelease(Buffer.from("never fetched"))); try { // Recorded: the update loop owns it. Declined: the person said no once. for (const record of [{ pieces: ["skills", "app"] }, { pieces: ["skills"], skipped: ["app"] }]) { freshApp(); fs.mkdirSync(path.dirname(RECORD), { recursive: true }); fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", ...record })); await captured(() => installer.offerDesktopApp({ unattended: true, outcome: {} })); assert.equal(fs.existsSync(installer.APP_DEST), false, JSON.stringify(record)); } assert.deepEqual(server.hits, []); } finally { server.close(); } }); test("app offered: unattended with nothing recorded about it means yes, and installing clears an old no", { skip: !ASSET }, async () => { freshApp(); writeRecord(["skills", "launcher"]); const bytes = Buffer.from("first time app"); const server = await releaseServer(goodRelease(bytes)); try { const outcome = {}; await captured(() => installer.offerDesktopApp({ unattended: true, outcome })); assert.equal(outcome.app, true); assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes); } finally { server.close(); } // A recorded decline is dropped once the piece is installed, and the key leaves the file when empty. fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", pieces: ["skills"], skipped: ["app"] })); installer.recordInstalled("app"); assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["app", "skills"] }); }); test("app declined: the no is remembered next to the pieces, and needs a record to be kept", () => { clearRecord(); installer.recordSkipped("app"); assert.equal(installer.readInstallRecord(), null, "no record is invented for a decline"); writeRecord(["skills"]); installer.recordSkipped("app"); assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["skills"], skipped: ["app"] }); installer.recordInstalled("launcher"); assert.deepEqual(installer.readInstallRecord().skipped, ["app"], "other writes keep the decline"); }); test("shared console install: the new version is placed, old versions go, and every other entry is left byte-identical", () => { const SHARED = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs"); if (!fs.existsSync(SHARED)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" }); const home = installer.consoleHomeDir(); assert.equal(home, path.join(HOME, ".plan2code", "console"), "the default home is under the temp HOME"); fs.rmSync(home, { recursive: true, force: true }); const put = (rel, body) => { const p = path.join(home, ...rel.split("/")); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, body); return p; }; put("2.9.9/console.mjs", "old"); put("2.9.9/public/core.js", "old"); put("10.0.0/console.mjs", "an older or newer version folder goes too"); put(`${VERSION}/stale.txt`, "a leftover inside the folder being replaced"); const kept = { "sessions/20261108-101010-aaaaaa/state.json": '{"a":1}', "sessions/20261108-101010-aaaaaa/shots/x.png": "png", "looks.json": '{"theme":"dark"}', "workspaces.json": "{}", "subagents.json": "[]", "runtime/x.json": "{}", "notes.txt": "not ours", "3.0/keep.txt": "not a version folder", }; for (const [rel, body] of Object.entries(kept)) put(rel, body); const lines = []; const log = console.log; console.log = (...a) => lines.push(a.join(" ")); let ok; try { ok = installer.installSharedConsole({ quiet: false }); } finally { console.log = log; } assert.equal(ok, true); assert.equal(fs.existsSync(path.join(home, "2.9.9")), false, "an old version folder is gone"); assert.equal(fs.existsSync(path.join(home, "10.0.0")), false, "every other version folder is gone"); assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the new version is present"); assert.equal(fs.readFileSync(path.join(home, VERSION, "version.txt"), "utf8").trim(), VERSION); assert.equal(fs.existsSync(path.join(home, VERSION, "stale.txt")), false, "the folder is replaced, not merged"); assert.equal(fs.readFileSync(path.join(home, "console-dir"), "utf8").trim(), path.join(home, VERSION)); for (const [rel, body] of Object.entries(kept)) { assert.equal(fs.readFileSync(path.join(home, ...rel.split("/")), "utf8"), body, rel + " is untouched"); } assert.ok(lines.some((line) => line.includes("Removed old console 2.9.9")), lines.join("\n")); // A second run changes nothing it should not. assert.equal(installer.installSharedConsole({ quiet: true }), true); assert.equal(fs.readFileSync(path.join(home, "looks.json"), "utf8"), kept["looks.json"]); assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs"))); }); test("shared console install: sweep false keeps old versions until sweepOldConsoles runs", () => { const SHARED = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs"); if (!fs.existsSync(SHARED)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" }); const home = installer.consoleHomeDir(); fs.rmSync(home, { recursive: true, force: true }); fs.mkdirSync(path.join(home, "2.9.9"), { recursive: true }); fs.writeFileSync(path.join(home, "2.9.9", "console.mjs"), "old"); fs.writeFileSync(path.join(home, "2.9.9", "version.txt"), "2.9.9\n"); assert.equal(installer.installSharedConsole({ quiet: true, sweep: false }), true); assert.ok(fs.existsSync(path.join(home, "2.9.9", "console.mjs")), "a failed skills add leaves the old version for the old stubs"); assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the new version is placed"); installer.sweepOldConsoles({ quiet: true }); assert.equal(fs.existsSync(path.join(home, "2.9.9")), false, "swept once skills add worked"); assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the current version stays"); }); test("shared console install: a missing build fails plainly and removes nothing", () => { const home = installer.consoleHomeDir(); fs.mkdirSync(home, { recursive: true }); fs.writeFileSync(path.join(home, "looks.json"), "{}"); const errors = []; const error = console.error; console.error = (...a) => errors.push(a.join(" ")); try { // An empty folder stands in for a build that did not happen; the real build is never touched. const empty = fs.mkdtempSync(path.join(HOME, "no-build-")); assert.equal(installer.installSharedConsole({ quiet: true, source: empty }), false); } finally { console.error = error; } assert.ok(errors.join("\n").includes("Could not install the shared console")); assert.ok(fs.existsSync(path.join(home, "looks.json")), "what was there stays"); }); test("the skills CLI is pinned to exact versions per Node line, and every doc line that runs it names one of them", () => { const { SKILLS_CLI_PINS } = require(path.join(ROOT, "src", "installer", "skills-cli.js")); for (const pin of [SKILLS_CLI_PINS.legacy, SKILLS_CLI_PINS.current, SKILLS_CLI_PINS.nodeFloor]) assert.match(pin, /^\d+\.\d+\.\d+$/); const pins = [SKILLS_CLI_PINS.legacy, SKILLS_CLI_PINS.current]; assert.ok(pins.includes(installer.SKILLS_CLI_VERSION), "install.js runs one of the pins"); for (const file of [INSTALL, path.join(ROOT, "src", "installer", "skills-cli.js")]) { const source = fs.readFileSync(file, "utf8"); assert.ok(!/npx (--yes )?skills( |')/.test(source), `no unpinned \`npx skills\` in ${path.basename(file)}`); assert.ok(!/skills@latest/.test(source), `no floating skills@latest in ${path.basename(file)}`); } for (const doc of ["README.md", ".agents-docs/AGENTS-development-commands.md"]) { const text = fs.readFileSync(path.join(ROOT, doc), "utf8"); assert.ok(!/npx (--yes )?skills (add|list|remove|--version)/.test(text), `${doc} has an unpinned \`npx skills\` command`); for (const m of text.matchAll(/npx (?:--yes )?skills@(\d+\.\d+\.\d+)/g)) { assert.ok(pins.includes(m[1]), `${doc} names skills@${m[1]}, not a pin in skills-cli.js`); } } }); /** Run uninstall() with console output captured and the answers to its y/N questions scripted. */ async function runUninstall(options, answers = []) { const lines = []; const asked = []; const calls = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); try { const code = await installer.uninstall({ ask: async (prompt) => { asked.push(prompt.replace(/\x1b\[[0-9;]*m/g, "")); return answers.shift() ?? false; }, remove: () => (calls.push("remove"), 0), purgeIt: () => (calls.push("purge"), 0), purgeWebview: () => (calls.push("webview"), 0), running: () => false, ...options, }); return { code, asked, calls, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") }; } finally { console.log = log; } } test("uninstall: a no at the confirmation removes nothing", async () => { const r = await runUninstall({}, [false]); assert.equal(r.code, 0); assert.deepEqual(r.calls, []); assert.equal(r.asked.length, 1); assert.match(r.out, /CANCELED/); }); test("uninstall: a yes removes everything, then asks about the data and keeps it on a no", async () => { const r = await runUninstall({}, [true, false]); assert.equal(r.code, 0); assert.deepEqual(r.calls, ["remove"]); assert.equal(r.asked.length, 2); assert.match(r.asked[1], /Also delete your Plan2Code data/); assert.match(r.out, /data in .* was kept/); }); test("uninstall: a yes to the data question purges it", async () => { const r = await runUninstall({}, [true, true]); assert.deepEqual(r.calls, ["remove", "purge", "webview"]); }); test("uninstall: --yes skips both questions and keeps the data", async () => { const r = await runUninstall({ yes: true }); assert.deepEqual(r.asked, []); assert.deepEqual(r.calls, ["remove"]); }); test("uninstall: --yes --purge deletes the data without a question", async () => { const r = await runUninstall({ yes: true, purge: true }); assert.deepEqual(r.asked, []); assert.deepEqual(r.calls, ["remove", "purge", "webview"]); }); test("uninstall: --purge alone still confirms the uninstall but never asks about the data", async () => { const r = await runUninstall({ purge: true }, [true]); assert.equal(r.asked.length, 1); assert.deepEqual(r.calls, ["remove", "purge", "webview"]); }); test("uninstall: a failing removal or purge makes the exit code non-zero", async () => { assert.equal((await runUninstall({ yes: true, remove: () => 1 })).code, 1); assert.equal((await runUninstall({ yes: true, purge: true, purgeIt: () => 1 })).code, 1); }); test("purgeData: deletes the folder and everything in it, and copes with it missing", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-purge-")); fs.mkdirSync(path.join(dir, "notepads")); fs.writeFileSync(path.join(dir, "notepads", "a.json"), "{}"); const log = console.log; console.log = () => {}; try { assert.equal(installer.purgeData(dir), 0); assert.equal(fs.existsSync(dir), false); assert.equal(installer.purgeData(dir), 0); } finally { console.log = log; } }); test("install.js --uninstall: an unknown extra option is refused", () => { const r = spawnSync(process.execPath, [INSTALL, "--uninstall", "--nuke"], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } }); assert.equal(r.status, 1); assert.match(r.stderr, /Unknown option\(s\): --uninstall --nuke/); }); test("install.js --uninstall: with no terminal and no --yes it explains, exits 1 and removes nothing", () => { fs.mkdirSync(path.join(HOME, ".plan2code"), { recursive: true }); const r = spawnSync(process.execPath, [INSTALL, "--uninstall"], { encoding: "utf8", input: "", env: { ...process.env, HOME, USERPROFILE: HOME } }); assert.equal(r.status, 1, r.stderr); assert.match(r.stdout, /Run plan2code uninstall --yes/); assert.ok(fs.existsSync(path.join(HOME, ".plan2code"))); }); test("install: the Node guard names the version on Node older than 18", () => { assert.equal(installer.nodeVersionProblem("16.20.2"), "Plan2Code needs Node.js 18 or newer; you have v16.20.2. Get it from nodejs.org"); assert.equal(installer.nodeVersionProblem("17.9.1").startsWith("Plan2Code needs Node.js 18 or newer"), true); assert.equal(installer.nodeVersionProblem("18.0.0"), null); assert.equal(installer.nodeVersionProblem("26.1.0"), null); }); test("install: an old Node fails fast with the guard's sentence before installing anything", () => { const code = `Object.defineProperty(process.versions, "node", { value: "16.20.2" }); require(${JSON.stringify(INSTALL)});`; const result = spawnSync(process.execPath, ["-e", code], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } }); assert.equal(result.status, 1); assert.match(result.stderr, /Plan2Code needs Node\.js 18 or newer; you have v16\.20\.2\. Get it from nodejs\.org/); }); test("uninstall: --purge also removes the app's webview data, and a failure there is non-zero", async () => { assert.equal((await runUninstall({ yes: true, purge: true, purgeWebview: () => 1 })).code, 1); const kept = await runUninstall({ yes: true }); assert.deepEqual(kept.calls, ["remove"]); }); test("uninstall: a running app is named before anything is removed", async () => { const r = await runUninstall({ yes: true, running: () => true }); assert.match(r.out, /Plan2Code is running: close it first/); const quiet = await runUninstall({ yes: true }); assert.doesNotMatch(quiet.out, /is running/); }); test("appWebviewDirs: the webview data folder for com.plan2code.desktop on each OS", () => { const home = path.join(path.sep, "h"); // The last folder on each OS is the app's config folder, where the window-state file lives. assert.deepEqual(installer.appWebviewDirs({ platform: "win32", home, env: { LOCALAPPDATA: path.join(home, "Local"), APPDATA: path.join(home, "Roaming") } }), [ path.join(home, "Local", "com.plan2code.desktop"), path.join(home, "Roaming", "com.plan2code.desktop"), ]); assert.deepEqual(installer.appWebviewDirs({ platform: "win32", home, env: {} }), [ path.join(home, "AppData", "Local", "com.plan2code.desktop"), path.join(home, "AppData", "Roaming", "com.plan2code.desktop"), ]); assert.deepEqual(installer.appWebviewDirs({ platform: "linux", home, env: {} }), [ path.join(home, ".local", "share", "com.plan2code.desktop"), path.join(home, ".cache", "com.plan2code.desktop"), path.join(home, ".config", "com.plan2code.desktop"), ]); assert.deepEqual(installer.appWebviewDirs({ platform: "linux", home, env: { XDG_DATA_HOME: path.join(home, "d"), XDG_CACHE_HOME: path.join(home, "c"), XDG_CONFIG_HOME: path.join(home, "g") } }), [ path.join(home, "d", "com.plan2code.desktop"), path.join(home, "c", "com.plan2code.desktop"), path.join(home, "g", "com.plan2code.desktop"), ]); assert.deepEqual(installer.appWebviewDirs({ platform: "darwin", home, env: {} }), [ path.join(home, "Library", "WebKit", "com.plan2code.desktop"), path.join(home, "Library", "WebKit", "plan2code-app"), path.join(home, "Library", "Caches", "com.plan2code.desktop"), path.join(home, "Library", "Caches", "plan2code-app"), path.join(home, "Library", "Application Support", "com.plan2code.desktop"), ]); }); test("purgeAppWebview: removes the folders that exist and skips the rest", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-webview-")); const there = path.join(dir, "com.plan2code.desktop"); fs.mkdirSync(path.join(there, "EBWebView"), { recursive: true }); const log = console.log; console.log = () => {}; try { assert.equal(installer.purgeAppWebview([there, path.join(dir, "missing")]), 0); assert.equal(fs.existsSync(there), false); } finally { console.log = log; fs.rmSync(dir, { recursive: true, force: true }); } }); test("appRunning: asks tasklist on Windows and pgrep elsewhere by the program's name", () => { const seen = []; const run = (cmd, args) => (seen.push([cmd, ...args]), { status: 0, stdout: cmd === "tasklist" ? "plan2code-app.exe 1234 Console" : "" }); assert.equal(installer.appRunning({ platform: "win32", run }), true); assert.equal(installer.appRunning({ platform: "win32", run: () => ({ status: 0, stdout: "INFO: No tasks are running" }) }), false); assert.equal(installer.appRunning({ platform: "linux", run }), true); assert.equal(installer.appRunning({ platform: "darwin", run: () => ({ status: 1 }) }), false); assert.equal(installer.appRunning({ platform: "linux", run: () => { throw new Error("no pgrep"); } }), false); assert.deepEqual(seen[1], ["pgrep", "-x", "plan2code-app"]); }); // --------------------------------------------------------------------------------------------- // The next steps after an install: on or off PATH, with or without the desktop app. // --------------------------------------------------------------------------------------------- /** printGettingStarted's output with colors stripped. */ async function gettingStarted(options) { const { out } = await captured(() => installer.printGettingStarted({ commandInstalled: true, agents: { found: ["Claude Code"], builtins: [] }, ...options })); return out; } const POSIX_BIN = "/home/me/.local/bin"; test("next steps: on PATH without the app, plan2code opens the agent and no PATH line is printed", async () => { const out = await gettingStarted({ pathMissing: false, appInstalled: false, platform: "linux" }); assert.match(out, /plan2code\s+opens your AI agent on the Plan2Code dashboard/); assert.match(out, /page that opens in your browser/); assert.doesNotMatch(out, /not on your PATH|export PATH|open a new terminal/); }); test("next steps: on PATH with the app, steps 2 and 3 name the Plan2Code app", async () => { const out = await gettingStarted({ pathMissing: false, appInstalled: true, platform: "linux" }); assert.match(out, /plan2code\s+opens the Plan2Code app/); assert.match(out, /3\. Pick a card on the dashboard: plan2code opens the Plan2Code app/); assert.doesNotMatch(out, /page that opens in your browser|export PATH/); }); test("next steps: off PATH without the app, the shell's PATH line, a new terminal and the full path", async () => { const out = await gettingStarted({ pathMissing: true, binDir: POSIX_BIN, appInstalled: false, platform: "linux", shell: "/bin/zsh" }); assert.match(out, /export PATH="[^"]*\.local\/bin:\$PATH"' >> ~\/\.zshrc/); assert.match(out, /open a new terminal/); assert.ok(out.includes(`"${POSIX_BIN}/plan2code"`), out); assert.match(out, /opens your AI agent on the Plan2Code dashboard/); }); test("next steps: off PATH with the app on Windows, the PowerShell line, a new terminal, the .cmd path and the app", async () => { const bin = "C:\\Users\\me\\AppData\\Roaming\\npm"; const out = await gettingStarted({ pathMissing: true, binDir: bin, appInstalled: true, platform: "win32" }); assert.ok(out.includes(`[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';${bin}', 'User')`), out); assert.match(out, /open a new terminal/); assert.ok(out.includes(`& "${bin}\\plan2code.cmd"`), out); assert.match(out, /opens the Plan2Code app/); }); test("pathFixLine: bash and other shells get ~/.bashrc, a folder under home is written with $HOME", () => { const fix = installer.pathFixLine("/home/me/.local/bin", { platform: "linux", shell: "/bin/bash", home: "/home/me" }); assert.equal(fix.file, "~/.bashrc"); assert.equal(fix.line, `echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc`); assert.equal(installer.pathFixLine("/home/me/.local/bin", { platform: "darwin", shell: "/bin/zsh", home: "/home/me" }).file, "~/.zshrc"); assert.equal(installer.pathFixLine("/opt/bin", { platform: "linux", shell: "/bin/bash", home: "/home/me" }).line, `echo 'export PATH="/opt/bin:$PATH"' >> ~/.bashrc`); }); test("next steps: with no agent found, plan2code's setup page is the lead and custom agents go to User Preferences", async () => { const builtins = [{ name: "Claude Code", installUrl: "https://example.test/claude", install: { linux: [{ run: "curl -fsSL https://example.test/install.sh | bash" }] } }]; const out = await gettingStarted({ agents: { found: [], builtins }, platform: "linux" }); assert.match(out, /No agent yet\? Just run plan2code: its setup page installs one with you\./); assert.ok(out.includes("curl -fsSL https://example.test/install.sh | bash (https://example.test/claude)"), out); assert.match(out, /User Preferences, Agents & models/); assert.doesNotMatch(out, /NO AI AGENT FOUND|agents\.json/); }); test("detectAgents: reads the shipped list and lookup, and finds a custom agent by its command", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-")); try { const userFile = path.join(dir, "user-agents.json"); fs.writeFileSync(userFile, JSON.stringify({ schema: 1, agents: [{ id: "mine", name: "Mine", command: process.execPath }] })); const nowhere = { path: "", savedPath: "", npmBin: "", home: dir, vars: {} }; const result = await installer.detectAgents({ binDir: dir, userAgentsFile: userFile, env: nowhere }); assert.ok(result.builtins.some((entry) => entry.id === "claude"), "falls back to src/ when nothing is installed"); assert.deepEqual(result.found, ["Mine"]); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("desktopAppState: installed, failed, or skipped when declined, not offered or not built yet", () => { assert.equal(installer.desktopAppState({ app: true }), "installed"); assert.equal(installer.desktopAppState({ app: false }), "failed"); assert.equal(installer.desktopAppState({ app: false, appMissing: "no file yet" }), "skipped"); assert.equal(installer.desktopAppState({}), "skipped"); }); test("launcher shim: a plan2code without the launcher marker is saved as .bak, ours is replaced in place", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shim-")); const foreign = "#!/bin/sh\necho another tool\n"; try { const file = path.join(dir, "plan2code"); const shim = { file, content: `#!/bin/sh\n# ${installer.LAUNCHER_MARKER}\nexit 0\n` }; fs.writeFileSync(file, foreign); assert.equal(installer.isOurLauncherShim(file), false); assert.deepEqual(installer.writeLauncherShim(shim), { backup: `${file}.bak` }); assert.equal(fs.readFileSync(`${file}.bak`, "utf8"), foreign); assert.equal(installer.isOurLauncherShim(file), true); assert.deepEqual(installer.writeLauncherShim(shim), { backup: null }, "our own shim is never backed up"); assert.equal(fs.readFileSync(`${file}.bak`, "utf8"), foreign); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("install.js: with no terminal the menu is not shown; it says how to install and exits 1", () => { const r = spawnSync(process.execPath, [INSTALL], { encoding: "utf8", input: "", env: { ...process.env, HOME, USERPROFILE: HOME } }); assert.equal(r.status, 1, r.stdout + r.stderr); assert.equal(r.stdout.trim(), installer.NO_TERMINAL_MESSAGE); assert.equal(installer.NO_TERMINAL_MESSAGE, "Run this in a terminal, or use `--update` for an unattended install."); }); test("install.js: piped output carries no escape codes and no boxes", () => { const code = `require(${JSON.stringify(INSTALL)}).printGettingStarted({ commandInstalled: true, agents: { found: [], builtins: [] } })`; const piped = spawnSync(process.execPath, ["-e", code], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } }); assert.equal(piped.status, 0, piped.stderr); assert.match(piped.stdout, /How to use Plan2Code/); assert.doesNotMatch(piped.stdout, /\x1b\[|╭|╰/); }); test("createSpinner: piped, it prints its label once as a plain line and draws nothing", () => { const writes = []; const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); try { const spinner = installer.createSpinner("Running skills add...", { stream: { isTTY: false, write: (s) => writes.push(s) } }).start(); spinner.stop(); } finally { console.log = log; } assert.deepEqual(lines, [" Running skills add..."]); assert.deepEqual(writes, []); }); test("createSpinner: on a terminal it redraws one line with the seconds and clears it on stop", () => { const writes = []; const spinner = installer.createSpinner("Running skills add...", { stream: { isTTY: true, write: (s) => writes.push(s) } }).start(); spinner.stop(); assert.match(writes[0], /^\r {2}\S+ Running skills add\.\.\. 0s/); assert.equal(writes.at(-1), "\r\x1b[K"); }); test("detectAgents: an agent only in npm's folder or an install folder off PATH is not present, as the launcher sees it", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-off-")); try { for (const name of ["claude", "claude.cmd"]) fs.writeFileSync(path.join(dir, name), ""); if (process.platform !== "win32") fs.chmodSync(path.join(dir, "claude"), 0o755); const none = path.join(dir, "none.json"); const off = { path: "", savedPath: "", npmBin: dir, home: dir, pathext: ".CMD", vars: {} }; assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: none, env: off })).found, []); const on = { ...off, npmBin: "", path: dir }; assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: none, env: on })).found, ["Claude Code"]); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("detectAgents: a custom agents file with the wrong schema is ignored, as the launcher ignores it", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-schema-")); try { const userFile = path.join(dir, "user-agents.json"); fs.writeFileSync(userFile, JSON.stringify({ schema: 99, agents: [{ id: "mine", name: "Mine", command: process.execPath }] })); const nowhere = { path: "", savedPath: "", npmBin: "", home: dir, vars: {} }; assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: userFile, env: nowhere })).found, []); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("next steps: without the plan2code command, no line tells the person to run it", async () => { const { out } = await captured(() => installer.printGettingStarted({ commandInstalled: false, agents: { found: [], builtins: [] }, platform: "linux" })); assert.doesNotMatch(out, /run plan2code|Just run plan2code/); assert.match(out, /type \/plan2code/); }); // --------------------------------------------------------------------------------------------- // Uninstall: works without the skills CLI, prints only what was installed, removes the console, // lists what stays, and always ends with the Removed / Could not remove / To finish block. // Everything runs against the temp HOME above; the steps that would reach the real machine (the // npm global bin, the desktop folder) are replaced. // --------------------------------------------------------------------------------------------- const CLAUDE_DIR = path.join(HOME, ".claude"); const SKILL_STORE = path.join(HOME, ".agents", "skills"); /** The legacy sweep reads %APPDATA% and %LOCALAPPDATA% on Windows: point them into the temp HOME while `fn` runs. */ function withAppData(fn) { const saved = { APPDATA: process.env.APPDATA, LOCALAPPDATA: process.env.LOCALAPPDATA }; process.env.APPDATA = path.join(HOME, "AppData", "Roaming"); process.env.LOCALAPPDATA = path.join(HOME, "AppData", "Local"); try { return fn(); } finally { for (const [key, value] of Object.entries(saved)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } } } function makeSkill(name) { fs.mkdirSync(path.join(SKILL_STORE, name), { recursive: true }); fs.writeFileSync(path.join(SKILL_STORE, name, "SKILL.md"), "---\nname: x\n---\n"); } test("uninstall without the skills CLI: the plan2code skill folders go directly, others stay, and the block says links may remain", () => { fs.rmSync(SKILL_STORE, { recursive: true, force: true }); for (const name of ["plan2code", "plan2code-plan", "plan2code-3-implement", "someone-elses-skill"]) makeSkill(name); const report = installer.newUninstallReport(); const result = withAppData(() => installer.uninstallSkillsPiece(report, { cli: { ensure: () => false, remove: () => assert.fail("the CLI is unreachable") } })); assert.equal(result.removed, 3); assert.deepEqual(result.failed, []); assert.deepEqual(fs.readdirSync(SKILL_STORE), ["someone-elses-skill"]); assert.equal(report.finish.length, 1); assert.match(report.finish[0], /could not be reached/); assert.match(report.finish[0], /may remain/); assert.deepEqual(installer.removeSkillsDirectly(SKILL_STORE), { removed: [], failed: [] }, "nothing left to remove, no error"); }); test("uninstall with the skills CLI: it does the removing and no folder is touched by hand", () => { fs.rmSync(SKILL_STORE, { recursive: true, force: true }); makeSkill("plan2code"); const calls = []; const report = installer.newUninstallReport(); const result = withAppData(() => installer.uninstallSkillsPiece(report, { cli: { ensure: () => true, remove: (scope, options) => (calls.push([scope, options.quiet]), 1) }, }) ); assert.deepEqual(calls, [["global", true]]); assert.equal(result.removed, 1); assert.deepEqual(report.finish, [], "nothing is left to do"); assert.ok(fs.existsSync(path.join(SKILL_STORE, "plan2code")), "the stand-in CLI removed nothing, and nothing else did"); fs.rmSync(SKILL_STORE, { recursive: true, force: true }); }); /** uninstallAll() with every step replaced by one that records itself; `results` says what each reports. */ function uninstallWith({ pieces, results = {}, probes = {} }) { if (pieces) writeRecord(pieces); else clearRecord(); const ran = []; const steps = {}; for (const piece of installer.INSTALL_PIECES) { steps[piece] = () => (ran.push(piece), results[piece] || { removed: 1, failed: [] }); } const report = installer.newUninstallReport(); const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); let code; try { code = installer.uninstallAll({ report, steps, probes, removeConsole: () => {} }); } finally { console.log = log; } return { code, ran, report, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") }; } const NO_STRAYS = { skills: () => false, launcher: () => false, app: () => false, statusline: () => false }; test("uninstall: only the recorded pieces are removed and named, never ones that were not installed", () => { const r = uninstallWith({ pieces: ["skills", "launcher"], probes: NO_STRAYS, results: { skills: { removed: 23, failed: [], detail: "23" } } }); assert.equal(r.code, 0, r.out); assert.deepEqual(r.ran, ["skills", "launcher"]); assert.match(r.out, /Removed Skills \(23\)/); assert.match(r.out, /Removed plan2code command/); assert.doesNotMatch(r.out, /Status line|Metrics|Bot|Desktop app|UNINSTALL|plan2code-metrics|plan2code-bot/); assert.deepEqual(r.report.removed, ["Skills (23)", "plan2code command"]); }); test("uninstall: a piece missing from the record but found on disk is removed, and a piece found nowhere is not run", () => { const r = uninstallWith({ pieces: null, probes: { ...NO_STRAYS, statusline: () => true } }); assert.deepEqual(r.ran, ["statusline"]); assert.match(r.out, /Removed Status line/); }); test("uninstall: the real probes look at the temp HOME and find nothing there", () => { fs.rmSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), { force: true }); fs.rmSync(SKILL_STORE, { recursive: true, force: true }); fs.rmSync(installer.APP_DEST, { force: true }); assert.equal(installer.UNINSTALL_PROBES.skills(), false); assert.equal(installer.UNINSTALL_PROBES.app(), false); assert.equal(installer.UNINSTALL_PROBES.statusline(), false); fs.mkdirSync(CLAUDE_DIR, { recursive: true }); fs.writeFileSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), "// ours"); assert.equal(installer.UNINSTALL_PROBES.statusline(), true); fs.rmSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), { force: true }); }); test("uninstall: the status line says it kept statusline-config.json only when that file exists", async () => { fs.mkdirSync(CLAUDE_DIR, { recursive: true }); fs.rmSync(path.join(CLAUDE_DIR, "statusline-config.json"), { force: true }); const quiet = (await captured(() => installer.uninstallStatusLine())).out; assert.doesNotMatch(quiet, /Preserved: statusline-config\.json/); fs.writeFileSync(path.join(CLAUDE_DIR, "statusline-config.json"), "{}"); const kept = (await captured(() => installer.uninstallStatusLine())).out; assert.match(kept, /Preserved: statusline-config\.json/); fs.rmSync(path.join(CLAUDE_DIR, "statusline-config.json"), { force: true }); }); test("uninstall: a piece that fails is named, makes the exit code 1, and the others still run", () => { const r = uninstallWith({ pieces: ["skills", "launcher", "app"], probes: NO_STRAYS, results: { launcher: { removed: 0, failed: ["EBUSY: file in use"] } } }); assert.equal(r.code, 1, r.out); assert.deepEqual(r.ran, ["skills", "launcher", "app"]); assert.deepEqual(r.report.failed, ["plan2code command: EBUSY: file in use"]); assert.match(r.out, /plan2code command: EBUSY: file in use/); }); test("uninstall: the console's version folders and pointer are removed, a running console is stopped first, and sessions stay", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-home-")); process.env.PLAN2CODE_CONSOLE_HOME = home; try { for (const version of ["3.0.2", "3.1.0"]) { fs.mkdirSync(path.join(home, version, "public"), { recursive: true }); fs.writeFileSync(path.join(home, version, "console.mjs"), "// console"); } fs.writeFileSync(path.join(home, "console-dir"), path.join(home, "3.1.0")); fs.mkdirSync(path.join(home, "sessions", "s1"), { recursive: true }); fs.writeFileSync(path.join(home, "looks.json"), "{}"); const stopped = []; const report = installer.newUninstallReport(); const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); try { installer.removeConsoleFolders(report, { stop: (dir) => (stopped.push(dir), 1) }); } finally { console.log = log; } const out = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, ""); assert.deepEqual(stopped, [home]); assert.match(out, /Stopped 1 running Plan2Code console first/); assert.deepEqual(fs.readdirSync(home).sort(), ["looks.json", "sessions"]); assert.deepEqual(report.removed, ["Console files"]); assert.deepEqual(report.failed, []); } finally { delete process.env.PLAN2CODE_CONSOLE_HOME; fs.rmSync(home, { recursive: true, force: true }); } }); test("uninstall: a console folder that cannot be removed is reported with what to do, and a missing console home is fine", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-busy-")); process.env.PLAN2CODE_CONSOLE_HOME = home; const realRm = fs.rmSync; try { fs.mkdirSync(path.join(home, "3.0.2"), { recursive: true }); fs.mkdirSync(path.join(home, "3.1.0"), { recursive: true }); fs.rmSync = (target, options) => { if (String(target).endsWith("3.0.2")) throw new Error("EBUSY: resource busy"); return realRm(target, options); }; const report = installer.newUninstallReport(); const log = console.log; console.log = () => {}; try { installer.removeConsoleFolders(report, { stop: () => 0 }); } finally { console.log = log; fs.rmSync = realRm; } assert.deepEqual(report.failed, ["Console files 3.0.2: EBUSY: resource busy"]); assert.deepEqual(report.finish, ["Close any open Plan2Code console or app, then run plan2code uninstall again."]); assert.deepEqual(report.removed, ["Console files"]); assert.ok(fs.existsSync(path.join(home, "3.0.2")) && !fs.existsSync(path.join(home, "3.1.0"))); process.env.PLAN2CODE_CONSOLE_HOME = path.join(home, "nowhere"); assert.doesNotThrow(() => installer.removeConsoleFolders(installer.newUninstallReport(), { stop: () => 0 })); } finally { fs.rmSync = realRm; delete process.env.PLAN2CODE_CONSOLE_HOME; realRm(home, { recursive: true, force: true }); } }); test("uninstall: what stays in the data folder is listed by name with its size, and the closing block always prints", async () => { const data = path.join(HOME, ".plan2code"); fs.rmSync(path.join(data, "notepads"), { recursive: true, force: true }); fs.mkdirSync(path.join(data, "notepads"), { recursive: true }); fs.writeFileSync(path.join(data, "notepads", "a.json"), "x".repeat(2048)); fs.mkdirSync(path.join(data, "handoffs"), { recursive: true }); const listed = installer.listKeptData(data); const notebooks = listed.find((item) => item.name === "notepads"); assert.equal(notebooks.label, "Notebooks"); assert.equal(notebooks.bytes, 2048); assert.ok(listed.some((item) => item.name === "handoffs" && item.label === "Handoffs")); const kept = await runUninstall({ yes: true }); assert.equal(kept.code, 0); assert.match(kept.out, /Your data in .* was kept/); assert.match(kept.out, /Notebooks: 2 KB/); assert.match(kept.out, /Removed: nothing/); assert.match(kept.out, /Could not remove: nothing/); assert.match(kept.out, /To finish: nothing, you are done/); assert.match(kept.out, /Plan2Code is uninstalled/); // A failed run still ends on the block, says that something failed, and leaves no cheerful closing line. const failed = await runUninstall({ yes: true, remove: () => 1 }); assert.equal(failed.code, 1); assert.match(failed.out, /Removed: nothing/); assert.match(failed.out, /Could not remove:\n\s+✗ One or more pieces/); assert.match(failed.out, /To finish:/); assert.doesNotMatch(failed.out, /Plan2Code is uninstalled/); // With the data deleted there is nothing to list, and the block names the data as removed. const purged = await runUninstall({ yes: true, purge: true }); assert.doesNotMatch(purged.out, /Notebooks:/); assert.match(purged.out, /Removed: Your Plan2Code data/); fs.rmSync(path.join(data, "notepads"), { recursive: true, force: true }); fs.rmSync(path.join(data, "handoffs"), { recursive: true, force: true }); }); // ============================================================================ // Copy-once skills install: the adaptive skills CLI runner and the canonical store // ============================================================================ const skillsCliRunner = require(path.join(ROOT, "src", "installer", "skills-cli.js")); const canonical = require(path.join(ROOT, "src", "installer", "canonical-skills.js")); /** A temp folder removed after the test. */ function scratch(t, prefix = "p2c-canonical-") { const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); return dir; } /** A built skills tree: `{ name: { "SKILL.md": "...", "sub/file": "..." } }`. */ function writeBuilt(dir, skills) { for (const [name, files] of Object.entries(skills)) { for (const [rel, text] of Object.entries(files)) { const file = path.join(dir, name, ...rel.split("/")); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); } } return dir; } const BUILT = { "plan2code-alpha": { "SKILL.md": "alpha", "references/a.md": "a" }, "plan2code-beta": { "SKILL.md": "beta", "scripts/b.mjs": "b" }, }; const NAMES = Object.keys(BUILT); /** A link to a folder: a junction on Windows (no admin needed), a symlink elsewhere. */ function linkDir(target, link) { fs.symlinkSync(target, link, process.platform === "win32" ? "junction" : "dir"); } /** * A stand-in skills CLI, laid out as npx caches it (`/_npx//node_modules/skills`), * that appends each call's arguments to calls.jsonl and exits with `exitCodes[command]`. */ function fakeSkillsCli(t, { version = installer.SKILLS_CLI_VERSION, exitCodes = {} } = {}) { const cache = scratch(t, "p2c-fake-npm-cache-"); const pkgDir = path.join(cache, "_npx", "0123abcd", "node_modules", "skills"); fs.mkdirSync(path.join(pkgDir, "bin"), { recursive: true }); fs.mkdirSync(path.join(cache, "_npx", "0123abcd", "node_modules", "yaml"), { recursive: true }); fs.writeFileSync(path.join(cache, "_npx", "0123abcd", "node_modules", "yaml", "package.json"), JSON.stringify({ name: "yaml", version: "2.8.3" })); fs.writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "skills", version, dependencies: { yaml: "^2.8.3" } })); const log = path.join(cache, "calls.jsonl"); fs.writeFileSync( path.join(pkgDir, "bin", "cli.mjs"), [ 'import fs from "node:fs";', "const args = process.argv.slice(2);", `fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify(args) + "\\n");`, `const codes = ${JSON.stringify(exitCodes)};`, 'console.log("fake skills " + args.join(" "));', "process.exitCode = codes[args[0]] || 0;", "", ].join("\n"), ); const cli = skillsCliRunner.resolveSkillsCli(version, { caches: [cache] }); const calls = () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : []); return { cache, cli, calls }; } /** Run `fn` with console.log captured: `{ value, out }`. */ async function quietly(fn) { const lines = []; const log = console.log; console.log = (...args) => lines.push(args.join(" ")); try { return { value: await fn(), out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") }; } finally { console.log = log; } } test("skills CLI pins: 1.5.18 below Node 22.20.0, 1.7.6 at 22.20.0 and above, from explicit version numbers", () => { assert.deepEqual({ ...skillsCliRunner.SKILLS_CLI_PINS }, { legacy: "1.5.18", current: "1.7.6", nodeFloor: "22.20.0" }); for (const node of ["18.0.0", "v20.19.5", "22.19.9", "22.9.0", "garbage", ""]) assert.equal(skillsCliRunner.selectSkillsCliVersion(node), "1.5.18", node); for (const node of ["22.20.0", "v22.20.1", "22.100.0", "24.0.0", "26.13.1"]) assert.equal(skillsCliRunner.selectSkillsCliVersion(node), "1.7.6", node); assert.equal(installer.SKILLS_CLI_VERSION, skillsCliRunner.selectSkillsCliVersion(process.versions.node)); }); test("npm cache candidates: npm_config_cache first, then the platform default, then old Windows npm's folder", () => { assert.deepEqual(skillsCliRunner.npmCacheCandidates({ npm_config_cache: "/c" }, "linux", "/home/me"), ["/c", "/home/me/.npm"]); assert.deepEqual(skillsCliRunner.npmCacheCandidates({}, "darwin", "/Users/me"), ["/Users/me/.npm"]); assert.deepEqual( skillsCliRunner.npmCacheCandidates({ NPM_CONFIG_CACHE: "D:\\cache", LOCALAPPDATA: "C:\\L", APPDATA: "C:\\R" }, "win32", "C:\\Users\\me"), ["D:\\cache", "C:\\L\\npm-cache", "C:\\R\\npm-cache"], ); assert.deepEqual(skillsCliRunner.npmCacheCandidates({}, "win32", "C:\\Users\\me"), ["C:\\Users\\me\\AppData\\Local\\npm-cache", "C:\\Users\\me\\AppData\\Roaming\\npm-cache"]); }); test("resolveSkillsCli: an exact cached copy runs through node directly; any other cache state falls back to the pinned npx", (t) => { const hit = fakeSkillsCli(t); assert.deepEqual(hit.cli, { kind: "cached", executable: process.execPath, argsPrefix: [path.join(hit.cache, "_npx", "0123abcd", "node_modules", "skills", "bin", "cli.mjs")], pin: installer.SKILLS_CLI_VERSION, }); const npx = { kind: "npx", command: "npx", argsPrefix: ["--yes", "skills@1.7.6"], pin: "1.7.6" }; // Another version, a missing cli.mjs, a missing dependency, an unreadable package.json, no cache. assert.deepEqual(skillsCliRunner.resolveSkillsCli("1.7.6", { caches: [fakeSkillsCli(t, { version: "1.9.1" }).cache] }), npx); const noCli = fakeSkillsCli(t, { version: "1.7.6" }); fs.rmSync(noCli.cli.argsPrefix[0]); assert.deepEqual(skillsCliRunner.resolveSkillsCli("1.7.6", { caches: [noCli.cache] }), npx); const noDep = fakeSkillsCli(t, { version: "1.7.6" }); fs.rmSync(path.join(noDep.cache, "_npx", "0123abcd", "node_modules", "yaml"), { recursive: true }); assert.deepEqual(skillsCliRunner.resolveSkillsCli("1.7.6", { caches: [noDep.cache] }), npx); const broken = fakeSkillsCli(t, { version: "1.7.6" }); fs.writeFileSync(path.join(broken.cache, "_npx", "0123abcd", "node_modules", "skills", "package.json"), "{ not json"); assert.deepEqual(skillsCliRunner.resolveSkillsCli("1.7.6", { caches: [broken.cache] }), npx); assert.deepEqual(skillsCliRunner.resolveSkillsCli("1.7.6", { caches: [path.join(os.tmpdir(), "p2c-no-such-cache")] }), npx); // The legacy pin falls back the same way. assert.deepEqual(skillsCliRunner.resolveSkillsCli("1.5.18", { caches: [] }).argsPrefix, ["--yes", "skills@1.5.18"]); }); test("skills CLI spawn: the cached CLI never goes through a shell; npx needs one on Windows only, with each argument quoted", () => { const cached = { kind: "cached", executable: "/usr/bin/node", argsPrefix: ["/c/cli.mjs"], pin: "1.7.6" }; assert.deepEqual(skillsCliRunner.spawnPlan(cached, ["add", "C:\\a b & c", "-y"], "win32"), { file: "/usr/bin/node", args: ["/c/cli.mjs", "add", "C:\\a b & c", "-y"], shell: false }); const npx = { kind: "npx", command: "npx", argsPrefix: ["--yes", "skills@1.7.6"], pin: "1.7.6" }; assert.deepEqual(skillsCliRunner.spawnPlan(npx, ["add", "/a b", "-y"], "linux"), { file: "npx", args: ["--yes", "skills@1.7.6", "add", "/a b", "-y"], shell: false }); assert.deepEqual(skillsCliRunner.spawnPlan(npx, ["add", "C:\\Users\\A B\\.agents\\skills", "-y"], "win32"), { file: 'npx --yes skills@1.7.6 add "C:\\Users\\A B\\.agents\\skills" -y', args: [], shell: true, }); }); test("skills CLI run: sync and async give { ok, output }, captured, stdout and stderr together on a failure", async (t) => { const fake = fakeSkillsCli(t, { exitCodes: { remove: 3 } }); assert.deepEqual(skillsCliRunner.execSkillsCliSync(fake.cli, ["add", "x y", "-y"]), { ok: true, output: "fake skills add x y -y" }); assert.deepEqual(await skillsCliRunner.execSkillsCliAsync(fake.cli, ["list"]), { ok: true, output: "fake skills list" }); const failed = skillsCliRunner.execSkillsCliSync(fake.cli, ["remove", "a"]); assert.equal(failed.ok, false); assert.match(failed.output, /fake skills remove a/); assert.equal((await skillsCliRunner.execSkillsCliAsync(fake.cli, ["remove", "a"])).ok, false); // The argument with a space arrived whole: no shell split it. assert.deepEqual(fake.calls()[0], ["add", "x y", "-y"]); }); test("install and the project install run no separate skills --version check", () => { const source = fs.readFileSync(INSTALL, "utf8"); for (const name of ["async function install(", "async function installProjectSkills(", "async function installCanonicalSkills("]) { const start = source.indexOf(name); assert.ok(start >= 0, name); const body = source.slice(start, source.indexOf("\n}\n", start)); assert.doesNotMatch(body, /ensureSkillsCli|--version/, `${name} has no CLI preflight`); } }); test("canonical store: global and project roots follow the skills CLI's rule", () => { assert.equal(canonical.canonicalRoot("global", "/work/app", "/home/me"), path.join("/home/me", ".agents", "skills")); assert.equal(canonical.canonicalRoot("project", "/work/app", "/home/me"), path.join("/work/app", ".agents", "skills")); }); test("canonical stage: copies each skill once, checks it, and refuses missing skills, unsafe names and links in the build", (t) => { const home = scratch(t); const built = writeBuilt(scratch(t), BUILT); const writes = new Map(); const realWrite = fs.writeFileSync; fs.writeFileSync = (file, ...rest) => { writes.set(String(file), (writes.get(String(file)) || 0) + 1); return realWrite(file, ...rest); }; let stage; try { stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home, version: "9.9.9", sourceRef: "v9.9.9" }); } finally { fs.writeFileSync = realWrite; } assert.deepEqual(stage.files, ["plan2code-alpha/SKILL.md", "plan2code-alpha/references/a.md", "plan2code-beta/SKILL.md", "plan2code-beta/scripts/b.mjs"]); for (const rel of stage.files) assert.equal(writes.get(path.join(stage.stageDir, ...rel.split("/"))), 1, `${rel} written once`); assert.equal(path.dirname(stage.stageDir), path.join(home, ".agents"), "the stage sits beside the store"); assert.match(path.basename(stage.stageDir), /^\.skills-stage-\d+-\d+$/); const staged = JSON.parse(fs.readFileSync(path.join(stage.stageDir, canonical.MANIFEST_NAME), "utf8")); assert.equal(staged.complete, false); assert.equal(staged.journal, null); assert.equal(staged.version, "9.9.9"); assert.equal(staged.sourceRef, "v9.9.9"); assert.deepEqual(Object.keys(staged.files), stage.files); assert.equal(staged.treeHash, stage.treeHash); assert.ok(!fs.existsSync(path.join(home, ".agents", "skills")), "nothing in the store yet"); assert.equal(canonical.readJournal(path.join(home, ".agents", "skills")).records[0].op, "staged"); // The same build stages to the same hashes. const again = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home }); assert.equal(again.treeHash, stage.treeHash); assert.throws(() => canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: [...NAMES, "plan2code-gone"], home }), { code: "missing-skill" }); for (const bad of ["../escape", "a/b", "..", ""]) { assert.throws(() => canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: [bad], home }), { code: "bad-name" }, bad); } const outside = writeBuilt(scratch(t), { elsewhere: { "x.md": "x" } }); linkDir(path.join(outside, "elsewhere"), path.join(built, "plan2code-alpha", "linked")); const before = fs.readdirSync(path.join(home, ".agents")).filter((n) => n.startsWith(".skills-stage-")).length; assert.throws(() => canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home }), { code: "link-in-tree" }); assert.equal(fs.readdirSync(path.join(home, ".agents")).filter((n) => n.startsWith(".skills-stage-")).length, before, "a refused stage is removed"); }); test("canonical commit: swaps the stage in, writes the complete manifest and clears the stage, backups and journal", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); writeBuilt(root, { "plan2code-alpha": { "SKILL.md": "old alpha", "old.md": "gone after the swap" }, "other-skill": { "SKILL.md": "not ours" } }); const built = writeBuilt(scratch(t), BUILT); const stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home, version: "9.9.9" }); const done = canonical.commitCanonicalSkills(stage); assert.equal(done.complete, true); assert.deepEqual(done.warnings, []); assert.equal(fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"), "alpha"); assert.ok(!fs.existsSync(path.join(root, "plan2code-alpha", "old.md"))); assert.equal(fs.readFileSync(path.join(root, "other-skill", "SKILL.md"), "utf8"), "not ours", "another tool's skill is left alone"); const manifest = canonical.readCanonicalManifest("global", undefined, home); assert.deepEqual(Object.keys(manifest).sort(), ["complete", "journal", "skills", "sourceRef", "version"]); assert.equal(manifest.complete, true); assert.equal(manifest.journal, null); assert.deepEqual(manifest.skills, stage.skills); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), ["skills"], "no stage, backup or journal left"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "9.9.9" }).complete, true); assert.deepEqual(canonical.validateCanonicalManifest("global", NAMES, { home, version: "9.9.10" }).problems, ["manifest is for 9.9.9"]); fs.writeFileSync(path.join(root, "plan2code-beta", "SKILL.md"), "edited"); assert.deepEqual(canonical.validateCanonicalManifest("global", NAMES, { home }).problems, ["plan2code-beta: changed on disk"]); fs.rmSync(path.join(root, "plan2code-beta"), { recursive: true }); assert.deepEqual(canonical.validateCanonicalManifest("global", NAMES, { home }).problems, ["plan2code-beta: missing"]); }); test("canonical commit: a junction or symlink in the store is unlinked itself, and what it pointed at is untouched", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); fs.mkdirSync(root, { recursive: true }); const target = writeBuilt(scratch(t), { "dev-alpha": { "SKILL.md": "a developer's own checkout" } }); linkDir(path.join(target, "dev-alpha"), path.join(root, "plan2code-alpha")); const stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: writeBuilt(scratch(t), BUILT), expectedNames: NAMES, home }); canonical.commitCanonicalSkills(stage); assert.ok(!fs.lstatSync(path.join(root, "plan2code-alpha")).isSymbolicLink(), "the link became a real copy"); assert.equal(fs.readFileSync(path.join(target, "dev-alpha", "SKILL.md"), "utf8"), "a developer's own checkout"); // A link where a skill should be is never complete: validation does not follow it. fs.rmSync(path.join(root, "plan2code-beta"), { recursive: true }); linkDir(path.join(target, "dev-alpha"), path.join(root, "plan2code-beta")); assert.deepEqual(canonical.validateCanonicalManifest("global", NAMES, { home }).problems, ["plan2code-beta: missing"]); }); test("canonical commit: a failed swap puts every skill and the old manifest back, and a retry then succeeds", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const v1 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v1 alpha" }, "plan2code-beta": { "SKILL.md": "v1 beta" } }); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: v1, expectedNames: NAMES, home, version: "1.0.0" })); const oldManifest = fs.readFileSync(path.join(root, canonical.MANIFEST_NAME), "utf8"); const built = writeBuilt(scratch(t), BUILT); const stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home, version: "2.0.0" }); let calls = 0; // The third rename (beta's backup) fails, as a file held open on Windows would. const rename = (from, to) => { if (++calls === 3) throw Object.assign(new Error("EBUSY: resource busy or locked"), { code: "EBUSY" }); fs.renameSync(from, to); }; // isLock off: this checks the roll back, not the held-folder fallback (tested below). assert.throws(() => canonical.commitCanonicalSkills(stage, { rename, isLock: () => false }), (err) => err.code === "commit-failed" && err.retryable === true && /EBUSY/.test(err.message)); assert.equal(fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"), "v1 alpha"); assert.equal(fs.readFileSync(path.join(root, "plan2code-beta", "SKILL.md"), "utf8"), "v1 beta"); assert.equal(fs.readFileSync(path.join(root, canonical.MANIFEST_NAME), "utf8"), oldManifest, "the old manifest is true again"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "1.0.0" }).complete, true); const ops = canonical.readJournal(root).records.map((r) => r.op); assert.ok(ops.includes("rolled-back"), "the journal records the roll back"); for (const record of canonical.readJournal(root).records) { for (const key of ["op", "scope", "operationId", "skill", "source", "destination", "at"]) assert.ok(key in record, `${record.op} has ${key}`); } const retry = canonical.reconcileCanonicalSkills("global", built, NAMES, { home, version: "2.0.0" }); assert.equal(retry.complete, true); assert.equal(retry.repaired, true); assert.equal(fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"), "alpha"); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), ["skills"]); }); test("canonical reconcile: an install killed mid-swap is put right from the build, and reports what it found", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const v1 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v1 alpha" }, "plan2code-beta": { "SKILL.md": "v1 beta" } }); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: v1, expectedNames: NAMES, home, version: "1.0.0" })); const built = writeBuilt(scratch(t), BUILT); // A real process exit after the first skill is swapped: no catch, no roll back. const script = [ `const c = require(${JSON.stringify(path.join(ROOT, "src", "installer", "canonical-skills.js"))});`, `const stage = c.stageCanonicalSkills({ scope: "global", builtDir: ${JSON.stringify(built)}, expectedNames: ${JSON.stringify(NAMES)}, home: ${JSON.stringify(home)}, version: "2.0.0" });`, "c.commitCanonicalSkills(stage, { hooks: { afterSwap: () => process.exit(9) } });", ].join("\n"); assert.equal(spawnSync(process.execPath, ["-e", script]).status, 9); const check = canonical.validateCanonicalManifest("global", NAMES, { home }); assert.equal(check.complete, false); assert.ok(check.problems.includes("manifest not complete") && check.problems.includes("a swap did not finish"), check.problems.join("; ")); // Without the build there is nothing to repair from: it says so and changes nothing. const blind = canonical.reconcileCanonicalSkills("global", null, NAMES, { home }); assert.equal(blind.complete, false); assert.ok(blind.issues.some((i) => /unfinished stage/.test(i)) && blind.issues.some((i) => /journal/.test(i)), blind.issues.join("; ")); assert.ok(fs.existsSync(canonical.journalPath(root)), "the journal is kept until the store is complete"); const fixed = canonical.reconcileCanonicalSkills("global", built, NAMES, { home, version: "2.0.0" }); assert.equal(fixed.complete, true); assert.equal(fixed.repaired, true); assert.equal(fs.readFileSync(path.join(root, "plan2code-beta", "SKILL.md"), "utf8"), "beta"); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), ["skills"], "stage, backups and journal cleared"); // A complete store is left as it is: nothing copied. const mtime = fs.statSync(path.join(root, "plan2code-alpha", "SKILL.md")).mtimeMs; assert.deepEqual(canonical.reconcileCanonicalSkills("global", built, NAMES, { home, version: "2.0.0" }), { complete: true, repaired: false, issues: [] }); assert.equal(fs.statSync(path.join(root, "plan2code-alpha", "SKILL.md")).mtimeMs, mtime); }); test("canonical reconcile: a skill moved to a backup but never replaced is put back before anything else", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const built = writeBuilt(scratch(t), BUILT); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home })); // A pid no process has: pid 1 is init on Linux, a live process, so its backup would count as a running install's. const backup = path.join(home, ".agents", ".skills-backup-999999999-2"); fs.mkdirSync(backup); fs.renameSync(path.join(root, "plan2code-beta"), path.join(backup, "plan2code-beta")); writeBuilt(backup, { "plan2code-retired": { "SKILL.md": "not expected: never restored" } }); const result = canonical.reconcileCanonicalSkills("global", null, NAMES, { home }); assert.equal(result.complete, true); assert.ok(result.issues.includes("restored plan2code-beta from a backup"), result.issues.join("; ")); assert.ok(!fs.existsSync(path.join(root, "plan2code-retired"))); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), ["skills"]); }); test("retired skills: only plan2code names the build no longer has; broken links are unlinked, never followed", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); writeBuilt(root, { "plan2code-alpha": { "SKILL.md": "kept" }, "plan2code-old": { "SKILL.md": "retired" }, "plan2code-stray": { "notes.md": "a stray copy with no SKILL.md" }, "other-skill": { "SKILL.md": "not ours" }, }); const target = writeBuilt(scratch(t), { outside: { "keep.md": "must survive" } }); linkDir(path.join(target, "outside"), path.join(root, "plan2code-linked")); const gone = writeBuilt(scratch(t), { vanished: { "SKILL.md": "x" } }); linkDir(path.join(gone, "vanished"), path.join(root, "plan2code-broken")); fs.rmSync(path.join(gone, "vanished"), { recursive: true }); fs.writeFileSync(path.join(root, canonical.MANIFEST_NAME), "{}"); assert.deepEqual(canonical.retiredSkillNames("global", ["plan2code-alpha"], { home }), ["plan2code-broken", "plan2code-linked", "plan2code-old", "plan2code-stray"]); assert.deepEqual(canonical.sweepBrokenLinks("global", { home }), ["plan2code-broken"]); const removed = canonical.removeRetiredCanonical("global", ["plan2code-linked", "plan2code-old", "plan2code-stray"], { home }); assert.deepEqual(removed, { removed: ["plan2code-linked", "plan2code-old", "plan2code-stray"], warnings: [] }); assert.deepEqual(fs.readdirSync(root).sort(), [canonical.MANIFEST_NAME, "other-skill", "plan2code-alpha"]); assert.equal(fs.readFileSync(path.join(target, "outside", "keep.md"), "utf8"), "must survive", "unlinking a junction left its target"); }); test("installCanonicalSkills (global): one canonical copy, retired names removed alone, one skills add from the store, timing events", async (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); writeBuilt(root, { "plan2code-alpha": { "SKILL.md": "old" }, "plan2code-old": { "SKILL.md": "retired" } }); // The current pin links from the store; the legacy pin (Node below 22.20) links from the build, so pin it for any Node. const fake = fakeSkillsCli(t, { version: skillsCliRunner.SKILLS_CLI_PINS.current }); const timingFile = path.join(scratch(t), "timing.jsonl"); process.env.PLAN2CODE_BENCH_JSON = timingFile; let run; try { run = await quietly(() => installer.installCanonicalSkills("global", { builtDir: writeBuilt(scratch(t), BUILT), expectedNames: NAMES, cli: fake.cli, home, version: "9.9.9" })); } finally { delete process.env.PLAN2CODE_BENCH_JSON; } assert.equal(run.value.ok, true, run.out || String(run.value.error)); assert.deepEqual(fake.calls(), [ ["remove", "plan2code-old", "-g", "-y"], ["add", root, "-g", "-s", ...NAMES, "-y"], ], "no --version, no broad remove of retained skills, one add with the store as its source"); assert.ok(!fs.existsSync(path.join(root, "plan2code-old")), "the retired folder goes once the CLI was asked"); assert.equal(fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"), "alpha"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "9.9.9" }).complete, true); const events = readTimingEvents(timingFile).map((e) => e.event); assert.deepEqual(events, ["canonical-staged", "canonical-committed", "retired-removed", "links-refreshed"], "retired skills go only after the swap worked"); // A second run with nothing retired asks the CLI for the add alone. const again = fakeSkillsCli(t, { version: skillsCliRunner.SKILLS_CLI_PINS.current }); const second = await quietly(() => installer.installCanonicalSkills("global", { builtDir: writeBuilt(scratch(t), BUILT), expectedNames: NAMES, cli: again.cli, home })); assert.equal(second.value.ok, true, second.out || String(second.value.error)); assert.deepEqual(again.calls(), [["add", root, "-g", "-s", ...NAMES, "-y"]]); }); test("installCanonicalSkills (project): the store and the one add are under the project, without -g", async (t) => { const home = scratch(t); const project = scratch(t, "p2c-project-"); const fake = fakeSkillsCli(t, { version: skillsCliRunner.SKILLS_CLI_PINS.current }); const run = await quietly(() => installer.installCanonicalSkills("project", { builtDir: writeBuilt(scratch(t), BUILT), expectedNames: NAMES, cli: fake.cli, cwd: project, home })); assert.equal(run.value.ok, true, run.out || String(run.value.error)); const root = path.join(project, ".agents", "skills"); assert.deepEqual(fake.calls(), [["add", root, "-s", ...NAMES, "-y"]]); assert.equal(canonical.validateCanonicalManifest("project", NAMES, { cwd: project, home }).complete, true); assert.ok(!fs.existsSync(path.join(home, ".agents")), "nothing written in the home folder"); }); test("installCanonicalSkills: a failed add leaves the store complete; a failed stage asks the CLI nothing", async (t) => { const home = scratch(t); const fake = fakeSkillsCli(t, { exitCodes: { add: 1 } }); const built = writeBuilt(scratch(t), BUILT); const run = await quietly(() => installer.installCanonicalSkills("global", { builtDir: built, expectedNames: NAMES, cli: fake.cli, home })); assert.equal(run.value.ok, false); assert.equal(run.value.result.ok, false); assert.match(run.value.result.output, /fake skills add/); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home }).complete, true); const none = fakeSkillsCli(t); const missing = await quietly(() => installer.installCanonicalSkills("global", { builtDir: built, expectedNames: [...NAMES, "plan2code-missing"], cli: none.cli, home })); assert.equal(missing.value.ok, false); assert.equal(missing.value.error.code, "missing-skill"); assert.deepEqual(none.calls(), []); }); test("installCanonicalSkills: a store an earlier run left mid-swap is finished before the new stage", async (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const built = writeBuilt(scratch(t), BUILT); const stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home }); assert.throws(() => canonical.commitCanonicalSkills(stage, { hooks: { afterSwap: () => { throw new Error("killed"); } } })); // The throw above rolled back; leave a journal and stage behind the way a killed run would. const leftover = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home }); assert.ok(fs.existsSync(leftover.stageDir)); const fake = fakeSkillsCli(t); const run = await quietly(() => installer.installCanonicalSkills("global", { builtDir: built, expectedNames: NAMES, cli: fake.cli, home })); assert.equal(run.value.ok, true, run.out || String(run.value.error)); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), ["skills"], "the earlier stage and journal were cleared"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home }).complete, true); assert.ok(fs.existsSync(root)); }); test("update: Already on also needs the canonical skills manifest complete for this version", async () => { fs.mkdirSync(path.dirname(RECORD), { recursive: true }); fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] })); writeLauncherVersion(VERSION); const asked = []; const stale = fakeSteps(); const { code, out } = await runUpdate(stale.steps, { skillsCurrent: (version) => (asked.push(version), false) }); assert.equal(code, 0, out); assert.deepEqual(asked, [VERSION]); assert.doesNotMatch(out, /Already on/); assert.match(out, /installed skills do not match/); assert.deepEqual(stale.ran(), ["skills"]); // The real check: this test's home has no manifest, so the skills are not in place. assert.equal(installer.canonicalSkillsCurrent(VERSION), false); }); test("skills CLI pins: a prerelease of the Node floor is below it, as semver orders them", () => { assert.equal(skillsCliRunner.selectSkillsCliVersion("22.20.0-rc.1"), "1.5.18"); assert.equal(skillsCliRunner.selectSkillsCliVersion("v22.20.0-nightly20261201abc"), "1.5.18"); assert.equal(skillsCliRunner.selectSkillsCliVersion("22.20.1-rc.1"), "1.7.6"); assert.equal(skillsCliRunner.selectSkillsCliVersion("23.0.0-pre"), "1.7.6"); }); test("retired skills: a user's own skill whose name only begins with the letters plan2code is never ours", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); writeBuilt(root, { plan2code: { "SKILL.md": "the dashboard" }, plan2codetips: { "SKILL.md": "a user's own" }, "plan2code-old": { "SKILL.md": "retired" } }); const gone = writeBuilt(scratch(t), { vanished: { "SKILL.md": "x" } }); linkDir(path.join(gone, "vanished"), path.join(root, "plan2codebroken")); fs.rmSync(path.join(gone, "vanished"), { recursive: true }); assert.deepEqual(canonical.retiredSkillNames("global", ["plan2code"], { home }), ["plan2code-old"]); assert.deepEqual(canonical.sweepBrokenLinks("global", { home }), []); assert.deepEqual(canonical.removeRetiredCanonical("global", ["plan2codetips"], { home }).removed, []); assert.ok(fs.existsSync(path.join(root, "plan2codetips", "SKILL.md"))); }); test("canonical commit: a store that does not match the stage after the swap is rolled back, old manifest and all", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const v1 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v1 alpha" }, "plan2code-beta": { "SKILL.md": "v1 beta" } }); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: v1, expectedNames: NAMES, home, version: "1.0.0" })); const oldManifest = fs.readFileSync(path.join(root, canonical.MANIFEST_NAME), "utf8"); const stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: writeBuilt(scratch(t), BUILT), expectedNames: NAMES, home, version: "2.0.0" }); // Something writes into a freshly swapped skill before the swap finishes. const hooks = { afterSwap: (name) => name === "plan2code-alpha" && fs.writeFileSync(path.join(root, name, "SKILL.md"), "tampered") }; assert.throws(() => canonical.commitCanonicalSkills(stage, { hooks }), (err) => err.code === "commit-failed" && err.cause.code === "commit-mismatch"); assert.equal(fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"), "v1 alpha"); assert.equal(fs.readFileSync(path.join(root, "plan2code-beta", "SKILL.md"), "utf8"), "v1 beta"); assert.equal(fs.readFileSync(path.join(root, canonical.MANIFEST_NAME), "utf8"), oldManifest); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "1.0.0" }).complete, true); }); test("installCanonicalSkills: a stage folder a run killed mid-copy left, with no journal yet, is cleared", async (t) => { const home = scratch(t); const built = writeBuilt(scratch(t), BUILT); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home })); // A pid no process has: a low pid like 123 can be a live process on a macOS runner, and its stage would count as a running install's. const orphan = path.join(home, ".agents", ".skills-stage-999999999-456"); writeBuilt(orphan, { "plan2code-alpha": { "SKILL.md": "half a copy" } }); assert.ok(!fs.existsSync(canonical.journalPath(path.join(home, ".agents", "skills"))), "no journal: the kill came before the first record"); assert.equal(canonical.hasCanonicalResidue("global", undefined, home), true); const fake = fakeSkillsCli(t); const run = await quietly(() => installer.installCanonicalSkills("global", { builtDir: built, expectedNames: NAMES, cli: fake.cli, home })); assert.equal(run.value.ok, true, run.out || String(run.value.error)); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), ["skills"]); assert.equal(canonical.hasCanonicalResidue("global", undefined, home), false); }); test("canonical journal: a rename Windows briefly refuses (EPERM, EBUSY) is tried again", { skip: process.platform !== "win32" && "the retry is for Windows only" }, (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const realRename = fs.renameSync; let refused = 0; fs.renameSync = (from, to) => { if (String(to).endsWith(canonical.JOURNAL_NAME) && refused < 2) { refused++; throw Object.assign(new Error(refused === 1 ? "EPERM: operation not permitted" : "EBUSY: resource busy"), { code: refused === 1 ? "EPERM" : "EBUSY" }); } return realRename(from, to); }; try { canonical.journalRecord(root, { op: "staged", scope: "global", operationId: "1-2" }); } finally { fs.renameSync = realRename; } assert.equal(refused, 2); assert.equal(canonical.readJournal(root).records[0].op, "staged"); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")), [canonical.JOURNAL_NAME], "no temp file left"); }); // --------------------------------------------------------------------------------------------- // Console staging, orchestration and capability truth (src/installer/console-stage.js) // --------------------------------------------------------------------------------------------- const consoleStage = require(path.join(ROOT, "src", "installer", "console-stage.js")); const CV = "4.5.6"; /** A built console tree for version `CV` (or `version`), with a nested file. */ function writeBuiltConsole(dir, version = CV) { const files = { "console.mjs": "export {};\n", "version.txt": `${version}\n`, "version.json": JSON.stringify({ version }), "public/core.js": "core" }; for (const [rel, text] of Object.entries(files)) { const file = path.join(dir, ...rel.split("/")); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); } return dir; } /** Every file under `dir` with its bytes, for byte-identical checks. */ function snapshotTree(dir) { const out = {}; const walk = (current, rel) => { for (const name of fs.readdirSync(current).sort()) { const full = path.join(current, name); const relPath = rel ? `${rel}/${name}` : name; if (fs.lstatSync(full).isDirectory()) walk(full, relPath); else out[relPath] = fs.readFileSync(full).toString("base64"); } }; if (fs.existsSync(dir)) walk(dir, ""); return out; } function lockError(code = "EBUSY") { return Object.assign(new Error(`${code}: resource busy or locked`), { code }); } function plainError(code = "EINVAL") { return Object.assign(new Error(`${code}: invalid argument`), { code }); } /** A console home holding entries the install must never touch, and a built console for `CV`. */ function consoleFixture(t) { const home = scratch(t, "p2c-console-home-"); const source = writeBuiltConsole(scratch(t, "p2c-console-built-")); const kept = { "looks.json": '{"theme":"dark"}', "workspaces.json": "{}", "sessions/s1/state.json": '{"a":1}', "runtime/x.json": "{}", "notes.txt": "not ours" }; for (const [rel, body] of Object.entries(kept)) { const file = path.join(home, ...rel.split("/")); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, body); } return { home, source, kept, dest: path.join(home, CV) }; } const escapeRe = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); test("console stage: the manifest lists every file with its hash and size, and .complete is written last", (t) => { const { home, source } = consoleFixture(t); const written = []; const write = fs.writeFileSync; fs.writeFileSync = (file, ...rest) => (written.push(String(file)), write(file, ...rest)); let stage; try { stage = consoleStage.stageConsole({ version: CV, source, home }); } finally { fs.writeFileSync = write; } assert.match(path.basename(stage.stageDir), new RegExp(`^${escapeRe(CV)}\\.install-${process.pid}-\\d+$`)); assert.equal(path.dirname(stage.stageDir), home, "the stage sits beside the version folder"); assert.equal(path.basename(written.at(-1)), consoleStage.COMPLETE_NAME, "the marker is the last write"); assert.equal(path.basename(written.at(-2)), consoleStage.MANIFEST_NAME, "the manifest goes in just before it"); const manifest = JSON.parse(fs.readFileSync(path.join(stage.stageDir, consoleStage.MANIFEST_NAME), "utf8")); assert.deepEqual(manifest.files.map((f) => f.path), ["console.mjs", "public/core.js", "version.json", "version.txt"], "sorted relative paths"); const core = manifest.files.find((f) => f.path === "public/core.js"); assert.equal(core.bytes, 4); assert.equal(core.sha256, crypto.createHash("sha256").update("core").digest("hex")); assert.equal(JSON.parse(fs.readFileSync(path.join(stage.stageDir, consoleStage.COMPLETE_NAME), "utf8")).version, CV); assert.equal(fs.existsSync(path.join(home, CV)), false, "nothing is in place until the commit"); }); test("console stage: a missing build is refused and changes nothing in the console home", (t) => { const { home } = consoleFixture(t); const before = snapshotTree(home); const entries = fs.readdirSync(home).sort(); const empty = scratch(t, "p2c-console-empty-"); assert.throws(() => consoleStage.stageConsole({ version: CV, source: empty, home }), (err) => err.code === "not-built"); assert.deepEqual(snapshotTree(home), before, "every entry is byte-identical"); assert.deepEqual(fs.readdirSync(home).sort(), entries, "no stage is left behind"); }); test("console commit: a first install is renamed in, console-dir is written through a rename, and other entries stay byte-identical", (t) => { const { home, source, dest } = consoleFixture(t); const before = snapshotTree(home); const renames = []; const ops = { rename: (a, b) => (renames.push([a, b]), fs.renameSync(a, b)) }; const committed = consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home }), { ops }); assert.equal(committed.committed, true); assert.equal(committed.fallbackUsed, false); assert.equal(committed.backupDir, null, "no folder was there to back up"); assert.deepEqual(renames.map(([, to]) => to), [dest], "one rename puts the stage in place"); assert.equal(fs.readFileSync(path.join(home, "console-dir"), "utf8").trim(), dest); assert.deepEqual(fs.readdirSync(home).filter((n) => n.includes(".tmp") || /\.(install|backup)-/.test(n)), [], "no temp, stage or backup left"); const after = snapshotTree(home); for (const rel of Object.keys(before)) assert.equal(after[rel], before[rel], `${rel} is untouched`); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), true); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).complete, true); }); test("console commit: an existing folder is backed up, replaced by the stage, and the backup removed once it validates", (t) => { const { home, source, dest } = consoleFixture(t); consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home })); fs.writeFileSync(path.join(dest, "stale.txt"), "left by an earlier copy"); const renames = []; const ops = { rename: (a, b) => (renames.push([a, b]), fs.renameSync(a, b)) }; const committed = consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home }), { ops }); assert.equal(renames[0][0], dest, "the old folder goes aside first"); assert.match(path.basename(renames[0][1]), new RegExp(`^${escapeRe(CV)}\\.backup-${process.pid}-\\d+$`)); assert.equal(renames[1][1], dest, "then the stage comes in"); assert.equal(committed.backupDir, renames[0][1]); assert.equal(fs.existsSync(committed.backupDir), false, "the backup is removed after validation"); assert.equal(fs.existsSync(path.join(dest, "stale.txt")), false, "replaced, not merged"); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).complete, true); }); test("console commit: a lock that refuses the renames falls back to copying in place, verifies it and says so", (t) => { const { home, source, dest } = consoleFixture(t); consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home })); fs.writeFileSync(path.join(source, "public", "core.js"), "core, newer"); const copies = []; const ops = { rename: () => { throw lockError("EBUSY"); }, // The running server holds the folder: its removal fails too, so the copy overwrites in place. rm: (target, options) => { if (target === dest) throw lockError("EPERM"); return fs.rmSync(target, options); }, cp: (from, to, options) => (copies.push(to), fs.cpSync(from, to, options)), }; const committed = consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home }), { ops }); assert.equal(committed.fallbackUsed, true); assert.ok(committed.warnings.some((w) => /in use \(EBUSY\).*copied over in place/.test(w)), committed.warnings.join("\n")); assert.deepEqual(copies.map((to) => path.basename(to)), [CV, consoleStage.COMPLETE_NAME], "everything but the marker, then the marker"); assert.equal(fs.readFileSync(path.join(dest, "public", "core.js"), "utf8"), "core, newer"); assert.equal(consoleStage.verifyConsoleDir(dest, CV).complete, true); assert.deepEqual(fs.readdirSync(home).filter((n) => /\.(install|backup)-/.test(n)), [], "the stage is cleared after the copy"); assert.equal(fs.readFileSync(path.join(home, "console-dir"), "utf8").trim(), dest); }); test("console commit: a failure that is not a lock is thrown, not hidden behind the fallback", (t) => { const { home, source } = consoleFixture(t); const stage = consoleStage.stageConsole({ version: CV, source, home }); let copied = false; const ops = { rename: () => { throw plainError(); }, cp: () => (copied = true), }; assert.throws(() => consoleStage.commitConsole(stage, { ops }), /EINVAL/); assert.equal(copied, false); }); test("console recovery: an interrupted stage and a half-copied folder are detected, and a retry replaces them", (t) => { const { home, source, dest } = consoleFixture(t); // An earlier run died twice: once mid-stage (no .complete), once mid-copy into the folder. const dead = consoleStage.stageConsole({ version: CV, source, home }); fs.rmSync(path.join(dead.stageDir, consoleStage.COMPLETE_NAME)); const leftover = path.join(home, `${CV}.install-999999-1`); fs.renameSync(dead.stageDir, leftover); fs.cpSync(source, dest, { recursive: true }); fs.writeFileSync(path.join(dest, consoleStage.MANIFEST_NAME), JSON.stringify({ version: CV, files: [{ path: "console.mjs", sha256: "0".repeat(64), bytes: 1 }] })); const state = consoleStage.consoleInstallState({ version: CV, home }); assert.equal(state.complete, false); assert.equal(state.state, "incomplete"); assert.deepEqual(state.staging.map((s) => s.name), [path.basename(leftover)]); assert.ok(state.problems.some((p) => /console\.mjs: changed on disk/.test(p)), state.problems.join("\n")); assert.ok(state.problems.some((p) => /no \.complete/.test(p))); assert.ok(state.problems.some((p) => /interrupted copy/.test(p))); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), false); const committed = consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home })); assert.deepEqual(committed.recovered.removed, [path.basename(leftover)]); assert.equal(fs.existsSync(leftover), false); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).complete, true); }); test("console recovery: with no complete folder a leftover backup is put back; with one, the backup is cleared", (t) => { const { home, source, dest } = consoleFixture(t); consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home })); const backup = path.join(home, `${CV}.backup-999999-1`); fs.renameSync(dest, backup); assert.deepEqual(consoleStage.consoleInstallState({ version: CV, home }).backups.map((b) => b.name), [path.basename(backup)]); // The new stage cannot go in (not a lock): the old console must still be usable afterwards. const stage = consoleStage.stageConsole({ version: CV, source, home }); const ops = { rename: (a, b) => { if (a === stage.stageDir) throw plainError(); fs.renameSync(a, b); }, }; assert.throws(() => consoleStage.commitConsole(stage, { ops }), /EINVAL/); assert.equal(fs.existsSync(backup), false, "the backup was put back"); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), true, "the restored console is usable"); const second = path.join(home, `${CV}.backup-999998-2`); fs.cpSync(dest, second, { recursive: true }); const committed = consoleStage.commitConsole(consoleStage.stageConsole({ version: CV, source, home })); assert.ok(committed.recovered.removed.includes(path.basename(second)), "a backup beside a complete folder is cleaned up"); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).complete, true); }); test("console state: a folder from before the markers counts only with console.mjs and a matching version file", (t) => { const home = scratch(t, "p2c-console-premarker-"); const dest = writeBuiltConsole(path.join(home, CV)); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), true, "version.txt matches"); fs.writeFileSync(path.join(dest, "version.txt"), "1.0.0\n"); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), true, "version.json still matches"); fs.writeFileSync(path.join(dest, "version.json"), JSON.stringify({ version: "1.0.0" })); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), false, "no matching version evidence"); writeBuiltConsole(dest); fs.rmSync(path.join(dest, "console.mjs")); assert.equal(consoleStage.isCompleteConsoleInstall({ version: CV, home }), false, "no console.mjs"); writeBuiltConsole(dest); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).complete, false, "usable, but console-dir does not name it yet"); fs.writeFileSync(path.join(home, "console-dir"), `${dest}\n`); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).state, "pre-marker"); assert.equal(consoleStage.consoleInstallState({ version: CV, home }).complete, true); }); test("console home: PLAN2CODE_CONSOLE_HOME wins, and install.js resolves the same folder", () => { const saved = process.env.PLAN2CODE_CONSOLE_HOME; try { process.env.PLAN2CODE_CONSOLE_HOME = path.join(HOME, "elsewhere"); assert.equal(consoleStage.consoleHomeDir(), path.join(HOME, "elsewhere")); assert.equal(installer.consoleHomeDir(), consoleStage.consoleHomeDir()); delete process.env.PLAN2CODE_CONSOLE_HOME; assert.equal(installer.consoleHomeDir(), path.join(HOME, ".plan2code", "console")); } finally { if (saved === undefined) delete process.env.PLAN2CODE_CONSOLE_HOME; else process.env.PLAN2CODE_CONSOLE_HOME = saved; } }); function ensureBuiltConsole() { const shared = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs"); if (!fs.existsSync(shared)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" }); } test("shared console install: a locked folder is copied in place and the warning is printed even when quiet", async () => { ensureBuiltConsole(); const home = installer.consoleHomeDir(); fs.rmSync(home, { recursive: true, force: true }); assert.equal(installer.installSharedConsole({ quiet: true, sweep: false }), true); const run = await quietly(() => installer.installSharedConsole({ quiet: true, sweep: false, ops: { rename: () => { throw lockError("EPERM"); }, }, }) ); assert.equal(run.value, true); assert.ok(run.out.split("\n").some((l) => /^(⚠|!) /.test(l.trim()) && /copied over in place/.test(l)), run.out); assert.equal(installer.sharedConsoleCurrent(VERSION), true); }); /** Point the folders install()'s legacy sweep reads outside HOME at the temp HOME while `fn` runs. */ async function withTempAppData(fn) { const saved = { APPDATA: process.env.APPDATA, LOCALAPPDATA: process.env.LOCALAPPDATA }; process.env.APPDATA = path.join(HOME, "AppData", "Roaming"); process.env.LOCALAPPDATA = path.join(HOME, "AppData", "Local"); try { return await fn(); } finally { for (const [key, value] of Object.entries(saved)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } } } /** A canonical step that records how the console stood when it began, then fails like a swap. */ function failingCanonical(seen = []) { return async (scope) => { seen.push({ scope, consoleComplete: installer.sharedConsoleCurrent(VERSION) }); return { ok: false, error: new Error("swap failed"), retired: { removed: [] } }; }; } test("install: the console is staged and committed before canonical replacement, and a failed replacement keeps the old console", async () => { const home = installer.consoleHomeDir(); fs.rmSync(home, { recursive: true, force: true }); writeBuiltConsole(path.join(home, "2.9.9"), "2.9.9"); const seen = []; const outcome = {}; const run = await withTempAppData(() => quietly(() => installer.install({ unattended: true, outcome, canonical: failingCanonical(seen) }))); assert.equal(seen.length, 1, run.out); assert.equal(seen[0].consoleComplete, true, "the console was committed before canonical replacement began"); assert.equal(outcome.skills, false); assert.ok(fs.existsSync(path.join(home, "2.9.9", "console.mjs")), "old consoles are swept only after the skills step works"); }); test("install: a console that cannot be committed leaves the canonical skills untouched", async () => { const home = installer.consoleHomeDir(); fs.rmSync(home, { recursive: true, force: true }); let canonicalRan = false; const errors = []; const error = console.error; console.error = (...a) => errors.push(a.join(" ")); const outcome = {}; let run; try { const consoleOps = { rename: () => { throw plainError(); }, }; const canonical = async () => ((canonicalRan = true), { ok: true }); run = await withTempAppData(() => quietly(() => installer.install({ unattended: true, outcome, consoleOps, canonical }))); } finally { console.error = error; } assert.equal(run.value, 1); assert.equal(canonicalRan, false, "no canonical replacement after a failed console commit"); assert.equal(outcome.skills, false); assert.ok(errors.join("\n").includes("Could not install the shared console"), errors.join("\n")); }); test("update: compact progress lines go past the captured output, in step order", async () => { writeRecord(["skills", "launcher", "app"]); const progress = []; const steps = { ...fakeSteps().steps, skills: (options) => installer.install({ ...options, canonical: failingCanonical() }), }; const { out } = await withTempAppData(() => runUpdate(steps, { progress: (line) => progress.push(line) })); assert.deepEqual(progress, ["Preparing skills…", "Preparing console…", "Replacing skills…", "Installing plan2code command…", "Installing desktop app…"]); for (const line of progress) assert.ok(!out.includes(line), `${line} is not part of the captured console.log output`); }); test("update: the default progress writer prints one dim line to stdout, and nothing is written outside an update", async () => { writeRecord(["launcher"]); const written = []; const write = process.stdout.write; process.stdout.write = (chunk) => (written.push(String(chunk)), true); try { await quietly(() => installer.update({ steps: fakeSteps().steps, cleanShims: () => {}, skillsCurrent: () => true, consoleCurrent: () => true })); } finally { process.stdout.write = write; } assert.ok(written.some((c) => c.replace(/\x1b\[[0-9;]*m/g, "") === " Installing plan2code command…\n"), written.join("")); ensureBuiltConsole(); const after = []; process.stdout.write = (chunk) => (after.push(String(chunk)), true); try { installer.installSharedConsole({ quiet: true, sweep: false }); } finally { process.stdout.write = write; } assert.deepEqual(after, [], "an install outside an update writes no progress lines"); }); test("update: Already on also needs the shared console complete, and an interrupted install is completed without --force", async () => { ensureBuiltConsole(); fs.mkdirSync(path.dirname(RECORD), { recursive: true }); fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] })); writeLauncherVersion(VERSION); const home = installer.consoleHomeDir(); fs.rmSync(home, { recursive: true, force: true }); assert.equal(installer.installSharedConsole({ quiet: true, sweep: false }), true); assert.match((await runUpdate(fakeSteps().steps, { consoleCurrent: installer.sharedConsoleCurrent })).out, /Already on/); fs.rmSync(path.join(home, VERSION, consoleStage.COMPLETE_NAME)); const consoleOnly = fakeSteps(); const first = await runUpdate(consoleOnly.steps, { consoleCurrent: installer.sharedConsoleCurrent }); assert.doesNotMatch(first.out, /Already on/); assert.match(first.out, new RegExp(`${escapeRe(VERSION)} is installed, but the shared console is not complete, so it is installed again`)); assert.deepEqual(consoleOnly.ran(), ["skills"]); fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] })); const both = fakeSteps(); const { code, out } = await runUpdate(both.steps, { consoleCurrent: installer.sharedConsoleCurrent, skillsCurrent: () => false }); assert.equal(code, 0, out); assert.match(out, /is installed, but the installed skills do not match it on disk and the shared console is not complete, so it is installed again/); assert.equal(out.split("\n").filter((l) => /so it is installed again/.test(l)).length, 1, "one line"); }); test("dev tools: metrics and bot are maintainable only from a checkout that has them", (t) => { const dir = scratch(t, "p2c-devtools-"); const none = installer.devToolCapabilities({ dir }); assert.deepEqual([none.metrics.present, none.metrics.maintainable, none.bot.present, none.bot.maintainable], [false, false, false, false]); assert.match(none.metrics.reason, /git checkout/); fs.mkdirSync(path.join(dir, "plan2code-metrics")); fs.mkdirSync(path.join(dir, "plan2code-bot")); const npx = installer.devToolCapabilities({ dir }); assert.deepEqual([npx.metrics.present, npx.metrics.maintainable], [true, false]); assert.match(npx.bot.reason, /checkout only/); fs.mkdirSync(path.join(dir, ".git")); const checkout = installer.devToolCapabilities({ dir }); assert.deepEqual(checkout.metrics, { present: true, maintainable: true, reason: null }); assert.deepEqual(checkout.bot, { present: true, maintainable: true, reason: null }); }); const stripAnsi = (lines) => lines.map((l) => l.replace(/\x1b\[[0-9;]*m/g, "")); test("Advanced menu: in an npx layout metrics and bot are left out with a plain reason; Everything installs only what can be kept up to date", () => { const missing = { present: false, maintainable: false, reason: "not in this copy" }; const menu = installer.advancedMenu({ metrics: missing, bot: { present: true, maintainable: false, reason: "checkout only" } }); assert.deepEqual(menu.letters, ["L", "S", "D", "E", "Q"]); assert.ok(!stripAnsi(menu.lines).some((l) => /METRICS|BOT /.test(l)), stripAnsi(menu.lines).join("\n")); assert.deepEqual(menu.notes, ["Metrics CLI: not in this copy", "Bot CLI: checkout only"]); assert.deepEqual(menu.everything, ["statusline", "skills"]); assert.ok(stripAnsi(menu.lines).some((l) => l.includes("the dev tools this copy can keep up to date"))); }); test("Advanced menu: from a checkout it is exactly the full menu, and Everything includes bot and metrics", () => { const on = { present: true, maintainable: true, reason: null }; const menu = installer.advancedMenu({ metrics: on, bot: on }); assert.deepEqual(stripAnsi(menu.lines), [ "Advanced options", "", "L. LOCAL Install skills into the current project only", "M. METRICS Install plan2code-metrics CLI only", "S. STATUS Install Claude Code status line", "B. BOT Install plan2code-bot CLI only", "D. COMMAND Install the plan2code command only", "E. EVERYTHING Install Plan2Code + all dev tools", "Q. BACK Return to main menu", ]); assert.deepEqual(menu.letters, ["L", "M", "S", "B", "D", "E", "Q"]); assert.deepEqual(menu.notes, []); assert.deepEqual(menu.everything, ["bot", "metrics", "statusline", "skills"]); // This repository is a checkout with both trees, so its real menu is the full one. assert.deepEqual(installer.advancedMenu().letters, menu.letters); }); test("update: in an npx layout metrics and bot are kept, never run", async () => { writeRecord(["metrics", "bot"]); const fake = fakeSteps(); const off = { present: true, maintainable: false, reason: "checkout only" }; const { code, out } = await runUpdate(fake.steps, { devTools: { metrics: off, bot: off } }); assert.equal(code, 0, out); assert.deepEqual(fake.ran(), []); assert.match(out, /Metrics: kept \(update it from a git checkout/); assert.match(out, /Bot: kept \(update it from a git checkout/); }); test("console stage: two stages started in the same millisecond get their own folders", (t) => { const { home, source } = consoleFixture(t); const now = Date.now; Date.now = () => 1700000000000; let first; let second; try { first = consoleStage.stageConsole({ version: CV, source, home }); second = consoleStage.stageConsole({ version: CV, source, home }); } finally { Date.now = now; } assert.notEqual(first.stageDir, second.stageDir); assert.match(path.basename(second.stageDir), new RegExp(`^${escapeRe(CV)}\\.install-${process.pid}-1700000000001$`)); assert.equal(consoleStage.verifyConsoleDir(second.stageDir, CV).complete, true); }); test("console residue: stages and backups of other versions are swept with the old consoles; this version's stay for recovery", (t) => { const { home } = consoleFixture(t); const leftovers = ["9.9.9.install-999999-1", "9.9.9.backup-999999-2", `${CV}.backup-999999-3`]; for (const name of leftovers) writeBuiltConsole(path.join(home, name)); const swept = consoleStage.sweepConsoleResidue({ home, keepVersion: CV }); assert.deepEqual(swept.removed.sort(), ["9.9.9.backup-999999-2", "9.9.9.install-999999-1"]); assert.ok(fs.existsSync(path.join(home, `${CV}.backup-999999-3`)), "the current version's backup is left for commitConsole() to recover"); assert.ok(fs.existsSync(path.join(home, "looks.json")), "other entries stay"); // A stage another running install is still building is never taken from under it. const live = path.join(home, `9.9.8.install-${process.ppid}-4`); writeBuiltConsole(live); assert.deepEqual(consoleStage.sweepConsoleResidue({ home, keepVersion: CV }).removed, []); assert.ok(fs.existsSync(live)); }); test("sweepOldConsoles: an interrupted update's stage or backup for another version goes with the old version folders", () => { ensureBuiltConsole(); const home = installer.consoleHomeDir(); fs.rmSync(home, { recursive: true, force: true }); assert.equal(installer.installSharedConsole({ quiet: true, sweep: false }), true); writeBuiltConsole(path.join(home, "2.9.9"), "2.9.9"); writeBuiltConsole(path.join(home, "9.9.9.backup-999999-1"), "9.9.9"); writeBuiltConsole(path.join(home, "9.9.9.install-999999-2"), "9.9.9"); installer.sweepOldConsoles({ quiet: true }); assert.deepEqual(fs.readdirSync(home).sort(), ["console-dir", VERSION].sort()); }); test("install: a console that cannot be staged is timed as a failed console-staged, never as a commit", async (t) => { const timingFile = path.join(HOME, "console-stage-timing.jsonl"); fs.rmSync(timingFile, { force: true }); // A file where the console home should be: the stage cannot even make its folder. const blocked = path.join(HOME, "console-home-is-a-file"); fs.writeFileSync(blocked, "not a folder"); const saved = process.env.PLAN2CODE_CONSOLE_HOME; process.env.PLAN2CODE_BENCH_JSON = timingFile; process.env.PLAN2CODE_CONSOLE_HOME = blocked; t.after(() => { delete process.env.PLAN2CODE_BENCH_JSON; if (saved === undefined) delete process.env.PLAN2CODE_CONSOLE_HOME; else process.env.PLAN2CODE_CONSOLE_HOME = saved; }); let canonicalRan = false; const error = console.error; console.error = () => {}; let run; try { run = await withTempAppData(() => quietly(() => installer.install({ unattended: true, canonical: async () => ((canonicalRan = true), { ok: true }) }))); } finally { console.error = error; } assert.equal(run.value, 1); assert.equal(canonicalRan, false); const consoleEvents = readTimingEvents(timingFile).filter((e) => e.event.startsWith("console-")); assert.deepEqual(consoleEvents.map((e) => [e.event, e.result]), [["console-staged", "failed"]]); }); test("the legacy skills CLI pin links from the built skills/ folder, since 1.5.x skips every agent when the source is the canonical store", () => { const pins = require(path.join(ROOT, "src", "installer", "skills-cli.js")).SKILLS_CLI_PINS; const home = path.join(os.tmpdir(), "p2c-link-source-home"); const builtDir = path.join(os.tmpdir(), "p2c-link-source-built"); const legacy = installer.agentLinkSource("global", { cli: { pin: pins.legacy }, home, builtDir }); const current = installer.agentLinkSource("global", { cli: { pin: pins.current }, home, builtDir }); assert.equal(legacy, builtDir, "skills@1.5.x gets the built folder, so Claude Code and Devin are linked"); assert.equal(path.resolve(current), path.resolve(home, ".agents", "skills"), "the current pin links straight from the canonical store"); }); test("with no cached skills CLI, an unreachable one stops the install before anything is replaced; a cached one is never checked", () => { const node = process.execPath; const quiet = (fn) => { const log = console.log; console.log = () => {}; try { return fn(); } finally { console.log = log; } }; assert.equal(installer.skillsCliReachable({ kind: "cached", executable: node, argsPrefix: ["-e", "process.exit(9)"], pin: "x" }), true, "a cached copy needs no check"); // Script files, not -e: on Windows the npx form runs through cmd.exe, which would mangle inline code. const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cli-reach-")); try { const fails = path.join(dir, "fails.js"); const works = path.join(dir, "works.js"); fs.writeFileSync(fails, "process.exit(3);"); fs.writeFileSync(works, "console.log('1.7.6');"); assert.equal(quiet(() => installer.skillsCliReachable({ kind: "npx", command: node, argsPrefix: [fails], pin: "x" })), false, "an unreachable CLI stops the install"); assert.equal(quiet(() => installer.skillsCliReachable({ kind: "npx", command: node, argsPrefix: [works], pin: "x" })), true, "a reachable CLI lets it go on"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("canonical commit: a skill folder Windows will not let go of is written over in place, and a later failure still puts the old files back", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const v1 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v1 alpha", "old-only.md": "gone after" }, "plan2code-beta": { "SKILL.md": "v1 beta" } }); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: v1, expectedNames: NAMES, home, version: "1.0.0" })); const held = (from) => path.basename(from) === "plan2code-alpha" && path.dirname(from) === root; const busy = () => Object.assign(new Error("EBUSY: resource busy or locked"), { code: "EBUSY" }); // alpha is held open: its backup rename fails, so it is replaced in place; the swap completes. const built = writeBuilt(scratch(t), BUILT); const stage = canonical.stageCanonicalSkills({ scope: "global", builtDir: built, expectedNames: NAMES, home, version: "2.0.0" }); const rename = (from, to) => { if (held(from)) throw busy(); fs.renameSync(from, to); }; canonical.commitCanonicalSkills(stage, { rename, isLock: (err) => err.code === "EBUSY" }); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "2.0.0" }).complete, true, "the store is complete at the new version"); assert.ok(!fs.existsSync(path.join(root, "plan2code-alpha", "old-only.md")), "a file the new version lacks is removed"); // Held again, and a later rename fails: the in-place skill gets its old files copied back. const v3 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v3 alpha" }, "plan2code-beta": { "SKILL.md": "v3 beta" } }); const stage3 = canonical.stageCanonicalSkills({ scope: "global", builtDir: v3, expectedNames: NAMES, home, version: "3.0.0" }); const before = fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"); const failing = (from, to) => { if (held(from)) throw busy(); if (path.basename(from) === "plan2code-beta" && path.dirname(from) === root) throw new Error("disk full"); fs.renameSync(from, to); }; assert.throws(() => canonical.commitCanonicalSkills(stage3, { rename: failing, isLock: (err) => err.code === "EBUSY" }), (err) => err.code === "commit-failed"); assert.equal(fs.readFileSync(path.join(root, "plan2code-alpha", "SKILL.md"), "utf8"), before, "the held skill is back to its old files"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "2.0.0" }).complete, true, "the old store is whole again"); }); test("a failed swap whose roll back also failed names the skills left missing", () => { const lines = []; const log = console.log; console.log = (line) => lines.push(String(line)); try { installer.printCanonicalError(Object.assign(new Error("Could not swap the skills"), { rollbackErrors: ["plan2code-beta: EBUSY"] })); installer.printCanonicalError(new Error("Could not swap again")); } finally { console.log = log; } const text = lines.join("\n"); assert.match(text, /1 skill\(s\) could not be put back/); assert.match(text, /plan2code-beta: EBUSY/); assert.equal(lines.filter((line) => /could not be put back/.test(line)).length, 1, "a clean roll back adds nothing"); }); test("uninstall's metadata sweep removes the store manifest, the journal and stage or backup copies, and no skill or other folder", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); fs.mkdirSync(path.join(root, "someone-elses-skill"), { recursive: true }); fs.writeFileSync(path.join(root, canonical.MANIFEST_NAME), "{}"); fs.writeFileSync(path.join(home, ".agents", canonical.JOURNAL_NAME), "{}"); fs.mkdirSync(path.join(home, ".agents", ".skills-stage-123-456", "plan2code-alpha"), { recursive: true }); fs.mkdirSync(path.join(home, ".agents", ".skills-backup-op1", "plan2code-beta"), { recursive: true }); fs.mkdirSync(path.join(home, ".agents", "unrelated"), { recursive: true }); const result = canonical.removeCanonicalMetadata(root); assert.deepEqual(result.failed, []); assert.equal(result.removed.length, 4); assert.deepEqual(fs.readdirSync(path.join(home, ".agents")).sort(), ["skills", "unrelated"]); assert.deepEqual(fs.readdirSync(root), ["someone-elses-skill"]); assert.deepEqual(canonical.removeCanonicalMetadata(path.join(home, "nowhere", "skills")), { removed: [], failed: [] }, "nothing there is fine"); }); test("reconcile leaves a stage or backup another running install owns, and clears one whose install is gone", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const v1 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v1 alpha" }, "plan2code-beta": { "SKILL.md": "v1 beta" } }); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: v1, expectedNames: NAMES, home, version: "1.0.0" })); // The parent of this test process is alive and is not this process: it stands in for another install. const liveStage = path.join(home, ".agents", `.skills-stage-${process.ppid}-1`); const deadStage = path.join(home, ".agents", ".skills-stage-999999999-1"); fs.mkdirSync(path.join(liveStage, "plan2code-alpha"), { recursive: true }); fs.mkdirSync(path.join(deadStage, "plan2code-alpha"), { recursive: true }); canonical.reconcileCanonicalSkills("global", v1, NAMES, { home, version: "1.0.0" }); assert.ok(fs.existsSync(liveStage), "a running install's stage is left alone"); assert.ok(!fs.existsSync(deadStage), "a stage whose install is gone is cleared"); }); test("an OS file in a skill folder (.DS_Store, Thumbs.db, desktop.ini) does not make the store look changed", (t) => { const home = scratch(t); const root = path.join(home, ".agents", "skills"); const v1 = writeBuilt(scratch(t), { "plan2code-alpha": { "SKILL.md": "v1 alpha" }, "plan2code-beta": { "SKILL.md": "v1 beta" } }); canonical.commitCanonicalSkills(canonical.stageCanonicalSkills({ scope: "global", builtDir: v1, expectedNames: NAMES, home, version: "1.0.0" })); for (const junk of [".DS_Store", "Thumbs.db", "desktop.ini"]) fs.writeFileSync(path.join(root, "plan2code-alpha", junk), "os"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "1.0.0" }).complete, true); fs.writeFileSync(path.join(root, "plan2code-alpha", "notes.md"), "a real change"); assert.equal(canonical.validateCanonicalManifest("global", NAMES, { home, version: "1.0.0" }).complete, false, "any other file still counts"); }); test("a cached skills CLI with a pruned dependency is retried once through npx, sync and async; any other failure is not", async (t) => { const runner = require(path.join(ROOT, "src", "installer", "skills-cli.js")); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cli-fallback-")); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); const write = (name, body) => { const file = path.join(dir, name); fs.writeFileSync(file, body); return file; }; const broken = write("broken.js", "console.error(\"Error: Cannot find module 'yaml'\"); process.exit(1);"); const failing = write("failing.js", "console.error('no such skill'); process.exit(1);"); const works = write("works.js", "console.log('linked');"); const cached = (file) => ({ kind: "cached", executable: process.execPath, argsPrefix: [file], pin: "1.7.6" }); const fallback = { kind: "cached", executable: process.execPath, argsPrefix: [works], pin: "1.7.6" }; assert.deepEqual(runner.execSkillsCliSync(cached(broken), [], { fallback }), { ok: true, output: "linked" }); assert.deepEqual(await runner.execSkillsCliAsync(cached(broken), [], { fallback }), { ok: true, output: "linked" }); assert.equal(runner.execSkillsCliSync(cached(failing), [], { fallback }).ok, false, "an ordinary failure is reported, not retried"); assert.equal((await runner.execSkillsCliAsync(cached(failing), [], { fallback })).ok, false); }); test("latestTag ignores a branch whose name only ends like a release tag", () => { const sha = "a".repeat(40); const text = `${sha}\trefs/tags/v3.2.3\n${sha}\trefs/heads/x/refs/tags/v9.9.9\n${sha}\trefs/tags/install-v3.2.3\n`; assert.equal(latestTag(text), "3.2.3"); assert.equal(latestTag("refs/tags/v1.0.0"), "1.0.0", "a bare ref line still counts"); }); test("after an npx install: the built skills/ folder and day-old Plan2Code npx folders go; this run's, fresh ones, other packages' and a checkout stay", (t) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-npx-leftovers-")); t.after(() => fs.rmSync(root, { recursive: true, force: true })); const npx = path.join(root, "_npx"); const copy = (hash, spec) => { const folder = path.join(npx, hash); const pkgDir = path.join(folder, "node_modules", "@acme", "plan2code"); fs.mkdirSync(path.join(pkgDir, "skills", "plan2code"), { recursive: true }); fs.writeFileSync(path.join(folder, "package.json"), JSON.stringify({ _npx: { packages: [spec] } })); return { folder, pkgDir }; }; const current = copy("current", "git+https://github.com/jparkerweb/plan2code.git#install-v3.3.0"); const old = copy("old", "git+https://github.com/jparkerweb/plan2code.git#v3.2.1"); const bare = copy("bare", "git+https://github.com/jparkerweb/plan2code.git"); const fresh = copy("fresh", "git+https://github.com/jparkerweb/plan2code.git#v3.2.3"); const other = copy("other", "skills@1.7.6"); const now = Date.now(); const dayAgo = new Date(now - 2 * 24 * 60 * 60 * 1000); for (const dir of [old.folder, bare.folder, other.folder]) fs.utimesSync(dir, dayAgo, dayAgo); assert.equal(path.resolve(installer.npxCopyRoot(current.pkgDir)), path.resolve(current.folder)); const removed = installer.removeNpxLeftovers({ dir: current.pkgDir, now }).sort(); assert.deepEqual(removed, ["bare", "old"]); assert.ok(!fs.existsSync(path.join(current.pkgDir, "skills")), "this run's built skills/ is removed"); assert.ok(fs.existsSync(current.folder), "this run's own npx folder stays"); assert.ok(fs.existsSync(fresh.folder), "one used within a day stays"); assert.ok(fs.existsSync(other.folder), "another package's npx folder stays"); // A git checkout is never touched, and neither is a folder outside any _npx. fs.mkdirSync(path.join(current.pkgDir, ".git")); fs.mkdirSync(path.join(current.pkgDir, "skills")); assert.deepEqual(installer.removeNpxLeftovers({ dir: current.pkgDir, now }), []); assert.ok(fs.existsSync(path.join(current.pkgDir, "skills"))); assert.equal(installer.npxCopyRoot(path.join(root, "plain", "folder")), null); }); test("an npx spec that names the fetched commit pins it; a branch, a tag or another commit does not", (t) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-npx-pin-")); t.after(() => fs.rmSync(root, { recursive: true, force: true })); const sha = "0123456789abcdef0123456789abcdef01234567"; const copy = (spec) => { const folder = fs.mkdtempSync(path.join(root, "_npx-")); const npx = path.join(folder, "_npx", "h"); const pkgDir = path.join(npx, "node_modules", "@acme", "plan2code"); fs.mkdirSync(pkgDir, { recursive: true }); fs.writeFileSync(path.join(npx, "package.json"), JSON.stringify({ _npx: { packages: [spec] } })); return pkgDir; }; assert.equal(installer.npxSpecPinsCommit(sha, copy(`git+https://github.com/jparkerweb/plan2code.git#${sha}`)), true); assert.equal(installer.npxSpecPinsCommit(sha, copy("git+https://github.com/jparkerweb/plan2code.git#0123456")), true, "an abbreviated sha"); assert.equal(installer.npxSpecPinsCommit(sha, copy("git+https://github.com/jparkerweb/plan2code.git#main")), false); assert.equal(installer.npxSpecPinsCommit(sha, copy("git+https://github.com/jparkerweb/plan2code.git")), false); assert.equal(installer.npxSpecPinsCommit(sha, copy("git+https://github.com/jparkerweb/plan2code.git#fedcba9")), false, "another commit"); assert.equal(installer.npxSpecPinsCommit(sha, path.join(root, "not-npx")), false); });