From cc7d89181dcd149ae01a8323b0832b250c7953b0 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Wed, 18 Nov 2026 09:23:38 -0800 Subject: [PATCH] Send installers fetched from unreleased main to the newest release, for launchers older than the release channel AI Assisted Co-Authored-By: Claude Opus 5.5 --- .agents-docs/AGENTS-architecture-install.md | 2 +- install.js | 106 ++++++++++++++++++-- scripts/test-install-update.mjs | 87 ++++++++++++++++ scripts/test-launcher.mjs | 5 + src/launcher/plan2code.js | 6 +- 5 files changed, 193 insertions(+), 13 deletions(-) diff --git a/.agents-docs/AGENTS-architecture-install.md b/.agents-docs/AGENTS-architecture-install.md index 992fb84..34018ee 100644 --- a/.agents-docs/AGENTS-architecture-install.md +++ b/.agents-docs/AGENTS-architecture-install.md @@ -123,7 +123,7 @@ plan2code/ ### Release channel -Install and update follow release tags, never `main`. `release-app.yml`'s `publish` job ends by fast-forwarding the `release` branch to the tag it just published (no force: a tag not ahead of the branch fails the job), and the README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`. `plan2code update` installs the newest `vX.Y.Z` tag (`newestReleaseTag()` in `src/launcher/plan2code.js`, using `latestTag()` and `runLsRemote()` from the copy of `update-check.mjs` beside it); `--main` installs the tip of `main`, `--tag ` any ref (how to go back to a release); `--main` and a `--tag` naming a branch always pass `--force`, since unreleased work keeps the last release's version and the installer's `Already on` check would install nothing. `plan2code uninstall` runs the newest release's installer the same way, falling back to `main` only when no release tag can be found. The console's release check (`update-check.mjs`) and the app's notice (`versions.rs` `latest_tag()`) use the same rule: the highest plain `vX.Y.Z` in `git ls-remote --tags`, peeled and pre-release tags skipped. The app's Update skills still pins to the app's own tag. +Install and update follow release tags, never `main`. `release-app.yml`'s `publish` job ends by fast-forwarding the `release` branch to the tag it just published (no force: a tag not ahead of the branch fails the job), and the README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`. `plan2code update` installs the newest `vX.Y.Z` tag (`newestReleaseTag()` in `src/launcher/plan2code.js`, using `latestTag()` and `runLsRemote()` from the copy of `update-check.mjs` beside it); `--main` installs the tip of `main`, `--tag ` any ref (how to go back to a release); `--main` and a `--tag` naming a branch always pass `--force`, since unreleased work keeps the last release's version and the installer's `Already on` check would install nothing. `plan2code uninstall` runs the newest release's installer the same way, falling back to `main` only when no release tag can be found. Launchers older than the channel (and install commands copied without `#release`) still fetch `main`, so `install.js` redirects itself (`redirectToRelease()`): when npx fetched it from a commit no `vX.Y.Z` tag points at (`fetchedCommit()` reads npm's hidden `node_modules/.package-lock.json`; `releaseRedirectRef()` decides), it reruns the same options from `#v`. The launcher sets `PLAN2CODE_INSTALL_REF` on every installer run (`main` for `--main`) so a deliberate ref is never redirected, a checkout is not under `node_modules` so it never is either, and anything unknown (no lock file, no network) runs in place. The redirect lives on `main` for old launchers to find, so it must stay there. The console's release check (`update-check.mjs`) and the app's notice (`versions.rs` `latest_tag()`) use the same rule: the highest plain `vX.Y.Z` in `git ls-remote --tags`, peeled and pre-release tags skipped. The app's Update skills still pins to the app's own tag. ### Agents file diff --git a/install.js b/install.js index f508a3e..b791761 100644 --- a/install.js +++ b/install.js @@ -3817,20 +3817,90 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims return 0; } +// ============================================================================ +// RELEASE REDIRECT +// ============================================================================ +// +// Launchers older than the release channel run `plan2code update` (and uninstall) as +// `npx git+ --update`, which is the tip of main, and so does an install command copied from +// an older README. Without this, those people would get unreleased work. When this copy came from +// an npx fetch of a commit that no `vX.Y.Z` tag points at, it hands the same command to the +// newest release instead. Any run the current launcher starts says which ref it picked on purpose +// (PLAN2CODE_INSTALL_REF, `--main` included), and a checkout (`node install.js`) is never under +// node_modules, so neither is redirected. Anything unknown (no lock file, no network) also means +// no redirect: the run goes on exactly as before. + +/** The commit npx fetched this copy from (from npm's hidden lock file beside it), or null. */ +function fetchedCommit(dir = __dirname) { + const modules = path.dirname(dir); + if (path.basename(modules) !== 'node_modules') return null; + try { + const lock = JSON.parse(fs.readFileSync(path.join(modules, '.package-lock.json'), 'utf8')); + const entry = lock && lock.packages && lock.packages[`node_modules/${path.basename(dir)}`]; + const m = entry && typeof entry.resolved === 'string' ? /#([0-9a-f]{40})$/i.exec(entry.resolved) : null; + return m ? m[1].toLowerCase() : null; + } catch { + return null; + } +} + +/** + * The release tag to hand this run to, as `vX.Y.Z`, or null to run here. `lsRemote` is + * `git ls-remote --tags` output and `newest` its newest release (update-check.mjs's pick). A + * commit any release tag points at (peeled or not) stays, so an older launcher's + * `update --tag v3.0.2` and the `#release` branch are left alone. + */ +function releaseRedirectRef({ commit, lsRemote, newest, env = process.env }) { + if (env.PLAN2CODE_INSTALL_REF || !commit || !newest || typeof lsRemote !== 'string') return null; + for (const line of lsRemote.split(/\r?\n/)) { + const m = /^([0-9a-f]{40})\s+refs\/tags\/v\d+\.\d+\.\d+(\^\{\})?$/i.exec(line.trim()); + if (m && m[1].toLowerCase() === commit) return null; + } + return `v${newest}`; +} + +/** + * Run the newest release's installer with the same options when this copy is unreleased work + * fetched by an older launcher. Resolves the child's exit code, or null to carry on here. + */ +async function redirectToRelease(argv) { + if (!argv.every((a) => /^--[a-z]+$/.test(a))) return null; + const commit = fetchedCommit(); + if (!commit || process.env.PLAN2CODE_INSTALL_REF) return null; + let ref = null; + try { + const checker = await import(pathToFileURL(UPDATE_CHECK_SRC).href); + const stub = process.env.PLAN2CODE_LS_REMOTE_FILE; + const lsRemote = stub ? fs.readFileSync(stub, 'utf8') : await checker.runLsRemote(); + ref = releaseRedirectRef({ commit, lsRemote, newest: checker.latestTag(lsRemote) }); + } catch { + return null; + } + if (!ref) return null; + console.log(`This installer is unreleased work from main, so Plan2Code is switching to the newest release, ${ref}.`); + console.log(`${COLORS.DIM}Fetching it can take a minute or two.${COLORS.RESET}`); + const command = ['npx', '--yes', '--allow-git=all', `git+https://github.com/jparkerweb/plan2code.git#${ref}`, ...argv].join(' '); + return new Promise((resolve) => { + let child; + try { + child = spawn(command, { shell: true, stdio: 'inherit', env: { ...process.env, PLAN2CODE_INSTALL_REF: ref } }); + } catch { + resolve(null); + return; + } + // The child owns the terminal now: Ctrl+C reaches it, and this process waits for its code. + for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => {}); + child.on('error', () => resolve(null)); + child.on('exit', (code) => resolve(code ?? 1)); + }); +} + // ============================================================================ // MAIN // ============================================================================ -// Run only when invoked directly; requiring the file (the update tests do) is load-only. -if (require.main === module) { - // Non-interactive build hooks for the generated skills/ artifact. - const argv = process.argv.slice(2); - - if (argv.includes('--build-skills')) { - process.exit(buildSkills() ? 0 : 1); - } else if (argv.includes('--verify-skills')) { - process.exit(verifySkillsSync() ? 0 : 1); - } else if (argv[0] === '--update' && argv.slice(1).every((a) => a === '--force')) { +function runCommand(argv) { + if (argv[0] === '--update' && argv.slice(1).every((a) => a === '--force')) { update({ force: argv.includes('--force') }).then((code) => process.exit(code)); } else if (argv[0] === '--uninstall' && argv.slice(1).every((a) => a === '--yes' || a === '--purge')) { uninstall({ yes: argv.includes('--yes'), purge: argv.includes('--purge') }).then((code) => process.exit(code)); @@ -3844,4 +3914,18 @@ if (require.main === module) { } } -module.exports = { printKeptData, uninstallSkillsPiece, removeSkillsDirectly, removeConsoleFolders, uninstallStatusLine, listKeptData, newUninstallReport, printUninstallReport, UNINSTALL_STEPS, UNINSTALL_PROBES, PIECE_LABELS, createSpinner, printGettingStarted, pathFixLine, fullCommandPath, desktopAppState, detectAgents, agentInstallLine, writeLauncherShim, isOurLauncherShim, LAUNCHER_MARKER, NO_TERMINAL_MESSAGE, appAllowLine, APP_GUIDE_URL, formatBytes, nodeVersionProblem, appWebviewDirs, purgeAppWebview, appRunning, uninstall, uninstallAll, purgeData, installSharedConsole, sweepOldConsoles, consoleHomeDir, CONSOLE_SHARED_DIR, update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName }; +// Run only when invoked directly; requiring the file (the update tests do) is load-only. +if (require.main === module) { + const argv = process.argv.slice(2); + + // Non-interactive build hooks for the generated skills/ artifact. + if (argv.includes('--build-skills')) { + process.exit(buildSkills() ? 0 : 1); + } else if (argv.includes('--verify-skills')) { + process.exit(verifySkillsSync() ? 0 : 1); + } else { + redirectToRelease(argv).then((code) => (code === null ? runCommand(argv) : process.exit(code))); + } +} + +module.exports = { fetchedCommit, releaseRedirectRef, printKeptData, uninstallSkillsPiece, removeSkillsDirectly, removeConsoleFolders, uninstallStatusLine, listKeptData, newUninstallReport, printUninstallReport, UNINSTALL_STEPS, UNINSTALL_PROBES, PIECE_LABELS, createSpinner, printGettingStarted, pathFixLine, fullCommandPath, desktopAppState, detectAgents, agentInstallLine, writeLauncherShim, isOurLauncherShim, LAUNCHER_MARKER, NO_TERMINAL_MESSAGE, appAllowLine, APP_GUIDE_URL, formatBytes, nodeVersionProblem, appWebviewDirs, purgeAppWebview, appRunning, uninstall, uninstallAll, purgeData, installSharedConsole, sweepOldConsoles, consoleHomeDir, CONSOLE_SHARED_DIR, update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName }; diff --git a/scripts/test-install-update.mjs b/scripts/test-install-update.mjs index 510c808..3e5551b 100644 --- a/scripts/test-install-update.mjs +++ b/scripts/test-install-update.mjs @@ -312,6 +312,93 @@ test("install.js --update: an option other than --force is refused", () => { assert.match(refused.stderr, /Unknown option\(s\): --update --nope/); }); +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"); + +test("release redirect: unreleased work goes to the newest release; a release commit, a chosen ref or an unknown stays", () => { + const ref = (commit, extra = {}) => installer.releaseRedirectRef({ commit, lsRemote: TAGS, newest: "3.1.2", env: {}, ...extra }); + assert.equal(ref(SHA_MAIN), "v3.1.2"); + assert.equal(ref(SHA_RELEASE), null, "the newest release (and the release branch on it) stays"); + assert.equal(ref(SHA_OLD_RELEASE), null, "an older launcher's update --tag v3.0.2 stays on v3.0.2"); + assert.equal(ref("d".repeat(40)), "v3.1.2", "a tag that is not vX.Y.Z is not a release"); + assert.equal(ref(SHA_MAIN, { env: { PLAN2CODE_INSTALL_REF: "main" } }), null, "the current launcher's --main stays on main"); + assert.equal(ref(null), null); + assert.equal(ref(SHA_MAIN, { newest: null }), null); + assert.equal(ref(SHA_MAIN, { lsRemote: null }), null); + // An annotated tag's commit is on its peeled line. + assert.equal(ref(SHA_MAIN, { lsRemote: `${"e".repeat(40)}\trefs/tags/v3.1.2\n${SHA_MAIN}\trefs/tags/v3.1.2^{}` }), null); +}); + +/** install.js laid out as npx leaves a git package: node_modules/plan2code beside npm's hidden lock file. */ +function npxCopy(commit) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-npx-copy-")); + const pkg = path.join(dir, "node_modules", "plan2code"); + fs.mkdirSync(path.join(pkg, "src", "web-console"), { 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")); + 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/plan2code": { version: VERSION, resolved } } })); + } + fs.writeFileSync(path.join(dir, "ls-remote.txt"), TAGS + "\n"); + // A stand-in npx that records its arguments and the ref 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 }));\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; + 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 result = copy.run(["--update", "--force"]); + 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 } = 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"); +}); + +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"); diff --git a/scripts/test-launcher.mjs b/scripts/test-launcher.mjs index afe0871..9f61ded 100644 --- a/scripts/test-launcher.mjs +++ b/scripts/test-launcher.mjs @@ -58,6 +58,8 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {} fs.writeFileSync( recorder, 'require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".json"), JSON.stringify(process.argv.slice(3)));\n' + + // The ref the launcher marks its installer runs with, so install.js never redirects them. + 'if (process.env.PLAN2CODE_INSTALL_REF) require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".ref"), process.env.PLAN2CODE_INSTALL_REF);\n' + "process.exitCode = Number(process.env.P2C_TEST_EXIT || 0);\n" ); for (const cli of clis) { @@ -503,6 +505,7 @@ test("launcher: update installs the newest release tag, by version and not by na assert.ok(args.includes("--update"), args.join(" ")); assert.ok(args.includes(`${REPO}#v3.10.0`), args.join(" ")); assert.ok(!args.includes("--force"), args.join(" ")); + assert.equal(fs.readFileSync(path.join(box.dir, "bin", "npx.ref"), "utf8"), "v3.10.0", "the run is marked with the ref it picked"); assert.equal(box.argsOf("claude"), null); }); @@ -518,6 +521,8 @@ test("launcher: update --main installs the tip of main, as it always did", (t) = // Unreleased work on main carries the last release's version, so the installer's "Already on" // check would stop it: --main always reinstalls. assert.ok(args.includes("--force"), args.join(" ")); + // Marked as chosen, so install.js's redirect for older launchers leaves it on main. + assert.equal(fs.readFileSync(path.join(box.dir, "bin", "npx.ref"), "utf8"), "main"); }); test("launcher: update --tag reinstalls for a branch, and not for a release tag", (t) => { diff --git a/src/launcher/plan2code.js b/src/launcher/plan2code.js index f45c088..ed93b88 100644 --- a/src/launcher/plan2code.js +++ b/src/launcher/plan2code.js @@ -1700,6 +1700,7 @@ async function runUpdate({ tag, main, force } = {}) { } console.log(ref === undefined ? 'Updating Plan2Code to the newest work on main...' : `Updating Plan2Code to ${ref}...`); console.log(c.dim('One update covers the skills, the plan2code command and the desktop app (when installed).')); + console.log(c.dim('npx fetches it quietly first, which can take a minute or two.')); const unreleased = main || (tag !== undefined && !/^v\d+\.\d+\.\d+$/.test(tag)); return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], ref); } @@ -1745,7 +1746,10 @@ function runInstaller(installerArgs, tag) { return process.exit(127); } const spec = tag ? `git+${REPO_URL}#${tag}` : `git+${REPO_URL}`; - const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit' }); + // The ref was picked on purpose (main included): install.js's release redirect, there for + // launchers older than the release channel, must leave this run where it is. + const env = { ...process.env, PLAN2CODE_INSTALL_REF: tag || 'main' }; + const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit', env }); for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) { process.on(signal, () => {}); }