Files
magpie/internal/proc/nodever_other.go
T
yetone 6b8dc4cdd8 proc, agent: magpie finds an agent CLI under the Node nvm's default names, not the folder whose name sorts last (v9 after v22)
proc.UserPath added "the newest-looking" nvm Node to magpie's PATH, the
last folder of ~/.nvm/versions/node/*/bin in string order. That isn't
the Node a terminal gets, and string order puts v9.11.2 after v22.12.0
and v22.3.0 after v22.12.0. So magpie could find, run and update a
codex/claude/gemini under a Node the user's terminal doesn't use (found
while answering 悠悠哥 on Discord, 9f407cafa). UserBinDirs (FindTool,
the Codex executable, nodeHere) took every version in reverse name
order, with the same flaw.

Now (internal/proc/nodever_other.go) the nvm folder is $NVM_DIR or
~/.nvm, and its default is resolved as nvm.sh does on load (nvm_auto
use -> nvm_resolve_local_alias default, read from nvm v0.40.3's
source): alias/default and each alias it names in turn (lts/* ->
lts/jod -> v22.x, lts/-N as nvm_normalize_lts counts it, user aliases),
a cycle being none; node/stable the highest installed; a partial
version (22, v20, 22.3) the highest installed it starts; an exact one
when its bin/node is installed. UserPath adds that one; with no usable
default (unset, not installed, cycle, iojs/unstable) the highest
version by number; with "system" none of nvm's, since the terminal then
runs the system Node. UserBinDirs lists the default first, then the
rest highest first.

Siblings:
- mise's installs and fnm's node-versions (UserBinDirs only) were in
  reverse name order too: now by number, fnm's aliases/default first
  (and $FNM_DIR looked in). mise's active Node is reached through its
  shims, which come earlier.
- volta, asdf and mise shims, and n (one copy in /usr/local/bin), pick
  the version themselves: no change.
- Windows (path_windows.go) lists no per-version folder: nvm-windows'
  current Node is its NVM_SYMLINK on the registry PATH. No change.
- The WSL probe's wslbin (internal/agent/wsl.go) globbed
  "$HOME"/.nvm/versions/node/*/bin, first in name order (v18 before the
  default v22). It now asks nvm itself (nvm.sh sourced by bash with
  --no-use, nvm_version default), then the rest highest first.
- NVM_DIR and FNM_DIR join agentenv.Vars: test sandboxes clear them, and
  UserPath takes them from the login shell like the agents' variables.

Run: TestUserPathNvmDefault (15 real nvm layouts: v9 vs v22, lts/*,
lts/iron, lts/-1, 22, v20, exact v9, node, stable, a user alias, a
default not installed, lts/* naming a line not installed, a cycle,
system direct and through an alias), TestFindToolNvmDefaultFirst,
TestUserPathNvmDir, TestUserBinDirsFnmMise, TestWSLProbeNvmDefault.
With the old path_other.go 14 of the 15 nvm cases go red (v9.11.2
picked; the exact-v9 default passes), as do the other three; with the
default ignored by hand 9 go red; with the old probe line all 3 WSL
cases go red. Cross-checked nvmDefault against
nvm v0.40.3's own nvm_version default on 19 alias layouts: same version
each time (nvm says N/A where magpie falls back, and N/A for system
with no system node). The new probe run with the real nvm.sh under
/bin/sh and /bin/dash resolved lts/*, lts/iron and 18 right. go test
./internal/proc ./internal/agent ./internal/agentenv ./internal/provider
./internal/testenv; full go test -tags nogui ./...; gofmt -l; go vet,
GOOS=linux and GOOS=windows go vet -tags nogui on the touched packages.
All under a temp HOME; no real ~/.nvm read.
2026-10-11 06:41:06 +08:00

243 lines
7.2 KiB
Go

//go:build !windows
package proc
import (
"os"
"path/filepath"
"slices"
"strconv"
"strings"
)
// A Node version manager keeps one folder per version, and a terminal runs
// the one it was told to use, not the one whose name sorts last. magpie
// picked nvm's "newest-looking" folder by name, and in plain string order
// v9.11.2 comes after v22.12.0: a codex, claude or gemini installed under a
// Node the terminal doesn't use was found, run and updated in place of the
// terminal's (found while answering 悠悠哥 on Discord, 9f407cafa). The
// folders are taken in the order a terminal would reach them instead: the
// manager's default first, then the highest version.
// nvmDir is nvm's folder: $NVM_DIR as the profile sets it, else ~/.nvm.
func nvmDir(home string) string {
if d := os.Getenv("NVM_DIR"); filepath.IsAbs(d) {
return d
}
if home == "" {
return ""
}
return filepath.Join(home, ".nvm")
}
// nvmBins are the bin folders of the Node versions nvm keeps in dir, the
// one a terminal gets first (nvmDefault), then the rest newest first.
// system is true when nvm's default is the system's Node, which a
// terminal then runs, and none of these.
func nvmBins(dir string) (bins []string, def string, system bool) {
root := filepath.Join(dir, "versions", "node")
names := nodeVersions(root, "bin")
def, system = nvmDefault(dir, names)
for _, n := range names {
bins = append(bins, filepath.Join(root, n, "bin"))
}
if def != "" {
def = filepath.Join(root, def, "bin")
bins = slices.DeleteFunc(bins, func(b string) bool { return b == def })
bins = append([]string{def}, bins...)
}
return bins, def, system
}
// nodeVersions are the names of the version folders under root that have
// a folder bin (root/<version>/<bin>), highest version first (nodeVersionLess); a name that is
// no version (mise's "lts", "latest") after every one that is.
func nodeVersions(root, bin string) []string {
es, _ := os.ReadDir(root)
var names []string
for _, e := range es {
if st, err := os.Stat(filepath.Join(root, e.Name(), bin)); err == nil && st.IsDir() {
names = append(names, e.Name())
}
}
slices.SortStableFunc(names, func(a, b string) int {
switch {
case nodeVersionLess(b, a):
return -1
case nodeVersionLess(a, b):
return 1
}
return strings.Compare(a, b)
})
return names
}
// parseNodeVersion reads v22.12.0 (or 22.12.0, mise's, or 22, a partial
// one) as its numbers; false for a name that isn't one.
func parseNodeVersion(s string) ([3]int, int, bool) {
var v [3]int
parts := strings.Split(strings.TrimPrefix(s, "v"), ".")
if len(parts) > 3 || parts[0] == "" {
return v, 0, false
}
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 {
return v, 0, false
}
v[i] = n
}
return v, len(parts), true
}
// nodeVersionLess says a is a lower version than b, by number: v9 before
// v22. A name that is no version is lower than one that is.
func nodeVersionLess(a, b string) bool {
va, _, oka := parseNodeVersion(a)
vb, _, okb := parseNodeVersion(b)
if oka != okb {
return okb
}
return oka && slices.Compare(va[:], vb[:]) < 0
}
// nvmDefault is the installed version (one of names, highest first) nvm's
// default alias resolves to, as nvm.sh does when a shell loads it
// (nvm_auto use → nvm_resolve_local_alias default): alias/default, then
// each alias it names in turn (lts/* → lts/jod → v22.20.0, node, stable),
// a cycle being none; "node" and "stable" the highest installed; a partial
// version (22, v22.1) the highest installed that it starts; a full one
// itself when it is installed (its bin/node there). "" when the default
// isn't set or names nothing installed (nvm then puts no Node on PATH), or
// is the system's Node, which system says.
func nvmDefault(dir string, names []string) (string, bool) {
alias := filepath.Join(dir, "alias")
cur, seen := "default", map[string]bool{"default": true}
for {
next := nvmAlias(alias, cur)
if next == "" {
break
}
if seen[next] {
return "", false // nvm's ∞
}
seen[next] = true
cur = next
}
if cur == "default" {
return "", false
}
installed := func(n string) bool {
st, err := os.Stat(filepath.Join(dir, "versions", "node", n, "bin", "node"))
return err == nil && !st.IsDir() && st.Mode()&0o111 != 0
}
switch cur {
case "system":
return "", true
case "node", "stable":
for _, n := range names {
if _, _, ok := parseNodeVersion(n); ok && strings.HasPrefix(n, "v") {
return n, false
}
}
return "", false
}
// nvm_ensure_version_prefix: 22 → v22
if cur[0] >= '0' && cur[0] <= '9' {
cur = "v" + cur
}
if _, parts, ok := parseNodeVersion(cur); !ok || !strings.HasPrefix(cur, "v") {
return "", false // iojs, unstable, N/A, ∞: no Node of versions/node
} else if parts == 3 {
if installed(cur) {
return cur, false
}
return "", false
}
// nvm_ls v22 matches v22.*, v22.1 matches v22.1.*, newest last
for _, n := range names {
if strings.HasPrefix(n, strings.TrimSuffix(cur, ".")+".") {
return n, false
}
}
return "", false
}
// nvmAlias is what nvm's alias name holds, nvm_alias: the first line of
// alias/<name> with something on it, after nvm_normalize_lts turns
// lts/-1 into the LTS line before the newest. "" when there is no such
// alias.
func nvmAlias(alias, name string) string {
if n, ok := strings.CutPrefix(name, "lts/-"); ok {
k, err := strconv.Atoi(n)
if err != nil || k < 1 {
return ""
}
es, _ := os.ReadDir(filepath.Join(alias, "lts"))
var ls []string
for _, e := range es {
ls = append(ls, e.Name())
}
slices.Sort(ls) // `ls`, whose order nvm takes
i := len(ls) - (k + 1)
if i < 0 {
i = 0
}
if len(ls) == 0 || ls[i] == "*" {
return ""
}
name = "lts/" + ls[i]
}
if name == "" || strings.Contains(name, "..") {
return ""
}
b, err := os.ReadFile(filepath.Join(alias, filepath.FromSlash(name)))
if err != nil {
return ""
}
for _, l := range strings.Split(string(b), "\n") {
if l = strings.TrimSpace(l); l != "" {
return l
}
}
return ""
}
// fnmBins are the bin folders of the Node versions fnm keeps in dir, the
// default alias's (aliases/default, a link to the version's folder) first,
// then the rest newest first.
func fnmBins(dir string) []string {
root := filepath.Join(dir, "node-versions")
var bins []string
for _, n := range nodeVersions(root, filepath.Join("installation", "bin")) {
bins = append(bins, filepath.Join(root, n, "installation", "bin"))
}
if to, err := filepath.EvalSymlinks(filepath.Join(dir, "aliases", "default")); err == nil {
if real, err := filepath.EvalSymlinks(root); err == nil {
if rel, err := filepath.Rel(real, to); err == nil && !strings.HasPrefix(rel, "..") {
def := filepath.Join(root, rel, "bin")
if isDir(def) {
bins = slices.DeleteFunc(bins, func(b string) bool { return b == def })
bins = append([]string{def}, bins...)
}
}
}
}
return bins
}
// nodeBins are the bin folders of a manager that keeps each version as
// root/<version>/bin (mise's installs), newest first.
func nodeBins(root string) []string {
var bins []string
for _, n := range nodeVersions(root, "bin") {
bins = append(bins, filepath.Join(root, n, "bin"))
}
return bins
}
func isDir(p string) bool {
st, err := os.Stat(p)
return err == nil && st.IsDir()
}