Skip to content

fix(manager,pathmeta,doctor,shell): isolate downloads, validate names, match plugin mode, keep env quiet, surface path diagnostics, and sort shell env - #827

Merged
linghengqian merged 16 commits into
version-fox:mainfrom
aloneangel45:fix/825-create-vfox-home
Nov 24, 2026

Conversation

@aloneangel45

@aloneangel45 aloneangel45 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #825

Summary

  • Writable plugin directory preflight, traversal checks, safe staging, and shared permissions (internal/manager.go, internal/plugin/plugin.go, internal/plugin/wrapper.go):
    • Export plugin.IsValidName and validate --alias and explicit plugin names up front in Manager.Add before any download or filesystem access, blocking path-traversal aliases such as --alias ../../../outside.
    • Check ensureWritableDir(pluginsDir) (os.MkdirAll + temp write probe with explicit Close/Remove error checks and sanitized preparePluginDirError messages naming VFOX_HOME) before registry lookups/downloads for named/aliased installs, and before moving unnamed --source downloads into plugin/.
    • Download remote unnamed --source archives in downloadPlugin (os.O_CREATE|os.O_WRONLY) into a private vfox-dl-* staging subdirectory under User.Temp, check plugin name / "already exists" before moving, match the installed plugin directory permissions to plugin/ (os.Stat(pluginsDir) -> os.Chmod) before MovePath so shared VFOX_HOME installs are not stuck 0700, copy local .lua sources with util.CopyFile instead of os.Rename so the caller's source file stays intact, and sweep vfox-dl-* entries older than 24h in Manager.CleanTmp.
    • Sanitize URL-derived filenames in pluginFileName / isSafePluginFileName (\ -> /, rejecting control/invalid characters and Windows reserved device names CON, PRN, AUX, NUL, COM0–COM9, COM¹–COM³, LPT0–LPT9, LPT¹–LPT³ before the first dot, falling back to "plugin" + ext).
  • Quiet read-path initialization with single temp-error log & doctor/use diagnostics (internal/pathmeta/path_meta.go, internal/sdk/finding.go, internal/manager.go, internal/manager_doctor.go, cmd/commands/use.go):
    • Keep NewPathMeta non-recursive on Shared.Installs and Shared.Plugins (os.Mkdir guarded by util.FileExists(meta.Shared.Root)), and log failed shared subdir creation only at debug level without recording InitErrors, so read-only shared VFOX_HOME roots with missing plugin/ or cache/ leave doctor and use free of false path.unusable diagnostics while write paths (Manager.Add / acquireInstallLock) still create and validate them.
    • Drop unused error return from NewPathMeta, create User.Temp / SessionSdkDir in a single coordinated helper (ensureUserTempDirs) so "create temp dir failed:" is logged at most once even when __VFOX_CURTMPPATH is set under an unusable User.Temp, and route NewPathMeta, getExecutablePath, and getWorkingDirectory failures to logger.Debugf so env and activate stdout/stderr remain clean on normal runs.
    • Record user-path and executable PathMeta.InitErrors plus Manager.workingDirErr and expose them as sdk.FindingPathUnusable ("path.unusable") diagnostics in Manager.Diagnose (vfox doctor / vfox doctor --json) and useCmd (vfox use, honoring diagnostics.onUse and diagnostics.ignore) — matching AGENTS.md ("Diagnostics belong to use and doctor, never to activate or env"). Unlike base, non-diagnostic commands such as vfox list no longer emit NewPathMeta errors unless --debug is set.
  • Documentation (docs/usage/core-commands.md, docs/zh-hans/usage/core-commands.md, docs/guides/multi-user-sharing.md, docs/zh-hans/guides/multi-user-sharing.md):
    • Document the path.unusable finding in both English and zh-hans doctor tables.
    • Update shared VFOX_HOME setup guides from plugins/ to plugin/ (matching pluginDirPrefix = "plugin" and configuration.md).
  • Deterministic shell environment exports (internal/shell/): sort environment variable keys via sortedEnvKeys across bash, zsh, fish, powershell, clink, and nushell so vfox activate and vfox env output stays identical across runs.
  • Tests: expanded internal/manager_test.go (using atomic.Int32 for HTTP hit tracking), internal/manager_doctor_test.go, internal/pathmeta/path_meta_test.go, cmd/commands/add_cli_test.go, and cmd/commands/env_readonly_test.go (runInProcessCaptured uses t.Chdir(f.work) and temp files; read-only shared VFOX_HOME coverage includes doctor and use in an activated shell when plugin/ or cache/ is absent).

Verification

Observed locally on Windows at 93592a4 (VFOX_TEST_WINDOWS_REGISTRY=1; POSIX chmod 0555 permission subtests are skipped on Windows and run on CI Linux/macOS):

  • gofmt -l, gofmt -s -w on PR-edited files (keeping internal/manager.go's unrelated ParseLegacyFile loop unchanged), git diff --check, 3-OS go vet ./..., and linux/darwin go test -c ./cmd/commands — clean
  • go test -race -count=1 ./internal ./internal/pathmeta ./internal/plugin ./internal/sdk ./internal/shell ./cmd ./cmd/commands — passed (2.251s, 2.018s, 3.817s, 4.141s, 12.155s, 16.687s, 104.128s)

@linghengqian linghengqian added this to the 1.1.1 milestone Nov 23, 2026
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.85202% with 65 lines in your changes missing coverage. Please review.
✅ Project coverage is 60.75%. Comparing base (90a96e1) to head (f2d31dc).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/manager.go 61.94% 28 Missing and 15 partials ⚠️
internal/manager_doctor.go 65.71% 11 Missing and 1 partial ⚠️
internal/pathmeta/path_meta.go 96.15% 1 Missing and 1 partial ⚠️
internal/shell/bash.go 0.00% 2 Missing ⚠️
internal/shell/fish.go 0.00% 2 Missing ⚠️
internal/shell/powershell.go 0.00% 2 Missing ⚠️
internal/shell/zsh.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #827      +/-   ##
==========================================
+ Coverage   59.57%   60.75%   +1.18%     
==========================================
  Files         124      124              
  Lines        9061     9235     +174     
==========================================
+ Hits         5398     5611     +213     
+ Misses       3181     3126      -55     
- Partials      482      498      +16     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The #825 case works now. A missing VFOX_HOME gets created, and a VFOX_HOME that sits under a regular file fails before the download with a message that names VFOX_HOME. I checked this on Linux with Go 1.27.3, comparing the base commit with this branch.

I found regressions in other commands, so I am requesting changes.

  1. NewPathMeta now returns an error when cache/ or plugin/ under VFOX_HOME cannot be created. It runs before storage.sdkPath is applied, and NewSdkManager has 27 call sites in cmd/commands (env, activate, cd, current, list and others). When VFOX_HOME is not writable for the user and does not have cache/ or plugin/ yet, these commands now fail. vfox env -s bash exits 0 on base and prints the PATH export; on this branch it exits 1 with no output. vfox activate bash exits 0 on base with 674 bytes of output; on this branch it exits 1 with no output, so the shell gets no activation code. The same happens when storage.sdkPath points to a writable directory in ~/.vfox/config.yaml: base applies it and creates the directory, while this branch fails before the config is read.

  2. The new logger.Errorf calls in NewPathMeta print to stdout (logger uses fmt.Printf), and the output of vfox env is evaluated by the shell. If ~/.vfox/sdks cannot be created, the message has no trailing newline and is joined to the export PATH=... line. In bash, the message runs as a command and the PATH export is lost. I checked this: after eval, PATH is unchanged on this branch and updated on base. The temp directory message was already printed in that situation on base, through generateSessionShimPath; this branch adds a second copy. AGENTS.md asks that unrelated output stay out of generated shell code and that env get no new checks.

  3. The new tests do not reach these paths. None of them uses a read-only VFOX_HOME with missing subdirectories, a storage.sdkPath override, or the stdout of env. The blocked-VFOX_HOME test fails inside NewSdkManager, so the error branch in Manager.Add is never reached, and Codecov reports 11 patch lines without coverage. TestNewPathMetaSharedDirectories/returns error when shared root cannot be created asserts the behavior described in item 1.

One direction, which is your call: keep NewPathMeta best-effort as it was, change the new logs to logger.Debugf, and rely on the check that Manager.Add already makes before any download. I tried this in a scratch copy, not on this branch. The #825 cases pass, env, activate, list and the storage.sdkPath case behave as on base, env stdout stays clean, and the blocked-download test still passes. Only the test that asserts NewPathMeta returns an error fails, and that test would have to change. Creating the shared directories only in commands that write, after the storage path is applied, would also work.

Whichever approach you choose, please add tests for:

  • a read-only VFOX_HOME without cache/ and plugin/: env and activate succeed with the same output as before;
  • a read-only VFOX_HOME with storage.sdkPath set: the override is used;
  • env stdout when the global SDK directory cannot be created: only shell code is printed;
  • a blocked VFOX_HOME: the Manager.Add error path is reached and no download happens.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review @linghengqian! Addressed all three points in commit 10a09b6:

  1. Reverted pathmeta.NewPathMeta to stay best-effort when creating Temp, GlobalSdkDir, Installs, and Plugins so read paths (env, activate, list, current) succeed on a read-only VFOX_HOME and storage.sdkPath from config still applies afterwards.
  2. Switched NewPathMeta directory-creation warnings to logger.Debugf (and dropped the unreachable error wrapper in NewSdkManager) so vfox env stdout emits only shell code when GlobalSdkDir cannot be created.
  3. Updated internal/pathmeta/path_meta_test.go and added tests in cmd/commands/add_cli_test.go covering clean env stdout when GlobalSdkDir is blocked, Manager.Add reaching prepare plugin directory with 0 HTTP requests on a blocked VFOX_HOME, and (on Unix runners) env/activate parity and storage.sdkPath override behavior on a read-only 0555 VFOX_HOME. CI will verify the POSIX permission subtests directly on Linux/macOS.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge yet. The missing-directory case from #825 works now, and env and activate on a read-only VFOX_HOME behave like base. All four points below block the merge.

  1. The new activate comparison is flaky. activate builds its export list by ranging over maps (cmd/commands/activate.go:178 and :219), so the order of the statements changes between runs. base does the same, so the test has to stop depending on order. The subtest "read-only VFOX_HOME without cache or plugin keeps env and activate identical" failed 13 times out of 30 for me:

    go test -count=30 ./cmd/commands -run TestReadOnlyAndBlockedVfoxHomeReadPaths

    Compare the statements as a sorted set (split on ";", then sort), or sort the keys in activate so the output is stable.

  2. generateSessionShimPath still writes to stdout. internal/pathmeta/path_meta.go:168 calls logger.Errorf without a trailing newline, and NewPathMeta calls it. When ~/.vfox/tmp cannot be created, vfox env -s bash prints "create temp dir failed: ...directoryexport PATH=...", and eval does not apply the PATH. The commit message says NewPathMeta is silent on directory errors, which is not true for this path. Changing the call to logger.Debugf("create temp dir failed: %v\n", err) fixes it; I checked that on a scratch copy. The silent test only blocks GlobalSdkDir and the shared directories, so it cannot see this. Please add a case that blocks the session temp directory and checks that the stdout of env -s bash is only shell code.

  3. An existing plugin directory that is not writable still fails after the download. Manager.Add only calls MkdirAll, which returns nil for an existing directory whatever its permissions. With VFOX_HOME/plugin set to 0555, vfox add --source <url> sends the request and then fails with "download wrapper error: open .../plugin/demo.zip: permission denied". VFOX_HOME is not named, and the failure comes after the download. That is the symptom #825 describes, and the shared VFOX_HOME setup in docs/guides/multi-user-sharing.md makes it a normal case. Check that the directory is writable before downloading (creating and removing a temp file is enough), and return the same "prepare plugin directory" error that names VFOX_HOME. Add a test with a 0555 plugin directory that asserts zero requests.

  4. The title and description describe the first version of the change. NewPathMeta no longer returns errors, NewSdkManager is not modified, and the verification section only mentions a local Windows run that was not updated for the last commit. The title says "surface errors", but only Manager.Add reports them now. Please update the title and body before merge, since the title becomes the commit message on squash.

I ran go vet, gofmt and go test ./... on Linux with Go 1.27.3. The full suite failed in some of my runs, and the failure I captured was the test from item 1.

@aloneangel45 aloneangel45 changed the title fix(pathmeta): create VFOX_HOME directories recursively and surface errors fix(pathmeta,manager): check writable plugin dir in Manager.Add and keep NewPathMeta quiet Nov 23, 2026
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for catching all four issues — addressed in commit 3fc868e and updated the PR title/description:

  1. Order-independent activate comparison (cmd/commands/add_cli_test.go): Added sortSemicolonStatements (splits on ;, trims whitespace, sorts) and switched the activate assertion to slices.Equal(sortSemicolonStatements(...)) so Go map iteration order no longer flakes across -count=30.
  2. Quiet generateSessionShimPath (internal/pathmeta/path_meta.go:168): Changed logger.Errorf("create temp dir failed: %v", err) to logger.Debugf("create temp dir failed: %v\n", err), and added tests blocking ~/.vfox/tmp (with __VFOX_CURTMPPATH unset) in both TestNewPathMetaSharedDirectories and TestReadOnlyAndBlockedVfoxHomeReadPaths (env -s bash stdout matches baseline shell code).
  3. Pre-download writability probe for existing non-writable plugin/ (internal/manager.go): Added ensureWritableDir (os.MkdirAll + os.CreateTemp write/remove probe) in Manager.Add so an existing 0555 VFOX_HOME/plugin fails immediately with prepare plugin directory ... (VFOX_HOME=...) before any download/manifest request, with a 0555 httptest.NewServer (hits.Load() == 0) regression test in TestAddSourceMissingVfoxHome.
  4. Updated PR title & body: Removed outdated NewPathMeta error-return / NewSdkManager claims and recorded the current checks (0555 subtests verified on CI since POSIX 0555 skips on Windows).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge. Please fix the items below and request review again.

What I checked on 3fc868e: gofmt and go vet are clean, go test ./... passes on Linux, and the new tests pass with -count=20. #825 is fixed: a missing VFOX_HOME is created, and a VFOX_HOME under a regular file fails before the download with a message that names VFOX_HOME. I also reintroduced the old stdout write in generateSessionShimPath and removed the writability check in Manager.Add. The tests failed both times, so they do cover what they claim.

Blocking

  1. An installed plugin now gets the wrong error when plugin/ is read-only. internal/manager.go:545-559: the probe runs before the "already exists" check. With VFOX_HOME/plugin at 0555 and demo already installed:

    vfox add demo
    # before: plugin named demo already exists
    # now:    prepare plugin directory ".../plugin" (VFOX_HOME=...): open .../.vfox-write-check-...: permission denied
    

    vfox add --source demo.zip shows the same change. With the guide's chmod 2775 /opt/vfox (docs/guides/multi-user-sharing.md, line 35), users outside the group only have read access, and line 290 says other users need read access. So this state is normal there. No test covers it. Check the existing name first. For a local source, run the probe after the existing-plugin check and before the move. Add a test with a 0555 plugin dir and an installed plugin that expects "already exists".

  2. NewPathMeta still writes to stdout. internal/pathmeta/path_meta.go:177 calls logger.Errorf with no trailing newline, and logger.Errorf always prints. NewPathMeta reaches it through getExecutablePath at line 139. When /proc is unavailable, vfox env -s bash prints get executable path failed: readlink /proc/self/exe: no such file or directoryexport PATH=.... Evaluating that output leaves PATH unchanged (get: command not found). Use logger.Debugf with \n. A package-level var executable = os.Executable would let a test force the error. The title's "keep NewPathMeta quiet" depends on this change.

  3. Read commands now create VFOX_HOME trees. path_meta.go:144-154 uses MkdirAll for Installs and Plugins. The base used os.Mkdir, which creates them only when the parent exists. On this branch, VFOX_HOME=/tmp/typo/a/b vfox env -s bash creates plugin/ and cache/, and env runs at every prompt. The base creates nothing. The PR body says read commands stay unaffected and does not mention this. Pick one: keep the old semantics for read paths, or leave creation to the write paths. Install already creates its lock directory through acquireInstallLock (internal/sdk/install_lock.go:29, called from internal/sdk/sdk.go:292), and Manager.Add creates plugin/ itself. If you keep MkdirAll, say so in the body. The test "creates missing shared root and nested parents" changes with either choice.

  4. ensureWritableDir drops errors silently. internal/manager.go:515-516 ignores probe.Close() and os.Remove with _ = and no comment. AGENTS.md asks for errors to be handled, or for best-effort cleanup to be explained. If Remove fails, the probe file stays in plugin/. Handle the errors, or comment them and say what remains.

Not blocking

  • The activate comparison now ignores statement order (sortSemicolonStatements). The source of the nondeterminism is map iteration at cmd/commands/activate.go:178 and :219. Sorting the keys in the renderer would let the test compare exactly. This can be a follow-up.
  • add_cli_test.go also holds the env and activate tests. A name like env_readonly_test.go would fit better.

Not counted against this PR

downloadPlugin opens plugin/<file> with O_CREATE|O_WRONLY and no O_TRUNC (internal/manager.go:490). A shorter download written over an older, longer file would keep trailing bytes. I read this in the code and did not reproduce it. It predates this change.

@aloneangel45 aloneangel45 changed the title fix(pathmeta,manager): check writable plugin dir in Manager.Add and keep NewPathMeta quiet fix(manager,pathmeta): check plugin dir on add and keep NewPathMeta quiet Nov 23, 2026
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the thorough review! Addressed all four blocking items and the test-file split in 3c8ad53 (and updated the PR title and description):

  1. Already-installed plugin error on read-only plugin/ (internal/manager.go, cmd/commands/add_cli_test.go):
    • Moved the existing-plugin check ahead of the writability probe: explicit names/aliases (pname != "") check util.FileExists(installPath) first before ensureWritableDir(pluginsDir), and local unnamed sources (--source demo.zip) inspect tempPlugin.Name and check already exists before probing pluginsDir right prior to util.MovePath. Remote downloads (len(url) == 0 or http(s)://) still probe before any HTTP request.
    • Added a 0555 regression subtest covering both vfox add demo and vfox add --source demo.zip when demo is already installed.
  2. Quiet getExecutablePath() (internal/pathmeta/path_meta.go, internal/pathmeta/path_meta_test.go):
    • Extracted var executable = os.Executable and changed getExecutablePath to log via logger.Debugf("get executable path failed: %v\n", err).
    • Added an executable lookup failure subtest verifying NewPathMeta leaves Executable == "" and writes zero bytes to stdout.
  3. Keep read paths non-creating on missing VFOX_HOME trees (internal/pathmeta/path_meta.go, cmd/commands/env_readonly_test.go):
    • Restored os.Mkdir for Shared.Installs and Shared.Plugins in NewPathMeta (leaving recursive parent creation to write paths such as Manager.Add's ensureWritableDir and acquireInstallLock), updated TestNewPathMetaSharedDirectories, and added env does not create missing nested VFOX_HOME directories.
  4. Explicit error handling in ensureWritableDir (internal/manager.go):
    • Propagate probe.Close() and os.Remove(probePath) errors cleanly without _ =.
  5. Test file split (cmd/commands/env_readonly_test.go):
    • Moved the env/activate read-only and blocked VFOX_HOME tests out of add_cli_test.go into env_readonly_test.go.

Re-verified after 3c8ad53:

  • gofmt -l and git diff --check: clean
  • go vet ./... (Windows, GOOS=linux GOARCH=amd64, GOOS=darwin GOARCH=arm64) and GOOS=linux GOARCH=amd64 go test -c ./cmd/commands: passed
  • go test -count=20 ./cmd/commands -run TestReadOnlyAndBlockedVfoxHomeReadPaths: passed
  • go test -count=1 ./internal ./internal/pathmeta ./cmd/commands: passed (POSIX 0555 and Windows-registry subtests skip cleanly on Windows host and will run on Linux CI)

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge. The #825 cases work and CI is green, but the items below are bugs and test gaps in code this PR adds.

What I checked on 3c8ad53 (Linux, Go 1.27.3): go test ./..., go vet for linux, windows and darwin, and go test -race on the touched packages pass, and the new tests are stable under -count=30 and -shuffle=on. I also ran a build of this branch against a build of base. A missing VFOX_HOME (one level or nested) now works for a local zip and for a remote --source. A VFOX_HOME under a regular file fails before the request and names VFOX_HOME. An installed plugin under a 0555 plugin/ still gets "already exists".

Blocking

  1. --debug reports a failure on every normal run. internal/pathmeta/path_meta.go:152: os.Mkdir returns EEXIST when cache/ or plugin/ is already there, and the new logger.Debugf prints that as a failure. Base drops the error. With both directories in place:

    $ vfox --debug env -s bash
    create shared directory ".../vhome/cache" failed: mkdir .../vhome/cache: file exists
    create shared directory ".../vhome/plugin" failed: mkdir .../vhome/plugin: file exists
    

    Every command that builds a Manager prints these two lines, and they send whoever reads the log looking for a problem that isn't there. Skip fs.ErrExist:

    if err := os.Mkdir(dir, ReadWriteAuth); err != nil && !errors.Is(err, fs.ErrExist) {

    The tests miss it because they run at the default log level. I wrote one that sets the debug level, creates cache/ and plugin/, captures stdout and expects no "failed". It fails on this head and passes with the change above.

  2. The new error prints paths with %q. internal/manager.go:529, and the debug lines at manager.go:517 and path_meta.go:153. Other messages print directories with %s (internal/sdk/sdk.go:1116, internal/plugin_development.go:57); %q is for names, versions and untrusted archive entries. %q doubles backslashes, so on Windows the message reads like this (I formatted a Windows-style path with the same verbs; I did not run it on Windows):

    prepare plugin directory "C:\\vfox\\plugin" (VFOX_HOME="C:\\vfox"): open C:\vfox\plugin\.vfox-write-check-123: Access is denied.
    

    That is two spellings of one path in one line, and VFOX_HOME is not what the user set. The message exists to tell them what to fix. Use %s. The wrapped error also names the probe file (open .../.vfox-write-check-3236389826), which the user never created. checkUpgradeDirWritable in cmd/commands/upgrade_unix.go unwraps the PathError for the same reason; do that here, or say "is not writable".

  3. Some of the new behavior has no test. I checked each of these by changing the code and running the suite:

    • internal/manager.go:609-610 (local --source demo.zip, no alias, plugin not installed, unwritable plugin/) never runs. If that error is dropped, everything still passes and the user gets the raw install plugin error: rename ... permission denied back. Add a 0555 case that expects prepare plugin directory and nothing installed. I wrote one; it passes on this head and fails with the error dropped.
    • Deleting os.Remove(probePath) (manager.go:521) also passes, and then every vfox add leaves a .vfox-write-check-* file in plugin/. ensureWritableDir has no unit test. internal/manager_test.go is the place for one. It should check that the function creates missing parents, leaves the directory empty on success, fails when a file is in the way, and fails on a 0555 directory (skip on Windows and root).
    • manager.go:531, the message without VFOX_HOME set, never runs.
    • The description lists --alias, but no test passes it. A remote --source into a missing VFOX_HOME works when I run it by hand (plugin installed, one request), but nothing guards it. The missing-directory tests only use a local zip.

Minor

Not bugs, but they are one-line changes.

  • path_meta.go:143: "keep base read-path semantics". "base" is review vocabulary and means nothing after the merge. The parenthesis after it says what you mean.
  • cmd/commands/cli_test.go:145: newIsolatedCLIFixture is a way around the registry guard that AGENTS.md describes for newCLIFixture. It is fine for add, env and activate, but the name reads as safe and nothing stops the next test from using it with use --global. Mention it in AGENTS.md next to that paragraph, or name it for what it skips.

Not counted against this PR

Both reproduce on base.

  • installPluginToTemp renames a local .lua source into the temp directory (manager.go:688), so any later failure deletes the user's file. vfox add --source mine.lua into a read-only plugin/ fails and mine.lua is gone.
  • getWorkingDirectory (manager.go:905) calls logger.Errorf with no trailing newline, and NewSdkManager calls it. After the shell's cwd has been removed, vfox env -s bash prints get current working directory failed: getwd: no such file or directoryexport PATH=..., which has the same effect as the messages this PR silences in NewPathMeta.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the detailed review! All three blocking items and both minor notes have been addressed:

  1. Silence EEXIST at --debug (internal/pathmeta/path_meta.go, internal/pathmeta/path_meta_test.go):
    • Guarded os.Mkdir logging with !errors.Is(err, fs.ErrExist) so existing cache/ and plugin/ directories no longer log spurious failures under --debug.
    • Added a subtest under TestNewPathMetaSharedDirectories that sets logger.DebugLevel, pre-creates cache and plugin, and asserts captured stdout has no "failed" line.
  2. Use %s for paths and unwrap probe PathError (internal/manager.go, internal/pathmeta/path_meta.go):
    • Replaced %q with %s in preparePluginDirError, ensureWritableDir's debug log, and path_meta.go's shared-directory debug log.
    • Added unwrapPathError (matching checkUpgradeDirWritable) in preparePluginDirError so failures report prepare plugin directory <dir> (VFOX_HOME=<val>) is not writable: <reason> without leaking the internal .vfox-write-check-* temp filename.
  3. Missing test coverage (internal/manager_test.go, cmd/commands/add_cli_test.go):
    • Added TestEnsureWritableDir (parent creation + empty-dir probe cleanup check, regular-file blocker, 0555 dir) and TestPreparePluginDirErrorWithoutVfoxHome (covers the unset VFOX_HOME branch and %s / probe-unwrapping format).
    • Expanded TestAddSourceMissingVfoxHome in cmd/commands/add_cli_test.go with --alias mydemo under missing nested VFOX_HOME, remote --source (httptest) under missing nested VFOX_HOME, and local --source demo.zip (no alias, not yet installed) hitting manager.go's post-inspection ensureWritableDir check on a 0555 plugin/ directory.
  4. Minor cleanups (internal/pathmeta/path_meta.go, cmd/commands/cli_test.go):
    • Removed "base" review vocabulary from the NewPathMeta comment.
    • Renamed newIsolatedCLIFixture to newCLIFixtureWithoutRegistryGuard so callers explicitly see it bypasses the Windows registry guard.

Re-verified locally (gofmt, git diff --check, Windows/linux/amd64/darwin/arm64 go vet, GOOS=linux GOARCH=amd64 go test -c ./cmd/commands, -count=20 on the CLI tests, and go test -count=1 ./internal ./internal/pathmeta ./cmd/commands; POSIX 0555 subtests skip on Windows host and run on Linux CI).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge.

I exported 89f1564 to a separate directory and ran the suite. go vet is clean. The read-only and blocked VFOX_HOME CLI tests pass 30 times in a row, and the 0555 subtests actually run on Linux. The stdout tests catch regressions: I reverted each of the three stdout/EEXIST changes and the matching test failed.

What looks right: a missing VFOX_HOME is created now (#825), a blocked VFOX_HOME fails before any request, an official plugin name under a read-only plugin/ fails before the registry fetch, and env stdout stays clean when GlobalSdkDir or the temp directory cannot be created.

Four bugs remain. Items 1 and 2 come from this branch. Items 3 and 4 were already on main, but they sit in the add --source path this PR changes, so I would fix them here too.

  1. Already-installed plugin, remote source without a name, read-only plugin/

With demo installed and plugin/ at 0555, vfox add --source https://.../demo.zip prints "prepare plugin directory ... is not writable: permission denied", makes no request, and never says the plugin exists. With plugin/ writable, the same command downloads the archive and then prints "plugin named demo already exists".

The name is only known after the download, so the early probe in Manager.Add (manager.go:579-586) cannot give the right answer. Moving the check does not fix it. I suggest downloading into a private directory under User.Temp, then checking the name (manager.go:609-616), then probing, then moving. This also stops writing the archive into the shared plugin/ directory (downloadPlugin, manager.go:489). The test "non-writable VFOX_HOME plugin dir fails before download and names VFOX_HOME" will need to change to: one request, nothing written, error names VFOX_HOME.

Keeping zero requests and accepting the wrong message is not acceptable to me, since the PR description says existing plugins still report "already exists".

  1. Diagnostics disappear when the executable path or the temp directory cannot be resolved

getExecutablePath now logs with Debugf (path_meta.go:182). With os.Executable forced to fail, vfox activate bash used to print "get executable path failed: ..." on stdout. Now it prints nothing, and the hook becomes eval "$("" env -s bash)" (internal/shell/bash.go:41). The hook is broken on main as well, but this branch removes the only message that says why. "create temp dir failed" (path_meta.go:171) is affected in the same way.

The message does not belong on stdout, because eval reads stdout. It does belong on stderr, which eval ignores. Please write these to stderr, and add a test that checks the message is on stderr and not on stdout. Cover activate as well as NewPathMeta.

  1. Already on main: add --source with a local .lua file deletes the source

For a local .lua source, installPluginToTemp renames the user's file into a temporary directory (manager.go:696-701), and Add removes that directory when it returns (manager.go:604-607). I reproduced this on the PR base 90a96e1 and on this branch: after a successful add, the source file is gone. The rename fails across filesystems, so it shows up whenever the source is on the same filesystem as ~/.vfox. Copy the file instead, and add a test that the source still exists after the add.

  1. Already on main: a leftover archive breaks the next download

downloadPlugin opens its target with O_CREATE|O_WRONLY and no O_TRUNC (manager.go:491). If an interrupted add left a larger plugin/demo.zip behind, the next add fails with "install wrapper error: zip: checksum error". The retry works, because the failed run removes the file. The fix for item 1 (a unique file in a private directory) also removes this bug. Add a regression test with a larger leftover file.

Nits, not blocking:

  • NewPathMeta always returns a nil error now, and NewSdkManager checks it (path_meta.go:113, manager.go:881-884). Drop the return value.
  • The preparePluginDirError message reads oddly for a "not a directory" cause (manager.go:536-542).
  • The PR description should not claim that existing plugins report "already exists" under a read-only plugin/ unless the remote-source-without-name case from item 1 is fixed.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the thorough review! Addressed all four items and all three nits in the new commit:

  1. Unnamed remote --source when plugin already exists & downloadPlugin isolation (internal/manager.go, cmd/commands/add_cli_test.go, internal/manager_test.go):
    • downloadPlugin now downloads into a unique private vfox-dl-* subdirectory under User.Temp (with os.O_CREATE|os.O_WRONLY|os.O_TRUNC) instead of writing directly into shared Shared.Plugins, and installPluginToTemp removes the private vfox-dl-* directory on cleanup.
    • Manager.Add now defers probing ensureWritableDir(pluginsDir) for unnamed --source installs until after downloading/unpacking and discovering tempPlugin.Name + checking already exists. Thus, both vfox add --source https://.../demo.zip and local unnamed sources report "plugin named demo already exists" when demo is installed even if plugin/ is 0555, while named/aliased installs still fail ensureWritableDir before any network request.
    • Updated cmd/commands/add_cli_test.go so the 0555 unnamed remote --source test asserts 1 download request, zero files written to plugin/, and the VFOX_HOME / is not writable error, and added a 0555 remote existing-plugin assertion.
  2. Route createTempDir and getExecutablePath diagnostics to os.Stderr (internal/pathmeta/path_meta.go, internal/pathmeta/path_meta_test.go, cmd/commands/env_readonly_test.go):
    • NewPathMeta (temp dir & global SDK dir failures), generateSessionShimPath ("create temp dir failed"), and getExecutablePath ("get executable path failed") now write diagnostics to os.Stderr so shell hooks such as eval "$(vfox activate bash)" keep stdout clean shell code while diagnostics still appear on stderr.
    • Exported pathmeta.Executable for testing and added stdout/stderr assertions across TestNewPathMetaSharedDirectories, env -s bash, and activate bash.
  3. Copy local .lua plugin sources instead of renaming (internal/manager.go, cmd/commands/add_cli_test.go):
    • installPluginToTemp now uses util.CopyFile instead of os.Rename for .lua wrappers so the caller's source .lua file is preserved after both successful and failed add --source runs; covered in add_cli_test.go.
  4. Leftover archive truncation (internal/manager.go, internal/manager_test.go, cmd/commands/add_cli_test.go):
    • Downloading to a private vfox-dl-* temp dir under User.Temp and opening with os.O_TRUNC prevents leftover archives in plugin/ (e.g. an oversized interrupted demo.zip) from breaking subsequent downloads; covered by TestDownloadPluginSavesToPrivateTempAndTruncates and add_cli_test.go.
  5. Nits:
    • Dropped the unused error return from pathmeta.NewPathMeta and updated all callers in internal/ and tests.
    • Refined preparePluginDirError so non-permission errors (such as a regular file blocking directory creation) format as prepare plugin directory <dir> ... failed: <reason> rather than is not writable: not a directory.

Re-verified locally after the commit:

  • gofmt -l and git diff --check: clean
  • go vet ./... on Windows host, GOOS=linux GOARCH=amd64, and GOOS=darwin GOARCH=arm64, plus GOOS=linux GOARCH=amd64 go test -c ./cmd/commands: passed
  • go test -race -count=1 ./internal ./internal/pathmeta ./cmd/commands: passed (internal 1.577s, internal/pathmeta 1.808s, cmd/commands 16.298s)

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up commit fixing the Ubuntu failure in TestDownloadPluginKeepsBackslashPathsInDownloadTempDir:

  • pluginFileName (internal/manager.go) now normalizes \ to / before calling path.Base and checks name != ".." and filepath.VolumeName(name) == "", instead of relying on filepath.Base (which left literal ..\\ inside the POSIX filename on Linux).

Verified locally on clean checkout after the edit:

  • gofmt -l internal/manager.go internal/manager_test.go (clean)
  • go vet ./cmd/... ./internal/... for GOOS=linux, GOOS=windows, and GOOS=darwin (exit 0)
  • go test -race -count=1 ./internal ./cmd ./cmd/commands and go test -v -race -count=10 -run TestDownloadPluginKeepsBackslashPathsInDownloadTempDir ./internal (pass)

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 759a01b.

Fixed since the last review: an installed plugin under a read-only plugin/ now reports "already exists" for named and unnamed sources, local .lua sources are kept, downloads go into a private directory, and --debug no longer prints EEXIST failures. Read paths no longer create VFOX_HOME trees (covered by tests), and NewPathMeta no longer returns an error.

What I ran on Linux with Go 1.27.3: go vet ./..., go test -race -count=1 ./..., and gofmt -l on the changed files. All pass, and CI is green on this head. None of the items below is covered by CI.

All of these block the merge.

  1. NewPathMeta now writes to stderr where base was silent. path_meta.go:147-151 print "create temp dir failed" and "create global sdk dir failed" with no debug check. With ~/.vfox/sdks as a dangling symlink, base prints nothing and this branch prints one line on every env -s bash (checked over three runs). AGENTS.md says diagnostics belong to use and doctor, never to activate or env. The title ("keep NewPathMeta quiet") no longer matches the code. Make these two logger.Debugf calls and change the case at path_meta_test.go:288 so it asserts an empty stderr. If stderr output from env and activate is wanted after all, change AGENTS.md in the same PR.

  2. The same missing ~/.vfox/tmp is reported twice, at path_meta.go:148 and path_meta.go:171. With ~/.vfox/tmp as a regular file, vfox env -s bash prints two identical lines. Keep one.

  3. stdout still gets a message glued to the shell code when the working directory has been removed. manager.go:937 calls logger.Errorf without a newline, and the logger writes to stdout. On base and on this branch, env -s bash run from a deleted directory prints "get current working directory failed: getwd: no such file or directoryexport PATH=..." on stdout, and eval leaves PATH unchanged. The PR says stdout stays clean shell code, and this case breaks that. Print to os.Stderr with a newline, and add a case to env_readonly_test.go that removes the cwd and checks that stdout holds only shell code.

  4. activate output changes between runs. Twenty runs of vfox activate bash gave three different outputs on this branch and on base. The cause is map iteration in the renderers (internal/shell/bash.go:65, zsh.go:68, nushell.go:153, clink.go:40), fed by the map built at cmd/commands/activate.go:178. The test now compares sorted ; fragments (env_readonly_test.go:35, 52, 174). That hides the nondeterminism instead of removing it, and AGENTS.md says not to weaken assertions to make a failure pass. Sort the keys before rendering and compare the exact output.

  5. TestDownloadPluginRejectsUnexpectedStatus (manager_test.go:286-302) checks Shared.Plugins. downloadPlugin no longer writes there, so the check cannot fail: a 403 body written to User.Temp would still pass. Set User.Temp to t.TempDir() and assert that it is empty.

  6. TestDownloadPluginNamesFileFromURLPath (manager_test.go:442-445) has no User.Temp, so both downloads go to os.TempDir() and nothing removes them. One run left two vfox-dl-* directories in TMPDIR. Base wrote into t.TempDir(), so this is new. Set User.Temp to t.TempDir().

  7. downloadPlugin ignores the error from f.Close() (manager.go:515) and then sets keepFile = true (manager.go:522). A failed flush is reported as a successful download, and the caller decompresses or installs the file as it is. Close the file explicitly before keepFile is set, return the error, and let the cleanup remove the directory. Base had the same defer, but this PR rewrites the function, so I am counting it here.

  8. pluginFileName can return names that Windows cannot create (manager.go:438-447). On Linux, a%3Fb.zip gives a?b.zip, a%22b.zip gives a"b.zip, and a%3Ab.zip gives a:b.zip. On Windows, ? and " make the open fail, and : creates an NTFS alternate data stream instead of a file. I have not run this on Windows, and no test covers it. Reject names containing <>:"|?* or control characters, fall back to "plugin" plus the extension, and add a test.

Not counted against this PR: vfox add --alias ../escaped --source x.zip installs to $VFOX_HOME/escaped, outside plugin/. Base does the same, because the alias is never validated (manager.go:599 and :633). This should be a separate issue.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all items from your review in e7cd471 (plus 759a01b backslash normalization):

  1. NewPathMeta User.Temp / GlobalSdkDir stderr noise (internal/pathmeta/path_meta.go): Switched GlobalSdkDir and User.Temp (when HookCurTmpPath is set) creation failures to logger.Debugf(...), and updated internal/pathmeta/path_meta_test.go so blocked GlobalSdkDir and SharedRoot asserts empty stderr.
  2. Duplicate create temp dir failed: log (internal/pathmeta/path_meta.go): Skipped the redundant os.MkdirAll(meta.User.Temp) attempt when HookCurTmpPath is empty because generateSessionShimPath already attempts os.MkdirAll inside meta.User.Temp and logs once to os.Stderr; added strings.Count(..., "create temp dir failed:") == 1 in path_meta_test.go.
  3. Deleted cwd in getWorkingDirectory (internal/manager.go): Replaced logger.Errorf(...) with fmt.Fprintf(os.Stderr, "get current working directory failed: %v\n", err) and added a deleted-cwd test in cmd/commands/env_readonly_test.go asserting stderr contains the error while stdout stays identical clean shell code (runs on POSIX CI; skipped on Windows where an open handle blocks removing cwd).
  4. Deterministic shell exports (internal/shell/* + cmd/commands/env_readonly_test.go): Added sortedEnvKeys in internal/shell/shell.go and used it across bash, zsh, clink, fish, powershell, and nushell; removed sortSemicolonStatements and restored exact string equality assertions in cmd/commands/env_readonly_test.go.
  5. TestDownloadPluginRejectsUnexpectedStatus (internal/manager_test.go): Set User.Temp to t.TempDir() and asserted both pluginsDir and userTemp stay empty.
  6. Download test temp isolation (internal/manager_test.go): Set User.Temp to t.TempDir() in TestDownloadPluginNamesFileFromURLPath and sibling downloadPlugin tests so runs no longer leak vfox-dl-* into os.TempDir().
  7. Explicit f.Close() check in downloadPlugin (internal/manager.go): Removed defer f.Close(), checked closeErr := f.Close() explicitly before keepFile = true, and returned closeErr on failure (also ensuring the file handle is closed before dlDir cleanup on error paths).
  8. Cross-platform filename sanitization in pluginFileName (internal/manager.go): Rejected <, >, :, ", |, ?, *, and control chars (< 0x20, 0x7f) via isSafePluginFileName so URLs like /a%3Fb.zip, /a%22b.zip, /a%3Ab.zip fall back to plugin.zip everywhere; added TestDownloadPluginSanitizesInvalidFilenameCharacters.

Verified locally at e7cd471 with gofmt -s -l, git diff --check, cross-OS go vet ./cmd/... ./internal/... (windows/linux/darwin), cross-OS go test -c (linux/darwin), go test -race -count=1 ./internal/pathmeta ./internal/shell ./internal ./cmd ./cmd/commands, and -count=20 runs on TestNewPathMetaSharedDirectories and the deterministic activate bash test.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CI failed.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Follow-up 03f8ac7 updates the deleted-cwd test in cmd/commands/env_readonly_test.go / cmd/commands/cli_test.go to use os.Chdir + os.Remove inside TestCLIProcess directly instead of spawning external rmdir under an empty fixture PATH (which caused sh: rmdir: command not found on macOS CI).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CI failed. Again.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Pushed 3d048bb to fix the macos-latest failure:

  • On macOS (darwin), os.Getwd() after rmdir on an open directory handle still resolves the path instead of returning ENOENT like Linux getcwd(3) does, so env writes deleted cwd diagnostic to stderr... saw an empty stderr on Darwin even though rmdir succeeded.
  • Added internal.Getwd = os.Getwd in internal/manager.go (matching pathmeta.Executable) and added env writes getwd failure diagnostic to stderr and keeps stdout clean shell code in cmd/commands/env_readonly_test.go, which tests getWorkingDirectory() returning an error across Windows, macOS, and Linux, while scoping the real unlinked-cwd subprocess test (VFOX_TEST_DELETED_CWD) to runtime.GOOS == "linux".

Verified locally at 3d048bb with gofmt -s -l, git diff --check, 3-OS go vet ./cmd/... ./internal/..., linux/darwin go test -c ./cmd/commands, and go test -race -count=1 ./internal ./cmd/commands (1.705s / 17.273s). Watching CI now.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 3d048bb.

CI is green and most items from the earlier reviews are fixed. I built base (90a96e1) and head (3d048bb) and compared them against a local HTTP server. Items 1 to 5 block the merge. Items 6 and 7 are not bugs.

  1. Ctrl-C during a remote add leaves vfox-dl-* in ~/.vfox/tmp for good.

Repro: the server sends 1000 bytes of a 100000-byte body and then stalls. Run vfox add --source <url> and send SIGINT after two seconds. ~/.vfox/tmp/vfox-dl-NNN/slow.zip stays behind. Nothing in the tree handles signals, so the deferred cleanup never runs. CleanTmp (internal/manager.go:818) only handles session names (YYYYMMDD-PID) and old timestamps, so vfox-dl-NNN is skipped. vfox env --cleanup, which zsh runs from its exit trap, leaves it too. Base leaves the partial archive in plugin/ instead, but this PR creates a leftover that nothing sweeps.
Fix: have CleanTmp remove vfox-dl-* older than a day, with a test that an old one is removed and a new one is kept. The same gap already exists for vfox-* on main, so that part can be a follow-up.

  1. stderr output from env and activate contradicts AGENTS.md.

internal/pathmeta/path_meta.go:173 (temp dir), :185 (executable path) and internal/manager.go:954 (working directory) write to stderr from env and activate. I reproduced the first with ~/.vfox/tmp as a regular file, where every env -s bash prints it, and the third with the cwd removed. AGENTS.md line 78 says diagnostics never belong to activate or env, and this PR does not change AGENTS.md. Your review of 759a01b said that if stderr stays, AGENTS.md changes in the same PR.
Fix: either update AGENTS.md to allow these three failures on stderr, or send them to logger.Debugf. The rule and the code have to agree.

  1. --debug reports two failures for a VFOX_HOME that does not exist yet.

vfox --debug env -s bash with a missing custom VFOX_HOME prints "create shared directory .../cache failed: ... no such file or directory", and the same for plugin. NewPathMeta skips creating them on purpose (path_meta.go:144-146), and base prints nothing. This is the EEXIST problem again: an expected state reported as a failure.
Fix: check that meta.Shared.Root exists before the Mkdir loop (path_meta.go:155-159), or reword the line as skipped.

  1. Windows device names pass isSafePluginFileName.

On Linux, pluginFileName returns nul.zip, CON.zip, com1.zip and aux.lua unchanged (internal/manager.go:447-457). I could not run Windows here. Windows reserves these base names with or without an extension and in any letter case, so the archive never reaches a file, and the install then fails on a file that was never written.
Fix: reject CON, PRN, AUX, NUL, COM0-COM9 and LPT0-LPT9 by base name before the first dot, and add a table test. The function is pure, so the test runs on every CI platform.

  1. A test that passes without the behavior its name claims.

TestDownloadPluginSavesToPrivateTempAndTruncates (internal/manager_test.go:721) still passes after removing O_TRUNC at internal/manager.go:520. Every download now goes into a new MkdirTemp directory, so the flag does nothing.
Fix: remove the flag and rename the test, or stop describing it as a truncation test.

Not bugs, but please fix in the same pass:

  1. The PR body's Verification section still describes e7cd471 and Windows runs. Update it for the final head.
  2. The gofmt -s change to ParseLegacyFile in internal/manager.go is unrelated to this PR. AGENTS.md asks to keep unrelated changes separate.

Checked and fine:

  • A missing VFOX_HOME is created by add (#825). A named add into a 0555 plugin/ makes no request.
  • An unnamed remote add into a 0555 plugin/ makes one request, writes nothing, and the error names VFOX_HOME. With the plugin already installed, it says "already exists".
  • A failed add of a local .lua source keeps the source file. Base deletes it.
  • activate output (bash, zsh, fish, pwsh, nu, clink) and env -s output (bash, pwsh, nu, clink) are identical across 30 runs. Base produced three distinct bash, zsh and fish outputs.
  • env -s bash prints only shell code to stdout when the session temp dir is blocked, when the cwd is removed, or when ~/.vfox/sdks is a dangling symlink. The statements match base as a set.
  • Failed downloads (404, truncated body, corrupt archive) leave nothing behind. Base left a partial archive in plugin/.
  • A successful remote add leaves no staging directory.
  • CI is green at 3d048bb. go vet passes for linux, windows and darwin, and go test ./... passes as a non-root user, so the 0555 subtests run.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all items at a011778:

  1. Leftover vfox-dl-* cleanup: Manager.CleanTmp (internal/manager.go) now removes vfox-dl-* staging directories older than 24 hours while retaining newer ones, covered by TestCleanTmpSweepsStaleDownloadDirs (internal/manager_test.go).
  2. AGENTS.md vs env/activate diagnostics: switched generateSessionShimPath, getExecutablePath (internal/pathmeta/path_meta.go), and getWorkingDirectory (internal/manager.go) failure logs to logger.Debugf so normal env and activate runs keep both stdout and stderr clean. Updated internal/pathmeta/path_meta_test.go and cmd/commands/env_readonly_test.go to verify empty stdout/stderr at InfoLevel and diagnostic output at DebugLevel.
  3. --debug with nonexistent VFOX_HOME: guarded the Shared.Installs/Shared.Plugins os.Mkdir loop in NewPathMeta with util.FileExists(meta.Shared.Root) (internal/pathmeta/path_meta.go), covered at DebugLevel in internal/pathmeta/path_meta_test.go and cmd/commands/env_readonly_test.go.
  4. Windows reserved device names: added isWindowsReservedDeviceName (CON, PRN, AUX, NUL, COM0-COM9, LPT0-LPT9, checked case-insensitively before the first dot) to isSafePluginFileName (internal/manager.go), covered by TestPluginFileNameRejectsWindowsReservedNames (internal/manager_test.go).
  5. O_TRUNC and test naming: removed unused os.O_TRUNC from downloadPlugin (internal/manager.go) and renamed TestDownloadPluginSavesToPrivateTempAndTruncates to TestDownloadPluginSavesToPrivateTemp (internal/manager_test.go).
  6. PR body: updated the Summary and Verification sections for a011778.
  7. ParseLegacyFile: restored the original for sdkName, _ := range legacyFileRecord.Record form in internal/manager.go so no unrelated diff remains.

…ug, sweep stale downloads, reject device names

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at a011778.

The five blocking items from my last review are fixed. I rechecked them with the binaries and the test suite:

  • A SIGINT during a remote download leaves a vfox-dl-* directory behind. vfox env --cleanup removes it once it is older than 24 hours.
  • With ~/.vfox/tmp blocked, env -s bash and activate bash print only shell code on stdout. Base prints the error in front of the export line.
  • --debug env -s bash no longer reports EEXIST for cache/ and plugin/, and no longer reports the shared directories when VFOX_HOME is missing.
  • Windows device names fall back to plugin.* (TestPluginFileNameRejectsWindowsReservedNames).
  • The misnamed truncation test is renamed and no longer claims to cover O_TRUNC.

go test ./... passes as a non-root user, so the 0555 cases run. CI is green, and #825 is fixed.

These still need a change:

  1. The comment on downloadPlugin (internal/manager.go:471) says the plugin is downloaded "to plugin home directory". It now goes to a private vfox-dl-* directory under User.Temp. Please update it.

  2. AGENTS.md asks for an explanation of intentional best-effort behavior, cleanup included. These new calls ignore the error without one:

    • internal/manager.go:527, the defer in downloadPlugin
    • internal/manager.go:728, the defer in installPluginToTemp (this line changed)
    • internal/manager.go:834, the vfox-dl-* branch of CleanTmp
      A short comment on each is enough: what is left behind if the removal fails, and who removes it. For download directories that is CleanTmp, after 24 hours.
  3. runInProcessCaptured (cmd/commands/env_readonly_test.go:256) does not change into the fixture directory. manager() and runHere() both call t.Chdir(f.work) (cli_test.go:356 and :408). Without it, the in-process runs use the package directory as their working directory, which is a different context from the subprocess tests. Please add t.Chdir(f.work).

  4. runInProcessCaptured reads the pipes only after Run returns (env_readonly_test.go:275, then :281-282). Output larger than the pipe buffer blocks Run, and the test hangs instead of failing. The activate debug output is about 1.2 KB in a local run, so this does not fail today. runHere already captures into temp files (cli_test.go:412). Please do the same here.

  5. Title and body. The title covers only the plugin directory check and NewPathMeta. The body does not mention the shell output ordering, the download staging, the CleanTmp sweep, the file name checks or the .lua copy. It also does not say that list, doctor and use no longer print the NewPathMeta diagnostics that base prints. I reproduced that with vfox list and a file at ~/.vfox/tmp. That trade-off may be fine, but the description should state it.

These also exist on base. They are outside this PR, so please open separate issues:

  • The installed plugin directory is created by os.MkdirTemp in installPluginToTemp with mode 0700, so other users who share a VFOX_HOME cannot read the plugin.
  • vfox add a b exits 0 when every add fails (cmd/commands/add.go, multi-name loop).

@aloneangel45 aloneangel45 changed the title fix(manager,pathmeta): check plugin dir on add and keep NewPathMeta quiet fix(manager,pathmeta,shell): check plugin dir on add, isolate download staging, keep NewPathMeta quiet, and sort shell env Nov 24, 2026
…gin doc, and use Chdir + temp capture in env_readonly_test
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all five notes at bfc8357:

  1. Updated downloadPlugin doc comment (internal/manager.go) to reflect private vfox-dl-* staging under User.Temp.
  2. Added AGENTS.md best-effort cleanup explanations for the ignored os.RemoveAll results in downloadPlugin, installPluginToTemp, and the vfox-dl-* sweep in CleanTmp.
  3. Added t.Chdir(f.work) in runInProcessCaptured (cmd/commands/env_readonly_test.go).
  4. Switched runInProcessCaptured from os.Pipe to temp-file capture (os.CreateTemp + os.ReadFile after Run, matching runHere).
  5. Broadened the PR title and updated the summary (including the list/doctor/use NewPathMeta/Getwd quiet-unless---debug trade-off, internal/shell key sorting, download staging, CleanTmp, reserved filename fallback, and .lua CopyFile).

Filed the two pre-existing base follow-up issues separately as requested:

  • https://github.com/version-fox/vfox/issues/829 (installPluginToTemp 0700 dir under shared VFOX_HOME)
  • https://github.com/version-fox/vfox/issues/830 (vfox add a b exiting 0 when all adds fail)

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at bfc8357.

What I ran, on Linux as a non-root user so the 0555 cases run:

  • go build, go vet for linux, windows and darwin, and gofmt on the changed files: clean. internal/plugin/model_test.go is unformatted on main too, so it is not part of this PR.
  • go test ./... with HOME and TMPDIR pointed at scratch directories: passes. The new CLI and download tests pass with -count=15, and the internal tests also with -shuffle=on.
  • CI is green. #825 is fixed: a missing VFOX_HOME is created, and a blocked one fails before any request.
  • The five items from the last review are fixed.

The items below are bugs. Each one blocks the merge.

  1. "create temp dir failed" is logged twice in an activated shell.

vfox activate exports __VFOX_CURTMPPATH. With that variable set and ~/.vfox/tmp blocked by a regular file, vfox --debug env -s bash prints the message twice. Base prints it once. The two calls are path_meta.go:147-151 and path_meta.go:175. The PR body says this is deduplicated, but the fix only holds when the variable is unset. The count assertion in TestNewPathMetaSharedDirectories runs only in that case.

Create the user temp directory in one place, log its failure once, and add a case with the variable set.

  1. --alias can install a plugin outside VFOX_HOME.

The alias is not validated. It becomes installPath at manager.go:619 and :629, and the move at :675 writes there. Reproduction:

VFOX_HOME=$W/vh vfox add --alias ../../../outside --source demo.zip

The plugin lands in $W/outside. Base does the same when $W/vh/plugin already exists. The preflight at :634 checks plugin/, which is not the directory that gets written, so it does not protect this path.

Validate the alias as a single path element before any download. Reusing the plugin name rule (isValidName in internal/plugin/plugin.go) is the simplest option. Add a test that checks nothing is written outside VFOX_HOME.

  1. list, doctor and use no longer report an unusable temp or working directory.

The messages at path_meta.go:149, :153, :158, :187 and manager.go:983 moved to Debugf. With ~/.vfox/tmp blocked, base vfox doctor reports the failure, and this branch reports only path.not-activated. vfox list gives no reason on this branch.

AGENTS.md says: "Diagnostics belong to use and doctor, never to activate or env." The code keeps the second half and breaks the first. The PR body documents the trade-off, but the code and AGENTS.md still disagree. Either report these failures from the command layer (for example as doctor findings), or change AGENTS.md in this PR.

  1. Windows reserved names with superscript digits are not rejected.

isWindowsReservedDeviceName (manager.go:460-469) covers COM0-COM9 and LPT0-LPT9 only. Microsoft's naming documentation also reserves COM¹, COM², COM³, LPT¹, LPT² and LPT³, and says Windows treats the superscript digits as the same device names. On this head pluginFileName returns com¹.zip, COM².zip, lpt³.zip and LPT¹.lua unchanged. On Windows those names refer to devices, so the archive never becomes a file.

Add the six names to TestPluginFileNameRejectsWindowsReservedNames. I have not run this on Windows; the expected result comes from the documentation.

  1. Installed plugins are mode 0700, so other users of a shared VFOX_HOME cannot read them.

installPluginToTemp creates its staging directory with os.MkdirTemp (manager.go:739), which is 0700, and the move into plugin/ keeps that mode. After vfox add --source demo.zip, plugin/demo is drwx------. Base behaves the same, and #829 tracks it. It sits on the add path this PR rewrites, and the preflight exists for shared VFOX_HOME directories. Other users cannot read main.lua. When a plugin fails to load, LoadAllSdk (manager.go:216-218) skips it and logs only at debug level, so they get no message.

Give the staging directory the same mode as plugin/ before the move, and add a test for the installed directory's mode.

Items 2 and 5 predate this PR. I count them because they are on the add path this PR changes.

Test gaps: no new test covers item 1 with the variable set, item 2, item 4 or item 5.

@aloneangel45 aloneangel45 changed the title fix(manager,pathmeta,shell): check plugin dir on add, isolate download staging, keep NewPathMeta quiet, and sort shell env fix(manager,pathmeta,doctor,shell): isolate downloads, validate names, match plugin mode, keep env quiet, surface path diagnostics, and sort shell env Nov 24, 2026
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all five blocking items from the review at 9dcf550:

  1. Deduplicated "create temp dir failed:" when __VFOX_CURTMPPATH is set (internal/pathmeta/path_meta.go, internal/pathmeta/path_meta_test.go, cmd/commands/env_readonly_test.go):
    • Consolidated User.Temp and SessionSdkDir directory creation into ensureUserTempDirs so a blocked User.Temp is logged once per run even when __VFOX_CURTMPPATH points inside it.
    • Added activated-shell regression coverage with __VFOX_CURTMPPATH set asserting "create temp dir failed:" appears once in both TestNewPathMetaSharedDirectories and TestReadOnlyAndBlockedVfoxHomeReadPaths.
  2. Validate --alias and plugin names before download (internal/plugin/plugin.go, internal/plugin/wrapper.go, internal/manager.go, internal/manager_test.go, cmd/commands/add_cli_test.go):
    • Exported plugin.IsValidName and rejected invalid/traversal --alias and explicit names at the start of Manager.Add before any HTTP download or filesystem check.
    • Added TestAddRejectsInvalidAliasBeforeDownload (0 HTTP hits) and CLI test alias traversal fails without writing outside VFOX_HOME.
  3. doctor and use report unusable temp / path / working directory (internal/pathmeta/path_meta.go, internal/sdk/finding.go, internal/manager_doctor.go, cmd/commands/use.go, internal/manager_doctor_test.go, cmd/commands/env_readonly_test.go):
    • Recorded PathMeta.InitErrors and Manager.workingDirErr while keeping NewPathMeta / NewSdkManager quiet at InfoLevel (env and activate remain clean).
    • Exposed them as sdk.FindingPathUnusable ("path.unusable") in Manager.Diagnose (vfox doctor / doctor --json) and useCmd (vfox use, honoring diagnostics.onUse and diagnostics.ignore), matching AGENTS.md ("Diagnostics belong to use and doctor, never to activate or env"). Added unit and CLI regression tests (TestDiagnoseReportsUnusablePathsAndWorkingDirectory and doctor and use report blocked temp directory while env stays clean).
  4. Reject Windows superscript device names (internal/manager.go, internal/manager_test.go):
    • Added COM¹ (\u00b9), COM² (\u00b2), COM³ (\u00b3), LPT¹, LPT², and LPT³ to isWindowsReservedDeviceName and added all six cases to TestPluginFileNameRejectsWindowsReservedNames.
  5. Match installed plugin directory permissions to plugin/ (internal/manager.go, cmd/commands/add_cli_test.go):
    • In Manager.Add, matched tempPlugin.InstalledPath permissions via os.Chmod to os.Stat(pluginsDir).Mode().Perm() before MovePath (leaving shared VFOX_HOME plugins readable instead of 0700) and added a CLI mode assertion for non-Windows hosts.
  6. Updated PR title & body to reflect the full change set and exact behavior across doctor, use, list, env, and activate.

Local Verification (9dcf550)

  • gofmt -s -l, git diff --check, 3-OS go vet ./..., and linux/darwin go test -c -o NUL ./cmd/commands: clean
  • VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./internal ./internal/pathmeta ./internal/plugin ./internal/sdk ./internal/shell ./cmd ./cmd/commands: passed (1.997s, 1.932s, 3.215s, 3.949s, 12.658s, 16.362s, 103.417s)

… dedup, alias traversal, plugin dir mode, superscripts, and diagnostics

- Deduplicate `create temp dir failed:` logging in `NewPathMeta` when `__VFOX_CURTMPPATH` is set under a blocked `User.Temp`.
- Reject invalid/traversal `--alias` and plugin names via `plugin.IsValidName` before any download or filesystem write.
- Surface `PathMeta.InitErrors` and `Getwd` failures as `sdk.FindingPathUnusable` diagnostics in `vfox doctor` (`--json` and text) and `vfox use` (`useCmd`), keeping `env` and `activate` quiet.
- Reject Windows superscript device names (`COM¹..³`, `LPT¹..³`) in `isWindowsReservedDeviceName`.
- Match staging directory permissions in `Manager.Add` to `plugins/` (`os.Stat` -> `os.Chmod`) before moving into `plugin/`.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 9dcf550.

I built base (90a96e1) and head (9dcf550) on Linux as a non-root user and compared them with a sandboxed HOME and VFOX_HOME. go vet passes for linux, windows and darwin, gofmt -s is clean on the changed files, go test ./... passes, and -race passes for ./internal, ./internal/pathmeta, ./internal/shell and ./cmd/commands. The fixes from the last round hold: env and activate print only shell code with a blocked session temp dir, a deleted cwd or a dangling ~/.vfox/sdks; the "create temp dir failed" line appears once under --debug; --alias ../../../outside is rejected before anything is written; an installed plugin under a 0555 plugin/ reports "already exists". The items below block the merge.

  1. A read-only shared VFOX_HOME now produces errors.

Setup: VFOX_HOME is not writable by the current user, cache/ exists, plugin/ does not, and the shell is activated (__VFOX_SHELL=bash).

  • base: vfox doctor prints "No problems found." and exits 0.
  • head: vfox doctor prints error path.unusable Cannot use shared directory (.../plugin): mkdir ...: permission denied. and exits 1.
  • head: vfox use -s <sdk>@<version> prints "ERROR Cannot use shared directory (...)" on every run. base prints nothing extra.

With both directories missing you get two errors. env and activate are not affected.

The cause is in NewPathMeta (internal/pathmeta/path_meta.go:173-185): a failed os.Mkdir on Shared.Installs or Shared.Plugins is recorded as an InitError. Read commands do not need these directories, and the write paths already handle them: Manager.Add calls ensureWritableDir, and acquireInstallLock creates the cache tree. Keep the debug line and drop the InitError.

The new read-only test only checks env and activate, which is why this was missed. Add a case that runs doctor and use in an activated shell with a read-only root and no plugin/, and expects exit 0 and no path.unusable finding.

docs/guides/multi-user-sharing.md (lines 244, 246, 275, 277) and docs/zh-hans/guides/multi-user-sharing.md (lines 246, 248, 277, 279) create and move plugins into plugins/. The code uses plugin/ (see docs/guides/configuration.md:131). Following the guide puts a read-only user in the state above, so the guide needs the same change.

  1. path.unusable is missing from the finding tables. Add it to docs/usage/core-commands.md (near line 286) and docs/zh-hans/usage/core-commands.md (near line 287). AGENTS.md treats finding IDs as stable API.

  2. The doc comment is attached to the wrong function. internal/manager_doctor.go:102-103: the "activationFindings checks ..." line now sits above PathFindings, and activationFindings has no comment. Move the line back.

  3. Data race in a test. internal/manager_test.go:835-837: hits is a plain int, incremented in the httptest handler and read by the test goroutine. Use atomic.Int32 like the other new tests. It only passes today because no request is sent.

  4. Unrelated change. internal/manager.go:939 changes for sdkName, _ := range to for sdkName := range in ParseLegacyFile. That is a gofmt -s cleanup outside this PR. AGENTS.md asks to keep unrelated changes separate, so revert it.

The PR description should also cover the new diagnostics for read-only shared roots and the doc changes once they land.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all five items at 93592a4:

  1. Read-only shared VFOX_HOME without plugin/ (or cache/) (internal/pathmeta/path_meta.go, internal/pathmeta/path_meta_test.go, cmd/commands/env_readonly_test.go, docs/*/guides/multi-user-sharing.md):
    • Kept the logger.Debugf line and dropped InitErrors recording for Shared.Installs and Shared.Plugins in NewPathMeta, since read commands do not need them and write paths create/check them.
    • Added read-only root coverage in TestNewPathMetaSharedDirectories (no InitErrors with missing plugin/) and in TestReadOnlyAndBlockedVfoxHomeReadPaths running doctor, doctor --json, and use -s [email protected] with __VFOX_SHELL=bash (missing plugin/ as well as missing cache/ with storage.sdkPath).
    • Updated plugins/ -> plugin/ in docs/guides/multi-user-sharing.md and docs/zh-hans/guides/multi-user-sharing.md (both the setup commands and the directory tree diagram).
  2. path.unusable in finding tables (docs/usage/core-commands.md, docs/zh-hans/usage/core-commands.md): added the path.unusable row to both doctor tables.
  3. Doc comment alignment (internal/manager_doctor.go): moved // activationFindings checks that this shell went through vfox activate. back directly above activationFindings.
  4. Race-free test counter (internal/manager_test.go): switched hits in TestAddRejectsInvalidAliasBeforeDownload to atomic.Int32.
  5. Reverted unrelated cleanup (internal/manager.go): restored for sdkName, _ := range legacyFileRecord.Record in ParseLegacyFile.

Updated the PR description to cover the read-only shared root behavior and doc updates.

Local Verification (93592a4, Windows host)

  • git diff --check, 3-OS go vet ./..., and linux/darwin go test -c ./cmd/commands: passed
  • VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./internal ./internal/pathmeta ./internal/plugin ./internal/sdk ./internal/shell ./cmd ./cmd/commands: passed (2.251s, 2.018s, 3.817s, 4.141s, 12.155s, 16.687s, 104.128s; POSIX chmod 0555 subtests skip on Windows and execute on Linux/macOS CI).

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Fixed the sdk.payload-empty failure on Linux/macOS CI in 6823fe9:

  • TestReadOnlyAndBlockedVfoxHomeReadPaths Case 2 previously ran vfox install [email protected] (which creates a stub installation with an empty bin/ directory), causing vfox doctor to report error sdk.payload-empty rather than No problems found.. Switched Case 2 setup to installOnDisk(t, "alpha", "1.0.0", "alphatool") + doctor --adopt so [email protected] has both an executable payload and a matching receipt before locking roNoCache to 0555.
  • Local check (6823fe9, Windows): gofmt -s, git diff --check, 3-OS go vet ./..., linux/darwin go test -c -o NUL ./cmd/commands, and VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./cmd/commands (103.654s; POSIX 0555 cases run on Linux/macOS CI).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 6823fe9.

The ubuntu-latest failure from 93592a4 is fixed. The Case 2 fixture now installs a command and runs doctor --adopt, and go test ./... passes on Linux as a non-root user. go build, go vet and gofmt are clean. Two items are left, and both are on the add path.

  1. --source URLs with a query string cannot be installed

    $ vfox add --source "https://example.com/demo.zip?raw=true"
    unsupported .zip?raw=xxxxx type wrapper to install, only support .lua or .zip

installPluginToTemp (internal/manager.go:731) takes the extension from the whole URL, so the query string becomes part of it. Base fails the same way, so this predates the PR. It is still on the path this PR rewrites: pluginFileName (manager.go:437) also takes its extension from the whole URL, and the description says download names are validated. Take the extension from the parsed path in both places, and add a test that installs a plugin from a URL with a query string.

  1. vfox add a/b/c now fails

    $ vfox add a/b/c
    invalid plugin name "b/c": name must start with a letter and contain only letters, digits, underscores, or hyphens

Base installs b, the middle segment, through the legacy / branch. This head splits with strings.SplitN (manager.go:616), so the same input is rejected. The description does not mention the change, and no test covers it. Either keep the old behavior, or describe the change and add a test for it.

I did not run anything on Windows or macOS.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Updated f2d31dc to address both items from your review:

  1. --source URLs with a query string (internal/manager.go):
    • Added pluginSourceExt and used it in both pluginFileName and installPluginToTemp so .lua/.zip extensions are taken from the parsed HTTP(S) URL u.Path before falling back to filepath.Ext (preserving existing main tests TestInstallPluginToTempNamesFileWithAcceptedExtension for /dl.php?file=plugin.zip and TestInstallPluginToTempRedactsUnsupportedExtension for redacted unsupported queries while guarding pluginFileName against unsafe characters in fallback extensions).
    • Added TestAddFromSourceURLWithQueryString (internal/manager_test.go), query-string cases in TestPluginFileNameRejectsWindowsReservedNames, and an end-to-end CLI subtest in cmd/commands/add_cli_test.go (remote --source with query string installs cleanly).
  2. Legacy <category>/<name> splitting on a/b/c (internal/manager.go):
    • Switched back to strings.Split(pluginName, "/")[1] (matching origin/main so a/b/c resolves b while still rejecting empty "a/" and unsafe path segments like "../../../outside"), and added TestAddMultiSlashLegacyNameKeepsMiddleSegment.

Verified on Windows: gofmt -l clean on changed files, 3-OS go vet ./... (windows/linux/darwin), linux/darwin go test -c cross-compile (./internal, ./cmd/commands), and go test -race -count=1 ./internal ./internal/pathmeta ./internal/plugin ./internal/shell ./cmd ./cmd/commands all passed (2.643s / 2.255s / 3.634s / 12.280s / 16.659s / 19.892s).

@linghengqian linghengqian added bug Something isn't working and removed need-more-info labels Nov 24, 2026

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

vfox add --source fails with a raw rename error when VFOX_HOME does not exist

2 participants