Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
plugin: a lock behind package.json's dist tarball is mended, its tarballs kept (#3622)
JoeyWu-tech6cb1cfb7942c
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.mdindex 2cd2cef44..98ffd1163 100644--- a/docs/subsystems/provider-plugins.md+++ b/docs/subsystems/provider-plugins.md@@ -168,9 +168,9 @@ New users do not see an unused deprecated built-in in the Add sheet. `unusedSub`The editor's *Update* button and *Update all* install npm's newest version; a pin the user set is kept until they update it themselves, and is then unpinned. `keepMovedCurrent` is the one path that acts without the user pressing anything, so `installPlugin` leaves what the user chose: a pinned npm version below the move's `min` is not reinstalled, and the move says it is pinned and which version it needs; a git install is reinstalled from its own spec; an unpinned npm one goes through `plugin.Upgrade` (npm's newest, which bun says why it won't install under a `minimumReleaseAge`, where `Add`'s `@latest` would quietly give an older one); a plugin the user turned off is left alone.-A `@magpie-community` package npm doesn't give is installed from the community repo's `dist` branch ([`dist.go`](../../internal/plugin/dist.go)). npm can't take a new package's first version without an owner's 2FA (Trusted Publishing sets up only a package that exists), so reviewed plugins sat unmerged waiting for someone to publish them (magpie-community/plugins#84); a Trusted Publisher made after 2026-09-03 allows stage publish only, and zed 0.1.7 and zen-free 0.1.7 were refused that way. The repo's `publish.yml` now packs every merged version onto `dist` (`scripts/dist.mjs`: `tgz/<file>` and `index.json` with each version's sha512, manifest and the README) with nobody's credentials, and npm is published to beside it. `install` asks npm first, as before; only when `bun add` fails for a community package at `latest` or an exact version (`distWanted`), and not because of the user's `minimumReleaseAge` (that hold is kept), does `installDist` fetch the tarball, refuse it unless its sha512 is the index's, keep it in `plugins/dist` and `bun add ./dist/<file>`. A later install from npm takes its place and `pruneDist` removes tarballs `package.json` no longer names. `npmAsk` (the market's version, *Update*, the hourly check) takes `dist`'s latest when npm errors or is behind, and `Readme` falls back to its README. The branch is read through the 「国内镜像」 switch's jsDelivr copy when that is on (`fetchJSONFaithful`), else raw.githubusercontent.com. `TestDistInstallsAPackageNPMDoesntHave`, `TestDistServesAVersionNPMRefused`, `TestDistRefusesATarballNotItsIndexs` and `TestUpdateBunHoldsBackSaysWhy` (with `dist` holding the held version) in [`dist_test.go`](../../internal/plugin/dist_test.go) and [`update_held_test.go`](../../internal/plugin/update_held_test.go) cover these.+A `@magpie-community` package npm doesn't give is installed from the community repo's `dist` branch ([`dist.go`](../../internal/plugin/dist.go)). npm can't take a new package's first version without an owner's 2FA (Trusted Publishing sets up only a package that exists), so reviewed plugins sat unmerged waiting for someone to publish them (magpie-community/plugins#84); a Trusted Publisher made after 2026-09-03 allows stage publish only, and zed 0.1.7 and zen-free 0.1.7 were refused that way. The repo's `publish.yml` now packs every merged version onto `dist` (`scripts/dist.mjs`: `tgz/<file>` and `index.json` with each version's sha512, manifest and the README) with nobody's credentials, and npm is published to beside it. `install` asks npm first, as before; only when `bun add` fails for a community package at `latest` or an exact version (`distWanted`), and not because of the user's `minimumReleaseAge` (that hold is kept), does `installDist` fetch the tarball, refuse it unless its sha512 is the index's, keep it in `plugins/dist` and `bun add ./dist/<file>`. A later install from npm takes its place and `pruneDist` removes the tarballs neither `package.json` names nor `bun.lock`'s `packages` has a package at: Bun installs from the lock's, which can be behind `package.json`, and Bun 1.4.0 writes a package it adds from a tarball into `package.json` a second time, the new tarball first, where `encoding/json` reads the second. A tarball only the lock's `workspaces` names (Bun 1.4.2 and 1.4.3 leave the one replaced there) goes. A lock behind `package.json` put a package's older version back at every bun command, and, once that tarball was gone from `plugins/dist`, failed every `bun add` and `bun remove`, of any plugin, with `ENOENT extracting tarball from <that package>` (#3622, Windows, Bun 1.4.4), so before each bun command `mendDist` runs one `bun update` of every package the lock has at a dist tarball `package.json` doesn't name, when `package.json`'s is there, which takes the lock back to `package.json`'s without the network (`bun add` doesn't, on Bun 1.4.2 and 1.4.3), and logs it. Both read the lock's first object alone (`lockHead`), as Bun does: a shorter lock written over a longer one without truncating, as `package.json` was (magpie-community/plugins#405), leaves the old lock's packages after it, which would keep their tarballs and send them to `bun update` at every command. `npmAsk` (the market's version, *Update*, the hourly check) takes `dist`'s latest when npm errors or is behind, and `Readme` falls back to its README. The branch is read through the 「国内镜像」 switch's jsDelivr copy when that is on (`fetchJSONFaithful`), else raw.githubusercontent.com. `TestDistInstallsAPackageNPMDoesntHave`, `TestDistServesAVersionNPMRefused`, `TestDistRefusesATarballNotItsIndexs`, `TestDistTarballTheLockNamesStays`, `TestDistLockBehindPackageJSONIsMended`, `TestDistLockTailIsntRead` and `TestUpdateBunHoldsBackSaysWhy` (with `dist` holding the held version) in [`dist_test.go`](../../internal/plugin/dist_test.go) and [`update_held_test.go`](../../internal/plugin/update_held_test.go) cover these.-A plugin on the list whose package isn't in `plugins/` is installed again from its own spec, switched off or not, by `plugin.InstallMissing`. `KeepUpdated` runs it 30 seconds after start and then hourly, before `CheckUpdates`. Nothing else did this. An update skips a plugin with no installed version, so the host said `no such plugin: …\node_modules\…` at every start until the user removed the plugin and added it again (#2002, Windows, after an update). Every bun command that changes `plugins/` runs one at a time under `installMu`: `install` (with the first `package.json` it writes), `reinstall`'s `bun update`, and `Remove`'s and `add`'s `bun remove`. At start, `KeepUpdated` and `keepMovedCurrent` both run `bun add`. Two at once each read `package.json` before either writes it, so one change was lost (reproduced with Bun 1.4.3 on Windows), and a git plugin whose dependency was dropped can't be found. `TestMissingPluginsInstalledAgain` and `TestBunCommandsOneAtATime` in [`plugin_missing_test.go`](../../internal/plugin/plugin_missing_test.go) cover both.+A plugin on the list whose package isn't in `plugins/` is installed again from its own spec, switched off or not, by `plugin.InstallMissing`. `KeepUpdated` runs it 30 seconds after start and then hourly, before `CheckUpdates`. Nothing else did this. An update skips a plugin with no installed version, so the host said `no such plugin: …\node_modules\…` at every start until the user removed the plugin and added it again (#2002, Windows, after an update). Every bun command that changes `plugins/` runs one at a time under `installMu`: `install` (with the first `package.json` it writes, through temp and rename), `reinstall`'s `bun update`, and `Remove`'s and `add`'s `bun remove`, each after `mendPackageJSON` and then `mendDist`, which reads `package.json`. At start, `KeepUpdated` and `keepMovedCurrent` both run `bun add`. Two at once each read `package.json` before either writes it, so one change was lost (reproduced with Bun 1.4.3 on Windows), and a git plugin whose dependency was dropped can't be found. `TestMissingPluginsInstalledAgain` and `TestBunCommandsOneAtATime` in [`plugin_missing_test.go`](../../internal/plugin/plugin_missing_test.go) cover both.A name the user types is resolved before anything is installed (`resolve` in [`resolve.go`](../../internal/plugin/resolve.go)), in `plugin.Add`, which the CLI's `magpie plugin add`, the Plugins page's field (`/api/plugins/add`) and the movers all go through. A bare name that one of the community's listings goes by, case aside, is that package at the version given: its package or that without the scope, its short name (`workbuddy`, `think-tags`), its shown name (`WorkBuddy`, `Command Code`), a provider id it serves or the subscription it replaces, and a retired subscription's id through its mover (`qoder-cn`, `plugin.SubscriptionPlugin` = `MovePackage`). A name two listings go by, or one no listing goes by that isn't an npm name, is refused with the community plugins named. A name no listing goes by is npm's own package (`opencode-gemini-auth`) only when the list was fetched within the six hours: when the fetch fails, the copy kept or built in may not name a newer plugin, so the name is refused with why, and `npm:<name>` installs npm's package as written. Before, `WorkBuddy` failed as no npm name, and `workbuddy` installed npm's unscoped `workbuddy` (Atlas on Discord, 10-25). Scoped names, paths and git specs are kept as written, and a backup's or a sync's plugins are installed by their own spec (`plugin.AddExact`), never resolved. `TestResolveCommunityNames`, `TestResolveRefusesWhatItCantName`, `TestResolveListUnread` and `TestAddByCommunityName` in [`resolve_test.go`](../../internal/plugin/resolve_test.go) cover these.diff --git a/internal/plugin/dist.go b/internal/plugin/dist.goindex cdbe03aee..3a3db0a8b 100644--- a/internal/plugin/dist.go+++ b/internal/plugin/dist.go@@ -1,15 +1,20 @@package pluginimport (+ "bytes""context""crypto/sha512""encoding/base64""encoding/json"+ "errors""fmt"+ "io/fs"+ "log""os""path""path/filepath""regexp"+ "slices""strings""sync""time"@@ -184,11 +189,73 @@ func installDist(ctx context.Context, bun, name, version string) error {return bunAdd(ctx, bun, "./dist/"+file)}-// pruneDist takes out the tarballs in plugins/dist that plugins/package.json-// no longer names: one an update from npm, or a newer one, took the place-// of. installMu held. One it can't tell about (package.json unreadable)-// stays.+// pruneDist takes out the tarballs in plugins/dist that neither+// plugins/package.json nor bun.lock's packages has a package at: one an+// update from npm, or a newer one, took the place of. Bun installs a+// package from the tarball the lock's packages has it at, which+// package.json can have moved on from (#3622), so that one stays too.+// package.json is read as text, every mention counting: Bun 1.4.0 adds a+// tarball's package again instead of replacing it, and of the two keys+// encoding/json takes the second where Bun takes the first, so the tarball+// taken out was the one Bun installs from. A tarball only the lock's+// workspaces names (Bun 1.4.2 and 1.4.3 keep the one replaced there, and+// drop it on their next command) goes. installMu held. One it can't tell+// about (package.json, or a bun.lock that is there, unreadable) stays.func pruneDist() {+ pj, err := os.ReadFile(filepath.Join(Dir(), "package.json"))+ if err != nil {+ return+ }+ lock, err := os.ReadFile(filepath.Join(Dir(), "bun.lock"))+ if err != nil && !errors.Is(err, fs.ErrNotExist) {+ return+ }+ locked := map[string]bool{}+ for _, m := range distLockedAt.FindAllSubmatch(lockHead(lock), -1) {+ locked[string(m[2])] = true+ }+ ents, err := os.ReadDir(filepath.Join(Dir(), "dist"))+ if err != nil {+ return+ }+ for _, e := range ents {+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".tgz") && !locked[e.Name()] && !distNamed(pj, e.Name()) {+ os.Remove(filepath.Join(Dir(), "dist", e.Name()))+ }+ }+}++// distNamed is whether package.json b names the tarball plugins/dist/file+// anywhere: "./dist/file" (the spec magpie hands Bun) or "file:dist/file".+func distNamed(b []byte, file string) bool {+ return bytes.Contains(b, []byte("dist/"+file+`"`))+}++// distLockedAt is a package bun.lock's packages has at a tarball in+// plugins/dist, and that tarball: "<name>": ["<name>@./dist/<file>", …].+var distLockedAt = regexp.MustCompile(`\["((?:@[^"/@]+/)?[^"/@]+)@(?:file:)?(?:\./)?dist/([A-Za-z0-9._-]+\.tgz)"`)++// mendDist sends bun.lock back to package.json for the packages it has at a+// dist tarball package.json doesn't name, when package.json has them at one+// plugins/dist holds. Bun installs what the lock has, at every command that+// changes plugins/: from that tarball, which pruneDist keeps, or from its+// copy of it, it put the older version back, and with neither it failed+// every install, update and removal, of any plugin, with "ENOENT extracting+// tarball from <it>". Bun 1.4.4 keys its copies by the tarball's sha512, so+// it has none of those 1.4.2 and 1.4.3 made (#3622, gkd2323c on Windows,+// Bun 1.4.4: autoclaw, codearts and cloudflare-workers-ai were locked at+// tarballs pruneDist had taken, while package.json and the lock's+// workspaces had moved on). A `bun update` of them all at once resolves+// them from package.json again: `bun add` doesn't on Bun 1.4.2 and 1.4.3,+// which keep what the lock has, and with no copy a package left out fails+// the update with it. A package.json that names the lock's tarball too (Bun+// 1.4.0 names a package twice) isn't behind. Each mend is logged, as+// nothing here says why a lock falls behind. installMu held.+func mendDist(ctx context.Context, bun string) {+ lock, err := os.ReadFile(filepath.Join(Dir(), "bun.lock"))+ if err != nil {+ return+ }b, err := os.ReadFile(filepath.Join(Dir(), "package.json"))if err != nil {return@@ -199,22 +266,62 @@ func pruneDist() {if json.Unmarshal(b, &pj) != nil {return}- named := map[string]bool{}- for _, s := range pj.Dependencies {- s = strings.TrimPrefix(s, "file:")- if rest, ok := strings.CutPrefix(filepath.ToSlash(s), "./dist/"); ok {- named[rest] = true- } else if rest, ok := strings.CutPrefix(filepath.ToSlash(s), "dist/"); ok {- named[rest] = true+ var stale []string+ for _, m := range distLockedAt.FindAllSubmatch(lockHead(lock), -1) {+ name, locked := string(m[1]), string(m[2])+ file, ok := distSpec(pj.Dependencies[name])+ if ok && file != locked && distHas(file) == nil && !distNamed(b, locked) && !slices.Contains(stale, name) {+ stale = append(stale, name)}}- ents, err := os.ReadDir(filepath.Join(Dir(), "dist"))- if err != nil {- return+ if len(stale) > 0 {+ // what this can't mend, the command it comes before says+ out, err := bunCommand(ctx, bun, Dir(), append([]string{"update", "--ignore-scripts"}, stale...)...).CombinedOutput()+ if err != nil {+ log.Printf("plugins: bun.lock behind package.json for %s; bun update: %v: %s", strings.Join(stale, ", "), err, lastLines(string(out), 3))+ } else {+ log.Printf("plugins: bun.lock behind package.json for %s, sent back", strings.Join(stale, ", "))+ }}- for _, e := range ents {- if !e.IsDir() && strings.HasSuffix(e.Name(), ".tgz") && !named[e.Name()] {- os.Remove(filepath.Join(Dir(), "dist", e.Name()))+}++// lockHead is bun.lock's first object, what Bun reads of it: Bun goes on+// past bytes left after it (tried on 1.4.4), which a shorter lock written+// over a longer one without truncating leaves, as package.json had+// (plugins#405). Read as packages, such a tail's old tarballs would be+// kept and sent to bun update at every command. A lock with no whole+// object is read as it is.+func lockHead(b []byte) []byte {+ depth, inStr, esc := 0, false, false+ for i, c := range b {+ switch {+ case esc:+ esc = false+ case inStr:+ esc = c == '\\'+ inStr = c != '"'+ case c == '"':+ inStr = true+ case c == '{' || c == '[':+ depth+++ case c == '}' || c == ']':+ depth--+ if depth == 0 {+ return b[:i+1]+ }}}+ return b+}++// distSpec is the tarball in plugins/dist a package.json dependency is at.+func distSpec(spec string) (string, bool) {+ s := filepath.ToSlash(strings.TrimPrefix(spec, "file:"))+ return strings.CutPrefix(strings.TrimPrefix(s, "./"), "dist/")+}++// distHas is os.Stat's answer for plugins/dist/file.+func distHas(file string) error {+ _, err := os.Stat(filepath.Join(Dir(), "dist", file))+ return err}diff --git a/internal/plugin/dist_test.go b/internal/plugin/dist_test.goindex eab38d193..6ab99cad9 100644--- a/internal/plugin/dist_test.go+++ b/internal/plugin/dist_test.go@@ -1,14 +1,21 @@package pluginimport (+ "bytes""context""crypto/sha512""encoding/base64""encoding/json"+ "errors"+ "io/fs"+ "maps""net/http""net/http/httptest""os"+ "os/exec""path/filepath"+ "regexp"+ "slices""strings""testing""time"@@ -176,6 +183,320 @@ func TestDistRefusesATarballNotItsIndexs(t *testing.T) {}}+// pruneDist keeps a tarball plugins/package.json names or bun.lock's+// packages has a package at, read as Bun writes them. gkd2323c's lock+// (#3622) had three packages at the tarballs before the ones package.json+// names, and c158b043 took those out; a package.json Bun 1.4.0 wrote names+// autoclaw twice, the new tarball first, which Bun reads, and c158b043 kept+// only the second. The tarball Bun 1.4.2 leaves in the lock's workspaces+// alone goes, as does one nothing names; with no bun.lock, package.json+// alone decides; with one that can't be read, nothing goes.+func TestDistTarballTheLockNamesStays(t *testing.T) {+ const (+ autoclaw = "magpie-community-opencode-autoclaw-auth-0.2.6.tgz"+ autoclawWas = "magpie-community-opencode-autoclaw-auth-0.2.1.tgz"+ cloudflare = "magpie-community-opencode-cloudflare-workers-ai-auth-0.0.3.tgz"+ cfWas = "magpie-community-opencode-cloudflare-workers-ai-auth-0.0.2.tgz"+ codearts = "magpie-community-opencode-codearts-auth-0.2.1.tgz"+ codeartsWas = "magpie-community-opencode-codearts-auth-0.2.0.tgz"+ unnamed = "magpie-community-opencode-autoclaw-auth-0.2.5.tgz"+ )+ // gkd2323c's package.json and lock: the lines #3622 quotes, in the+ // files Bun writes, the lock's workspaces as package.json (the issue+ // says they were)+ reported := `{+ "name": "magpie-plugins",+ "private": true,+ "dependencies": {+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz",+ "@magpie-community/opencode-cloudflare-workers-ai-auth": "./dist/magpie-community-opencode-cloudflare-workers-ai-auth-0.0.3.tgz",+ "@magpie-community/opencode-codearts-auth": "./dist/magpie-community-opencode-codearts-auth-0.2.1.tgz"+ }+}+`+ reportedLock := `{+ "lockfileVersion": 2,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "magpie-plugins",+ "dependencies": {+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz",+ "@magpie-community/opencode-cloudflare-workers-ai-auth": "./dist/magpie-community-opencode-cloudflare-workers-ai-auth-0.0.3.tgz",+ "@magpie-community/opencode-codearts-auth": "./dist/magpie-community-opencode-codearts-auth-0.2.1.tgz",+ },+ },+ },+ "packages": {+ "@magpie-community/opencode-autoclaw-auth": ["@magpie-community/opencode-autoclaw-auth@./dist/magpie-community-opencode-autoclaw-auth-0.2.1.tgz", {}, "sha512-..."],++ "@magpie-community/opencode-cloudflare-workers-ai-auth": ["@magpie-community/opencode-cloudflare-workers-ai-auth@./dist/magpie-community-opencode-cloudflare-workers-ai-auth-0.0.2.tgz", {}, "sha512-..."],++ "@magpie-community/opencode-codearts-auth": ["@magpie-community/opencode-codearts-auth@./dist/magpie-community-opencode-codearts-auth-0.2.0.tgz", {}, "sha512-..."],+ }+}+`+ // `bun add ./dist/<0.2.6>` over 0.2.1: Bun 1.4.2 writes package.json+ // so, Bun 1.4.0 with the package twice, and both write the lock below+ once := `{+ "name": "magpie-plugins",+ "private": true,+ "dependencies": {+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz"+ }+}+`+ twice := `{+ "name": "magpie-plugins",+ "private": true,+ "dependencies": {+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz",+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.1.tgz"+ }+}+`+ updatedLock := `{+ "lockfileVersion": 2,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "magpie-plugins",+ "dependencies": {+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz",+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.1.tgz",+ },+ },+ },+ "packages": {+ "@magpie-community/opencode-autoclaw-auth": ["@magpie-community/opencode-autoclaw-auth@./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz", {}, "sha512-63rE5gosmPjiHJlJZU3SImX8OBOk8pAKQHX5OAa5Ke2vaSlhVgDzmyPiiiXOJ2fCHMs8ty5cYoMhcOzeaDLhvA=="],+ }+}+`+ for _, c := range []struct {+ name, pj, lock string // lock: "" for none, "unreadable" for a folder in its place+ stay, gone []string+ }{+ {"the lock at the tarballs before", reported, reportedLock, []string{autoclaw, autoclawWas, cloudflare, cfWas, codearts, codeartsWas}, []string{unnamed}},+ {"package.json naming a package twice", twice, updatedLock, []string{autoclaw, autoclawWas}, []string{unnamed}},+ {"package.json naming a package twice, no lock", twice, "", []string{autoclaw, autoclawWas}, []string{unnamed}},+ {"the lock's workspaces alone naming one", once, updatedLock, []string{autoclaw}, []string{autoclawWas, unnamed}},+ // a shorter lock written over a longer one without truncating+ // (plugins#405's package.json): Bun reads the first object alone+ {"the lock with an older lock's tail past it", once, updatedLock + reportedLock[strings.Index(reportedLock, ` "@magpie-community/opencode-autoclaw-auth": [`):], []string{autoclaw}, []string{autoclawWas, unnamed}},+ {"no lock", reported, "", []string{autoclaw, cloudflare, codearts}, []string{autoclawWas, cfWas, codeartsWas, unnamed}},+ {"a lock that can't be read", reported, "unreadable", []string{autoclaw, autoclawWas, cloudflare, cfWas, codearts, codeartsWas, unnamed}, nil},+ } {+ t.Run(c.name, func(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("HOME", dir)+ t.Setenv("USERPROFILE", dir)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))+ if err := os.MkdirAll(filepath.Join(Dir(), "dist"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(Dir(), "package.json"), []byte(c.pj), 0o644); err != nil {+ t.Fatal(err)+ }+ switch c.lock {+ case "":+ case "unreadable":+ if err := os.Mkdir(filepath.Join(Dir(), "bun.lock"), 0o755); err != nil {+ t.Fatal(err)+ }+ default:+ if err := os.WriteFile(filepath.Join(Dir(), "bun.lock"), []byte(c.lock), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ for _, f := range append(slices.Clone(c.stay), c.gone...) {+ if err := os.WriteFile(filepath.Join(Dir(), "dist", f), []byte("tgz"), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ pruneDist()+ for _, f := range c.stay {+ if _, err := os.Stat(filepath.Join(Dir(), "dist", f)); err != nil {+ t.Errorf("%s taken out: %v", f, err)+ }+ }+ for _, f := range c.gone {+ if _, err := os.Stat(filepath.Join(Dir(), "dist", f)); !errors.Is(err, fs.ErrNotExist) {+ t.Errorf("%s kept (%v)", f, err)+ }+ }+ })+ }+}++// A bun.lock that has packages at tarballs package.json has moved on from,+// as gkd2323c's had autoclaw, codearts and cloudflare-workers-ai (#3622),+// is sent back to package.json before Bun runs. Bun installs what the lock+// has, at every add and removal of any plugin: from the older tarball,+// which pruneDist keeps now, or from its copy of one gone from+// plugins/dist, it put the older version back; with neither it failed each+// with "ENOENT extracting tarball". A Bun moved to 1.4.4 has no copy of+// those 1.4.2 and 1.4.3 made, as 1.4.4 keys its copies by the tarball's+// sha512 and they didn't. The state is made with real bun: the lock's+// packages given back the entries Bun wrote for the tarballs before, which+// pruneDist took when the newer were added, or which are put back. The+// packages stay at the versions package.json names, and package.json as it+// was. A package.json with bytes after its object (plugins#405) is cut+// first, as mendDist reads it.+func TestDistLockBehindPackageJSONIsMended(t *testing.T) {+ const (+ autoclaw = "@magpie-community/opencode-autoclaw-auth"+ codearts = "@magpie-community/opencode-codearts-auth"+ zcode = "@magpie-community/opencode-zcode-auth"+ )+ tarball := func(pkg, v string) string {+ return strings.ReplaceAll(strings.TrimPrefix(pkg, "@"), "/", "-") + "-" + v + ".tgz"+ }+ for _, c := range []struct {+ name string+ copiesGone, tarballsKept, tail bool+ }{+ {"Bun's copies of the tarballs kept", false, false, false},+ {"Bun's copies of the tarballs gone", true, false, false},+ {"the tarballs kept", false, true, false},+ {"Bun's copies gone, package.json with a tail", true, false, true},+ } {+ t.Run(c.name, func(t *testing.T) {+ sandbox(t)+ npmHasNothing(t)+ fakeDist(t, map[string][]string{autoclaw: {"0.2.1", "0.2.6"}, codearts: {"0.2.0", "0.2.1"}, zcode: {"0.1.30"}}, false)+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ lockPath := filepath.Join(Dir(), "bun.lock")+ readLock := func() []byte {+ t.Helper()+ b, err := os.ReadFile(lockPath)+ if err != nil {+ t.Fatal(err)+ }+ return b+ }+ // the package's entry in the lock's packages, the line Bun writes+ entry := func(lock []byte, pkg string) []byte {+ t.Helper()+ m := regexp.MustCompile(`(?m)^[ \t]*"` + regexp.QuoteMeta(pkg) + `": \[.*$`).Find(lock)+ if m == nil {+ t.Fatalf("bun.lock's packages have no %s:\n%s", pkg, lock)+ }+ return m+ }+ specs := func() map[string]string {+ t.Helper()+ b, err := os.ReadFile(filepath.Join(Dir(), "package.json"))+ if err != nil {+ t.Fatal(err)+ }+ var pj struct{ Dependencies map[string]string }+ if err := json.Unmarshal(b, &pj); err != nil {+ t.Fatal(err)+ }+ return map[string]string{autoclaw: pj.Dependencies[autoclaw], codearts: pj.Dependencies[codearts]}+ }+ before := map[string]string{autoclaw: "0.2.1", codearts: "0.2.0"}+ want := map[string]string{autoclaw: "0.2.6", codearts: "0.2.1"}+ was, wasTgz := map[string][]byte{}, map[string][]byte{}+ for _, at := range []map[string]string{before, want} {+ for _, pkg := range []string{autoclaw, codearts} {+ if err := installAt(ctx, pkg, at[pkg]); err != nil {+ t.Fatalf("installAt %s %s: %v", pkg, at[pkg], err)+ }+ }+ if len(was) == 0 {+ for _, pkg := range []string{autoclaw, codearts} {+ was[pkg] = entry(readLock(), pkg)+ b, err := os.ReadFile(filepath.Join(Dir(), "dist", tarball(pkg, before[pkg])))+ if err != nil {+ t.Fatal(err)+ }+ wasTgz[pkg] = b+ }+ }+ }+ pj := specs()+ breakLock := func() {+ t.Helper()+ b := readLock()+ for pkg, old := range was {+ f := filepath.Join(Dir(), "dist", tarball(pkg, before[pkg]))+ if _, err := os.Stat(f); !errors.Is(err, fs.ErrNotExist) {+ t.Fatalf("%s is still in plugins/dist (%v)", tarball(pkg, before[pkg]), err)+ }+ if c.tarballsKept {+ if err := os.WriteFile(f, wasTgz[pkg], 0o644); err != nil {+ t.Fatal(err)+ }+ }+ b = bytes.Replace(b, entry(b, pkg), old, 1)+ }+ if err := os.WriteFile(lockPath, b, 0o644); err != nil {+ t.Fatal(err)+ }+ if c.tail {+ // what plugins#405's bun remove left after the object+ f, err := os.OpenFile(filepath.Join(Dir(), "package.json"), os.O_APPEND|os.O_WRONLY, 0)+ if err != nil {+ t.Fatal(err)+ }+ _, err = f.WriteString("@magpie-community/opencode-zcode-auth\": \"^0.1.27\"\n }\n}\n")+ if cerr := f.Close(); err == nil {+ err = cerr+ }+ if err != nil {+ t.Fatal(err)+ }+ }+ if c.copiesGone {+ if err := os.RemoveAll(installCacheDir()); err != nil {+ t.Fatal(err)+ }+ }+ }+ mended := func(after string) {+ t.Helper()+ b := readLock()+ for pkg, v := range want {+ if got := Installed(pkg); got != v {+ t.Errorf("after %s, %s is at %q, want %s", after, pkg, got, v)+ }+ if !bytes.Contains(entry(b, pkg), []byte(pkg+"@./dist/"+tarball(pkg, v)+`"`)) || bytes.Contains(b, []byte(tarball(pkg, before[pkg]))) {+ t.Errorf("after %s, bun.lock doesn't have %s at %s alone:\n%s", after, pkg, v, b)+ }+ }+ if got := specs(); !maps.Equal(got, pj) {+ t.Errorf("after %s, package.json has %v, was %v", after, got, pj)+ }+ }++ breakLock()+ if _, err := Add(ctx, zcode); err != nil {+ t.Fatalf("Add with the lock behind package.json: %v", err)+ }+ if v := Installed(zcode); v != "0.1.30" {+ t.Fatalf("zcode installed %q", v)+ }+ mended("the add")+ for pkg := range was {+ if _, err := os.Stat(filepath.Join(Dir(), "dist", tarball(pkg, before[pkg]))); !errors.Is(err, fs.ErrNotExist) {+ t.Errorf("after the add, %s is still in plugins/dist (%v)", tarball(pkg, before[pkg]), err)+ }+ }++ breakLock()+ if err := Remove(ctx, zcode); err != nil {+ t.Fatal(err)+ }+ if b, _ := os.ReadFile(filepath.Join(Dir(), "package.json")); bytes.Contains(b, []byte(zcode)) {+ t.Fatalf("plugins/package.json still names zcode after Remove:\n%s", b)+ }+ mended("the removal")+ })+ }+}+func TestDistWanted(t *testing.T) {for spec, want := range map[string]string{"@magpie-community/opencode-zed-auth": "@magpie-community/opencode-zed-auth latest",@@ -203,3 +524,64 @@ func TestDistWanted(t *testing.T) {}}}++// A lock with an older lock's bytes past its object (a shorter one written+// over a longer one without truncating, as plugins#405's package.json) is+// read as Bun reads it, its first object: the tail's older tarball isn't+// sent to bun update at every command, while the same tarball in the+// object still is.+func TestDistLockTailIsntRead(t *testing.T) {+ const pj = `{+ "name": "magpie-plugins",+ "private": true,+ "dependencies": {+ "@magpie-community/opencode-autoclaw-auth": "./dist/magpie-community-opencode-autoclaw-auth-0.2.6.tgz"+ }+}+`+ at := func(file string) string {+ return `{+ "lockfileVersion": 2,+ "packages": {+ "@magpie-community/opencode-autoclaw-auth": ["@magpie-community/opencode-autoclaw-auth@./dist/` + file + `", {}, "sha512-..."],+ }+}+`+ }+ const now, was = "magpie-community-opencode-autoclaw-auth-0.2.6.tgz", "magpie-community-opencode-autoclaw-auth-0.2.1.tgz"+ old := at(was)+ for _, c := range []struct {+ name, lock string+ update bool+ }{+ {"an older lock's tail past it", at(now) + old[strings.Index(old, ` "@magpie-community/`):], false},+ {"the object behind", at(was), true},+ {"a tail with braces and quotes in its strings", strings.Replace(at(now), `"sha512-..."`, `"}\"{]"`, 1) + old[strings.Index(old, ` "@magpie-community/`):], false},+ } {+ t.Run(c.name, func(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("HOME", dir)+ t.Setenv("USERPROFILE", dir)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))+ if err := os.MkdirAll(filepath.Join(Dir(), "dist"), 0o755); err != nil {+ t.Fatal(err)+ }+ for name, body := range map[string]string{"package.json": pj, "bun.lock": c.lock, filepath.Join("dist", now): "tgz"} {+ if err := os.WriteFile(filepath.Join(Dir(), name), []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ var ran [][]string+ was := bunCommand+ t.Cleanup(func() { bunCommand = was })+ bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exec.Cmd {+ ran = append(ran, args)+ return exec.CommandContext(ctx, filepath.Join(dir, "no-such-bun"))+ }+ mendDist(context.Background(), "bun")+ if got := len(ran) > 0; got != c.update {+ t.Fatalf("bun update run: %v, want %v (%q)", got, c.update, ran)+ }+ })+ }+}diff --git a/internal/plugin/store.go b/internal/plugin/store.goindex 0e665d78e..0634122ce 100644--- a/internal/plugin/store.go+++ b/internal/plugin/store.go@@ -87,6 +87,7 @@ func runBun(ctx context.Context, bun string, args ...string) ([]byte, error) {defer installMu.Unlock()mendPackageJSON()defer mendPackageJSON()+ mendDist(ctx, bun)return bunCommand(ctx, bun, Dir(), args...).CombinedOutput()}@@ -745,7 +746,9 @@ func install(ctx context.Context, spec string) error {installMu.Lock()pj := filepath.Join(Dir(), "package.json")if _, err := os.Stat(pj); err != nil {- if err := os.WriteFile(pj, []byte("{\n \"name\": \"magpie-plugins\",\n \"private\": true\n}\n"), 0o644); err != nil {+ // through temp and rename, as every write of it: a write cut+ // short would leave bun a package.json it can't read+ if err := edit.WriteAtomic(pj, []byte("{\n \"name\": \"magpie-plugins\",\n \"private\": true\n}\n")); err != nil {installMu.Unlock()return err}@@ -753,6 +756,7 @@ func install(ctx context.Context, spec string) error {defer installMu.Unlock()mendPackageJSON()defer mendPackageJSON()+ mendDist(ctx, bun)err = bunAdd(ctx, bun, spec)// a @magpie-community package or version npm doesn't have (a new// one waits for an owner to publish it there) comes from the