diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md index da3550531..1d50686ef 100644 --- a/packages/coding-agent/CHANGELOG.md +++ b/packages/coding-agent/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Fixed + +- Fixed git plugin re-installs retaining stale commits by fetching Bun's cached clone before updating the lockfile pin ([#5401](https://github.com/can1357/oh-my-pi/issues/5401)). + ## [16.5.0] - 2026-07-13 ### Breaking Changes diff --git a/packages/coding-agent/src/extensibility/plugins/bun-git-cache.ts b/packages/coding-agent/src/extensibility/plugins/bun-git-cache.ts new file mode 100644 index 000000000..45b8fcc78 --- /dev/null +++ b/packages/coding-agent/src/extensibility/plugins/bun-git-cache.ts @@ -0,0 +1,91 @@ +import type { Dirent } from "node:fs"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { isEnoent } from "@oh-my-pi/pi-utils"; +import type { GitSource } from "./git-url"; + +interface CommandResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +async function runCommand(command: string[], cwd: string): Promise { + const proc = Bun.spawn(command, { + cwd, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + windowsHide: true, + }); + const [exitCode, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + return { exitCode, stdout, stderr }; +} + +function normalizeRepositoryUrl(repository: string): string { + const withoutFragment = repository.replace(/^git\+/i, "").replace(/#.*$/, ""); + const scpLike = withoutFragment.match(/^(?:[^@]+@)?([^:]+):(.+)$/); + if (scpLike && !withoutFragment.includes("://")) { + const host = scpLike[1]?.toLowerCase() ?? ""; + const repoPath = (scpLike[2] ?? "").replace(/^\/+|\/+$/g, "").replace(/\.git$/i, ""); + return `ssh://${host}/${repoPath}`; + } + + try { + const parsed = new URL(withoutFragment); + const repoPath = parsed.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, ""); + return `${parsed.protocol.toLowerCase()}//${parsed.host.toLowerCase()}/${repoPath}`; + } catch { + return withoutFragment.replace(/\/+$/g, "").replace(/\.git$/i, ""); + } +} + +/** Fetches current heads and tags into Bun's matching cached bare clone before a plugin update. */ +export async function refreshBunGitCache(source: GitSource, cwd: string): Promise { + const cacheResult = await runCommand(["bun", "pm", "cache"], cwd); + if (cacheResult.exitCode !== 0) { + throw new Error(`bun pm cache failed: ${cacheResult.stderr}`); + } + const cacheDir = cacheResult.stdout.trim(); + if (!cacheDir) { + throw new Error("bun pm cache returned an empty cache path"); + } + + let entries: Dirent[]; + try { + entries = await fs.readdir(cacheDir, { withFileTypes: true }); + } catch (err) { + if (isEnoent(err)) return; + throw err; + } + + const repositoryUrl = normalizeRepositoryUrl(source.repo); + for (const entry of entries) { + if (!entry.isDirectory() || !entry.name.endsWith(".git")) continue; + const repositoryDir = path.join(cacheDir, entry.name); + const originResult = await runCommand(["git", "-C", repositoryDir, "config", "--get", "remote.origin.url"], cwd); + if (originResult.exitCode !== 0 || normalizeRepositoryUrl(originResult.stdout.trim()) !== repositoryUrl) continue; + + const fetchResult = await runCommand( + [ + "git", + "-C", + repositoryDir, + "fetch", + "--force", + "--prune", + "origin", + "+refs/heads/*:refs/heads/*", + "+refs/tags/*:refs/tags/*", + ], + cwd, + ); + if (fetchResult.exitCode !== 0) { + throw new Error(`Failed to refresh Bun's git cache for ${source.host}/${source.path}: ${fetchResult.stderr}`); + } + } +} diff --git a/packages/coding-agent/src/extensibility/plugins/manager.ts b/packages/coding-agent/src/extensibility/plugins/manager.ts index f1e7801c3..4c01c6be1 100644 --- a/packages/coding-agent/src/extensibility/plugins/manager.ts +++ b/packages/coding-agent/src/extensibility/plugins/manager.ts @@ -12,6 +12,7 @@ import { logger, } from "@oh-my-pi/pi-utils"; import { withExitGuard } from "../utils"; +import { refreshBunGitCache } from "./bun-git-cache"; import { type GitSource, parseGitUrl } from "./git-url"; import { installLegacyPiSpecifierShim, loadLegacyPiModule } from "./legacy-pi-compat"; import { resolvePluginManifestEntries } from "./loader"; @@ -500,14 +501,13 @@ export class PluginManager { // Step 2: refresh the git lockfile pin when re-installing an existing // git plugin. `bun install ` is a no-op when the spec matches the - // lockfile entry — it never re-resolves the remote ref — so re-running - // `omp plugin install github:owner/repo` would silently keep the user on - // the original resolved commit even after upstream moved (#3063). - // `bun update ` re-resolves the ref against the remote and - // rewrites the pin; SHA-pinned refs stay put because the commit can't - // move. First-time installs skip this — the initial `bun install` already - // fetched HEAD. Rollback is handled by the outer catch. + // lockfile entry, while `bun update ` resolves through Bun's bare + // clone cache. Fetch the matching cache clone first so a stale cached + // ref cannot silently preserve the old pin (#3063, #5401). First-time + // installs skip this because the initial `bun install` populated the + // cache from the remote. Rollback is handled by the outer catch. if (gitSource && existingActualName) { + await refreshBunGitCache(gitSource, getPluginsDir()); const updateProc = Bun.spawn(["bun", "update", actualName], { cwd: getPluginsDir(), stdin: "ignore", diff --git a/packages/coding-agent/test/plugin-install-git.test.ts b/packages/coding-agent/test/plugin-install-git.test.ts index 347c23b3e..890a5c7ad 100644 --- a/packages/coding-agent/test/plugin-install-git.test.ts +++ b/packages/coding-agent/test/plugin-install-git.test.ts @@ -31,6 +31,24 @@ function emptyStream(): ReadableStream { return body; } +async function runCommand(command: string[], cwd: string): Promise { + const proc = Bun.spawn(command, { + cwd, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }); + const [exitCode, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + if (exitCode !== 0) { + throw new Error(`${command.join(" ")} failed (${exitCode}): ${stderr}`); + } + return stdout.trim(); +} + describe("PluginManager.install with git sources", () => { let tmpRoot: string; let pluginsDir: string; @@ -161,7 +179,7 @@ describe("PluginManager.install with git sources", () => { expect(result.version).toBe("1.0.0"); }); - test("re-installing a github plugin runs `bun update` to refresh the stale lockfile pin (#3063)", async () => { + test("refreshes Bun's git cache before updating a re-installed github plugin (#3063)", async () => { // Seed plugins/package.json + node_modules with a previously-installed // github plugin. `findGitPackageName` matches the new install spec to // this existing dep (by repository identity), which is the signal the @@ -184,6 +202,8 @@ describe("PluginManager.install with git sources", () => { path.join(seedDir, "package.json"), JSON.stringify({ name: "stale-plugin", version: "0.1.0" }, null, 2), ); + const cacheDir = path.join(tmpRoot, "bun-cache"); + await fs.mkdir(cacheDir); const spawnedCommands: string[][] = []; vi.spyOn(Bun, "spawn").mockImplementation(((cmd: string[]) => { @@ -200,6 +220,16 @@ describe("PluginManager.install with git sources", () => { exited: Promise.resolve(0), } as Subprocess; } + if (cmd[1] === "pm") { + const stdout = new Response(`${cacheDir}\n`).body; + if (!stdout) throw new Error("Failed to create cache path stream"); + return { + pid: 2, + stdout, + stderr: emptyStream(), + exited: Promise.resolve(0), + } as Subprocess; + } // The follow-up call: simulate bun resolving the upstream HEAD to a // newer commit and bumping the on-disk version. The manager should // read the new version from package.json after this step returns. @@ -211,7 +241,7 @@ describe("PluginManager.install with git sources", () => { ); })(); return { - pid: 2, + pid: 3, stdout: emptyStream(), stderr: emptyStream(), exited: prepare.then(() => 0), @@ -224,6 +254,7 @@ describe("PluginManager.install with git sources", () => { expect(result.version).toBe("0.1.6"); expect(spawnedCommands).toEqual([ ["bun", "install", "github:foo/bar"], + ["bun", "pm", "cache"], ["bun", "update", "stale-plugin"], ]); }); @@ -330,6 +361,71 @@ describe("PluginManager.install with git sources", () => { expect(installed.name).toBe("real-name"); }); + test("refreshes Bun's cached git clone before updating an existing plugin (#5401)", async () => { + const sourceDir = path.join(tmpRoot, "source"); + const httpRoot = path.join(tmpRoot, "http"); + const remoteDir = path.join(httpRoot, "testuser", "remote.git"); + const cacheDir = path.join(tmpRoot, "bun-cache"); + await fs.mkdir(sourceDir, { recursive: true }); + await fs.mkdir(path.dirname(remoteDir), { recursive: true }); + await runCommand(["git", "init", "-b", "main"], sourceDir); + await runCommand(["git", "config", "user.name", "Plugin test"], sourceDir); + await runCommand(["git", "config", "user.email", "plugin-test@example.com"], sourceDir); + await Bun.write( + path.join(sourceDir, "package.json"), + JSON.stringify({ name: "@test/pi-package", version: "1.0.0" }, null, 2), + ); + await runCommand(["git", "add", "package.json"], sourceDir); + await runCommand(["git", "commit", "-m", "version A"], sourceDir); + await runCommand(["git", "clone", "--bare", sourceDir, remoteDir], tmpRoot); + await runCommand(["git", "update-server-info"], remoteDir); + + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const url = new URL(request.url); + const relativePath = decodeURIComponent(url.pathname).replace(/^\/+/, ""); + const filePath = path.resolve(httpRoot, relativePath); + if (!filePath.startsWith(`${httpRoot}${path.sep}`)) { + return new Response("Not found", { status: 404 }); + } + try { + return new Response(await Bun.file(filePath).arrayBuffer(), { + headers: { "Content-Type": "application/octet-stream" }, + }); + } catch { + return new Response("Not found", { status: 404 }); + } + }, + }); + + try { + await Bun.write( + pluginsPkgJson, + JSON.stringify({ name: "omp-plugins", private: true, dependencies: {} }, null, 2), + ); + await Bun.write(path.join(pluginsDir, "bunfig.toml"), `[install.cache]\ndir = ${JSON.stringify(cacheDir)}\n`); + const spec = `git+http://127.0.0.1:${server.port}/testuser/remote.git#main`; + const mgr = new PluginManager(tmpRoot); + expect((await mgr.install(spec)).version).toBe("1.0.0"); + + await Bun.write( + path.join(sourceDir, "package.json"), + JSON.stringify({ name: "@test/pi-package", version: "2.0.0" }, null, 2), + ); + await runCommand(["git", "add", "package.json"], sourceDir); + await runCommand(["git", "commit", "-m", "version B"], sourceDir); + await runCommand(["git", "push", remoteDir, "main"], sourceDir); + await runCommand(["git", "update-server-info"], remoteDir); + + const reinstalled = await mgr.install(spec); + expect(reinstalled.version).toBe("2.0.0"); + } finally { + await server.stop(true); + } + }); + test("rejects git specs containing shell metacharacters", async () => { const mgr = new PluginManager(tmpRoot); await expect(mgr.install("github:foo/bar; rm -rf /")).rejects.toThrow(/Invalid characters in plugin source/);