Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7923: fix(test): isolate test home on Windows so tests stop overwriting ~/.multica/config.json (#9128)

ZhangRuic8d6a1fad03d
diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.go
index 00647c3493..fbb995e92b 100644
--- a/server/cmd/multica/cmd_agent_test.go
+++ b/server/cmd/multica/cmd_agent_test.go
@@ -251,7 +251,7 @@ func TestMissingServerConfigMessageExplainsPortOnlyContext(t *testing.T) {
// and asserts the CLI refuses the config-PAT fallback from the escaped cwd.
func TestNewAPIClient_WorkdirParentEscapeFailsClosed(t *testing.T) {
// Seed a user config with a mul_ PAT that must never be picked up.
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
if err := cli.SaveCLIConfig(cli.CLIConfig{Token: "mul_owner_pat"}); err != nil {
t.Fatalf("seed config: %v", err)
}
@@ -333,7 +333,7 @@ func TestNewAPIClient_LeftoverMarkerActionableError(t *testing.T) {
// Outside agent context, the three-level fallback (flag → env → config) is
// unchanged.
func TestResolveWorkspaceID_AgentContextSkipsConfig(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
// Seed the global CLI config with a workspace_id that must NOT be
// picked up while running inside an agent task.
@@ -428,7 +428,7 @@ func TestResolveWorkspaceID_AgentContextSkipsConfig(t *testing.T) {
}
func TestResolveToken_AgentContextSkipsConfig(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
if err := cli.SaveCLIConfig(cli.CLIConfig{Token: "mul_profile_token"}); err != nil {
t.Fatalf("seed config: %v", err)
@@ -642,7 +642,7 @@ func TestNewAPIClient_AgentContextRequiresTaskToken(t *testing.T) {
func TestNewAPIClient_DaemonPortRequiresTaskToken(t *testing.T) {
t.Chdir(t.TempDir())
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
t.Setenv("MULTICA_AGENT_ID", "")
@@ -667,7 +667,7 @@ func TestNewAPIClient_DaemonPortRequiresTaskToken(t *testing.T) {
}
func TestNewAPIClient_WorkdirMarkerRequiresTaskToken(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")
t.Setenv("MULTICA_AGENT_ID", "")
t.Setenv("MULTICA_TASK_ID", "")
@@ -775,7 +775,7 @@ func TestParseCustomEnv(t *testing.T) {
// --custom-env* flags are gone from `agent update`; the hint must
// surface their replacement so users discover the new audited path.
func TestAgentUpdateNoFieldsErrorPointsAtEnvCommand(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")
t.Setenv("MULTICA_WORKSPACE_ID", "test-ws")
t.Setenv("MULTICA_TOKEN", "test-token")
@@ -831,7 +831,7 @@ func TestAgentMaxConcurrentTasksFlagValidation(t *testing.T) {
}))
defer srv.Close()
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", srv.URL)
t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
t.Setenv("MULTICA_TOKEN", "test-token")
diff --git a/server/cmd/multica/cmd_auth_test.go b/server/cmd/multica/cmd_auth_test.go
index 4e6d76336a..3a1ebac4d6 100644
--- a/server/cmd/multica/cmd_auth_test.go
+++ b/server/cmd/multica/cmd_auth_test.go
@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
+ "fmt"
"net"
"net/http"
"net/http/httptest"
@@ -10,6 +11,7 @@ import (
"strings"
"testing"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/spf13/cobra"
)
@@ -25,9 +27,27 @@ func TestMain(m *testing.M) {
} {
os.Unsetenv(key)
}
- os.Exit(m.Run())
+
+ // Redirect both home environment variables to one scratch directory for the
+ // whole binary. On Windows os.UserHomeDir reads USERPROFILE, not HOME, so a
+ // test that redirects only HOME still resolves ~/.multica against the real
+ // home — which is how a full-suite run wrote SaveCLIConfig fixtures over a
+ // real default-profile config.json. Process-wide redirection isolates tests
+ // that forget their own redirect on every platform; per-test t.Setenv
+ // overrides still take precedence.
+ scratchHome, err := testutil.IsolateUserHome("multica-cli-tests-home-")
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "isolate cmd/multica test home: %v\n", err)
+ os.Exit(1)
+ }
+
+ code := m.Run()
+ _ = os.RemoveAll(scratchHome)
+ os.Exit(code)
}
+var redirectTestHome = testutil.RedirectUserHome
+
// testCmd returns a minimal cobra.Command with the --profile persistent flag
// registered, matching the rootCmd setup used in production.
func testCmd() *cobra.Command {
@@ -333,7 +353,7 @@ func TestLoginTokenFlagParsing(t *testing.T) {
func TestRunAuthStatusTaskContextDoesNotPrintCredential(t *testing.T) {
const fakeTaskToken = "mat_task_status_sentinel"
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TOKEN", fakeTaskToken)
@@ -372,7 +392,7 @@ func TestRunAuthStatusTaskContextDoesNotPrintCredential(t *testing.T) {
func TestRunAuthStatusTaskContextRequiresTaskToken(t *testing.T) {
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
@@ -433,7 +453,7 @@ func TestRunAuthStatusTaskContextRequiresTaskToken(t *testing.T) {
func TestHumanAuthCommandsFailClosedInTaskContext(t *testing.T) {
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TOKEN", "mat_task_sentinel")
diff --git a/server/cmd/multica/cmd_compat_test.go b/server/cmd/multica/cmd_compat_test.go
index 3a9634ed7b..eff2ea4c66 100644
--- a/server/cmd/multica/cmd_compat_test.go
+++ b/server/cmd/multica/cmd_compat_test.go
@@ -7,7 +7,7 @@ import (
)
func TestRunConfigSetPersistsValues(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
cmd := testCmd()
if err := runConfigSet(cmd, []string{"server_url", "http://example.com"}); err != nil {
diff --git a/server/cmd/multica/cmd_config_test.go b/server/cmd/multica/cmd_config_test.go
index 84ba1fb51d..da37f56f35 100644
--- a/server/cmd/multica/cmd_config_test.go
+++ b/server/cmd/multica/cmd_config_test.go
@@ -19,7 +19,7 @@ func newConfigTestCmd() *cobra.Command {
}
func TestRunConfigSetPersistsSupportedKeysInProfile(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
workspacesRoot := filepath.Join(t.TempDir(), "multica-dev")
cmd := newConfigTestCmd()
@@ -51,7 +51,7 @@ func TestRunConfigSetPersistsSupportedKeysInProfile(t *testing.T) {
}
func TestRunConfigShowIncludesProfileAndDefaults(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
cmd := newConfigTestCmd()
_ = cmd.Flags().Set("profile", "empty")
@@ -98,7 +98,7 @@ func TestRunConfigShowIncludesProfileAndDefaults(t *testing.T) {
func TestRunConfigCommandsUseTaskLocalConfigWithoutTouchingOwner(t *testing.T) {
ownerHome := t.TempDir()
taskRoot := filepath.Join(t.TempDir(), "task-multica")
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TASK_CONFIG_ROOT", taskRoot)
@@ -151,7 +151,7 @@ func TestRunConfigCommandsUseTaskLocalConfigWithoutTouchingOwner(t *testing.T) {
func TestRunConfigCommandsFailClosedWithoutTaskRoot(t *testing.T) {
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TASK_CONFIG_ROOT", "")
@@ -182,7 +182,7 @@ func TestRunConfigCommandsFailClosedWithoutTaskRoot(t *testing.T) {
}
func TestRunConfigSetRejectsUnknownKey(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
cmd := newConfigTestCmd()
err := runConfigSet(cmd, []string{"token", "secret"})
diff --git a/server/cmd/multica/cmd_daemon_diskusage_status_test.go b/server/cmd/multica/cmd_daemon_diskusage_status_test.go
index d5cc9861a1..adbecf7d44 100644
--- a/server/cmd/multica/cmd_daemon_diskusage_status_test.go
+++ b/server/cmd/multica/cmd_daemon_diskusage_status_test.go
@@ -175,7 +175,7 @@ func TestDiskUsageNeedsParentStatus(t *testing.T) {
func TestRunDaemonDiskUsageByWorkspaceTableMakesNoRequest(t *testing.T) {
pinHumanCLIContext(t)
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
t.Setenv("MULTICA_SERVER_URL", "")
@@ -206,7 +206,7 @@ func TestRunDaemonDiskUsageByWorkspaceTableMakesNoRequest(t *testing.T) {
func TestRunDaemonDiskUsageTaskTableResolvesStatus(t *testing.T) {
pinHumanCLIContext(t)
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
t.Setenv("MULTICA_SERVER_URL", "")
@@ -233,7 +233,7 @@ func TestRunDaemonDiskUsageTaskTableResolvesStatus(t *testing.T) {
func TestRunDaemonDiskUsageJSONSurvivesServerFailure(t *testing.T) {
pinHumanCLIContext(t)
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
t.Setenv("MULTICA_SERVER_URL", "")
@@ -278,7 +278,7 @@ func TestRunDaemonDiskUsageJSONSurvivesServerFailure(t *testing.T) {
func TestRunDaemonDiskUsageAllProfilesUsesPerProfileToken(t *testing.T) {
pinHumanCLIContext(t)
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
t.Setenv("MULTICA_SERVER_URL", "")
@@ -376,7 +376,7 @@ func TestPrintRepoCacheLineSilentWhenEmpty(t *testing.T) {
func setupTaskDiskUsageContext(t *testing.T, home, ownerServerURL string) string {
t.Helper()
t.Chdir(t.TempDir())
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
t.Setenv("MULTICA_SERVER_URL", "")
@@ -482,7 +482,7 @@ func TestResolveDiskUsageRootTaskContext(t *testing.T) {
t.Run("outside a task keeps profile resolution", func(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
t.Setenv(daemon.TaskWorkspacesRootEnv, filepath.Join(t.TempDir(), "ignored"))
@@ -500,7 +500,7 @@ func TestRunDaemonDiskUsageHonorsProfileWorkspacesRoot(t *testing.T) {
pinHumanCLIContext(t)
home := t.TempDir()
customRoot := filepath.Join(t.TempDir(), "configured-workspaces")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
if err := cli.SaveCLIConfig(cli.CLIConfig{WorkspacesRoot: customRoot}); err != nil {
t.Fatalf("SaveCLIConfig: %v", err)
@@ -528,7 +528,7 @@ func TestResolveDiskUsageRootEnvOverridesProfileConfig(t *testing.T) {
home := t.TempDir()
configRoot := filepath.Join(t.TempDir(), "configured-workspaces")
envRoot := filepath.Join(t.TempDir(), "env-workspaces")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", envRoot)
if err := cli.SaveCLIConfig(cli.CLIConfig{WorkspacesRoot: configRoot}); err != nil {
t.Fatalf("SaveCLIConfig: %v", err)
@@ -550,7 +550,7 @@ func TestEnumerateDiskUsageRootsUsesAndDeduplicatesProfileConfig(t *testing.T) {
sharedRoot := filepath.Join(t.TempDir(), "shared-root")
uniqueRoot := filepath.Join(t.TempDir(), "unique-root")
neverRanRoot := filepath.Join(t.TempDir(), "never-ran-root")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
configs := []struct {
diff --git a/server/cmd/multica/cmd_daemon_precedence_test.go b/server/cmd/multica/cmd_daemon_precedence_test.go
index 68f6e39759..34eef18964 100644
--- a/server/cmd/multica/cmd_daemon_precedence_test.go
+++ b/server/cmd/multica/cmd_daemon_precedence_test.go
@@ -52,7 +52,7 @@ func TestResolveDaemonWorkspacesRootPrecedence(t *testing.T) {
flagRoot := filepath.Join(t.TempDir(), "flag")
envRoot := filepath.Join(t.TempDir(), "env")
configRoot := filepath.Join(t.TempDir(), "config")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{WorkspacesRoot: configRoot}, "dev"); err != nil {
t.Fatalf("SaveCLIConfigForProfile: %v", err)
diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.go
index be016bc4bf..6a610465c1 100644
--- a/server/cmd/multica/cmd_daemon_test.go
+++ b/server/cmd/multica/cmd_daemon_test.go
@@ -219,7 +219,7 @@ func TestPrintDaemonStatusOmitsVersionWhenMissing(t *testing.T) {
// already died with "not authenticated".
func TestRequireDaemonAuth(t *testing.T) {
t.Run("not logged in", func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
err := requireDaemonAuth("")
if err == nil || !strings.Contains(err.Error(), "multica login") {
t.Fatalf("requireDaemonAuth() = %v, want error mentioning 'multica login'", err)
@@ -227,7 +227,7 @@ func TestRequireDaemonAuth(t *testing.T) {
})
t.Run("not logged in with profile", func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
err := requireDaemonAuth("staging")
if err == nil || !strings.Contains(err.Error(), "multica login --profile staging") {
t.Fatalf("requireDaemonAuth(staging) = %v, want error mentioning profile login hint", err)
@@ -235,7 +235,7 @@ func TestRequireDaemonAuth(t *testing.T) {
})
t.Run("authenticated", func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
if err := cli.SaveCLIConfig(cli.CLIConfig{Token: "mul_test_token"}); err != nil {
t.Fatalf("SaveCLIConfig: %v", err)
}
@@ -249,7 +249,7 @@ func TestRequireDaemonAuth(t *testing.T) {
// `daemon start` background path: without a stored token it must error out
// before spawning the child (and long before the 45s readiness wait).
func TestDaemonStartBackgroundUnauthenticatedFailsFast(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
cmd := &cobra.Command{Use: "start"}
cmd.Flags().Bool("foreground", false, "")
@@ -418,7 +418,7 @@ list workspaces: GET /api/workspaces returned 401: {"error":"invalid token"}
// The spawned child is stubbed to `false` via daemonExecutable so it dies
// immediately with a non-zero status, the same shape as a failed preflight.
func TestDaemonStartBackgroundReportsEarlyChildExit(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
falseBin, err := exec.LookPath("false")
if err != nil {
@@ -459,7 +459,7 @@ func TestDaemonStartBackgroundReportsEarlyChildExit(t *testing.T) {
// and only then discovers it cannot start a replacement, leaving the user
// with no daemon at all.
func TestDaemonRestartUnauthenticatedFailsBeforeStopping(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
const profile = "restart-authtest"
@@ -522,7 +522,7 @@ func newRestartTestCmd(t *testing.T, profile string) *cobra.Command {
// running daemon is stopped. Otherwise restart kills the working daemon and
// the replacement child dies in preflight, leaving no daemon at all (#5165).
func TestDaemonRestartRejectedTokenFailsBeforeStopping(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "")
const profile = "restart-401test"
@@ -557,7 +557,7 @@ func TestDaemonRestartRejectedTokenFailsBeforeStopping(t *testing.T) {
// restart must abort before stopping the running daemon, because the
// replacement child would die in preflight against the same dead server.
func TestDaemonRestartUnreachableServerFailsBeforeStopping(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "")
const profile = "restart-unreachable-test"
@@ -624,7 +624,7 @@ func TestPrintDaemonStatusAlignsValuesWithProfileLabel(t *testing.T) {
func TestPrintDiskUsageOtherRootsHintSuggestsProfilesWithTasks(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
mkdirProfile(t, home, "empty")
@@ -672,7 +672,7 @@ func TestPrintDiskUsageOtherRootsHintSuggestsProfilesWithTasks(t *testing.T) {
// a non-empty default root.
func TestPrintDiskUsageOtherRootsHintFiresWhenCurrentRootNonEmpty(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
mkdirProfile(t, home, "desktop-host")
@@ -692,7 +692,7 @@ func TestPrintDiskUsageOtherRootsHintFiresWhenCurrentRootNonEmpty(t *testing.T)
func TestPrintDiskUsageOtherRootsHintSuggestsDefaultFromNamedProfile(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
writeDefaultDiskUsageTaskFile(t, home, "ws0", "task0", "workdir/main.go")
@@ -711,7 +711,7 @@ func TestPrintDiskUsageOtherRootsHintSuggestsDefaultFromNamedProfile(t *testing.
func TestPrintDiskUsageOtherRootsHintUsesProfileConfig(t *testing.T) {
home := t.TempDir()
customRoot := filepath.Join(t.TempDir(), "custom-profile-root")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{WorkspacesRoot: customRoot}, "custom"); err != nil {
t.Fatalf("SaveCLIConfigForProfile: %v", err)
@@ -734,7 +734,7 @@ func TestPrintDiskUsageOtherRootsHintUsesProfileConfig(t *testing.T) {
func TestPrintDiskUsageOtherRootsHintSkipsExplicitRootOverride(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
mkdirProfile(t, home, "has-task")
@@ -752,7 +752,7 @@ func TestPrintDiskUsageOtherRootsHintSkipsExplicitRootOverride(t *testing.T) {
func TestEnumerateDiskUsageRoots(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
// Two profiles configured under ~/.multica/profiles, but only one has its
diff --git a/server/cmd/multica/cmd_daemon_unknown_profile_test.go b/server/cmd/multica/cmd_daemon_unknown_profile_test.go
index 7d4b8b8ad2..543a13b4f2 100644
--- a/server/cmd/multica/cmd_daemon_unknown_profile_test.go
+++ b/server/cmd/multica/cmd_daemon_unknown_profile_test.go
@@ -22,7 +22,7 @@ func mkProfiles(t *testing.T, names ...string) string {
t.Helper()
t.Chdir(t.TempDir())
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
for _, name := range names {
dir := filepath.Join(home, ".multica", "profiles", filepath.FromSlash(name))
if err := os.MkdirAll(dir, 0o755); err != nil {
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 4b2be02a4e..6403c29c6e 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -4176,7 +4176,7 @@ func TestRunIssueAssignRejectsNoStartWithUnassign(t *testing.T) {
func TestIssueReadCommandsUseInjectedTaskToken(t *testing.T) {
const fakeTaskToken = "mat_task_issue_sentinel"
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TOKEN", fakeTaskToken)
@@ -4242,7 +4242,7 @@ func TestIssueReadCommandsUseInjectedTaskToken(t *testing.T) {
func TestIssueReadCommandsFailClosedWithoutTaskToken(t *testing.T) {
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TOKEN", "")
diff --git a/server/cmd/multica/cmd_login_test.go b/server/cmd/multica/cmd_login_test.go
index 59c3860b52..936cfc7c68 100644
--- a/server/cmd/multica/cmd_login_test.go
+++ b/server/cmd/multica/cmd_login_test.go
@@ -20,7 +20,7 @@ func newLoginTestCmd() *cobra.Command {
}
func TestResolveLoginTokenServerURLDefaultsToCloud(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "")
if got := resolveLoginTokenServerURL(newLoginTestCmd()); got != defaultCloudServerURL {
@@ -30,7 +30,7 @@ func TestResolveLoginTokenServerURLDefaultsToCloud(t *testing.T) {
func TestResolveLoginTokenServerURLPrefersConfiguredServer(t *testing.T) {
t.Chdir(t.TempDir())
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", "")
// A stale host/container value is not proof that this process is running
// inside a daemon task. Login still needs the selected human profile.
@@ -53,7 +53,7 @@ func TestResolveLoginTokenServerURLPrefersConfiguredServer(t *testing.T) {
func TestRunLoginTokenAutoWatchesDiscoveredWorkspaces(t *testing.T) {
t.Chdir(t.TempDir())
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "")
t.Setenv("MULTICA_WORKSPACE_ID", "")
// Regression for #6779: older container setups may leave this daemon-
diff --git a/server/cmd/multica/cmd_runtime_profile_test.go b/server/cmd/multica/cmd_runtime_profile_test.go
index a42ac5ef72..21ae75bae1 100644
--- a/server/cmd/multica/cmd_runtime_profile_test.go
+++ b/server/cmd/multica/cmd_runtime_profile_test.go
@@ -74,7 +74,7 @@ func newProfileUnsetPathTestCmd() *cobra.Command {
}
func TestRunRuntimeProfileList(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
@@ -106,7 +106,7 @@ func TestRunRuntimeProfileList(t *testing.T) {
}
func TestRunRuntimeProfileCreate(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
@@ -170,7 +170,7 @@ func TestRunRuntimeProfileCreateRequiresFlags(t *testing.T) {
}
func TestRunRuntimeProfileUpdateOnlySendsChangedFlags(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
@@ -215,7 +215,7 @@ func TestRunRuntimeProfileUpdateOnlySendsChangedFlags(t *testing.T) {
}
func TestRunRuntimeProfileUpdateNoFieldsErrors(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")
@@ -227,7 +227,7 @@ func TestRunRuntimeProfileUpdateNoFieldsErrors(t *testing.T) {
}
func TestRunRuntimeProfileDeleteSuccess(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
@@ -253,7 +253,7 @@ func TestRunRuntimeProfileDeleteSuccess(t *testing.T) {
}
func TestRunRuntimeProfileDeleteConflictSurfacesServerMessage(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
@@ -275,7 +275,7 @@ func TestRunRuntimeProfileDeleteConflictSurfacesServerMessage(t *testing.T) {
}
func TestRunRuntimeProfileSetAndUnsetPath(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
// set-path
setCmd := newProfileSetPathTestCmd()
@@ -307,7 +307,7 @@ func TestRunRuntimeProfileSetAndUnsetPath(t *testing.T) {
}
func TestRunRuntimeProfileSetPathRejectsRelative(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
cmd := newProfileSetPathTestCmd()
_ = cmd.Flags().Set("path", "relative/path")
if err := runRuntimeProfileSetPath(cmd, []string{"prof-1"}); err == nil {
@@ -317,7 +317,7 @@ func TestRunRuntimeProfileSetPathRejectsRelative(t *testing.T) {
func TestRunRuntimeProfileSetPathPreservesExistingConfig(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
// Seed an existing config with unrelated fields.
seed := cli.CLIConfig{ServerURL: "https://api.multica.ai", WorkspaceID: "ws-123", Token: "mul_xyz"}
@@ -345,7 +345,7 @@ func TestRunRuntimeProfileSetPathPreservesExistingConfig(t *testing.T) {
func TestRuntimeProfilePathMutationFailsClosedInTaskContext(t *testing.T) {
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
@@ -377,7 +377,7 @@ func TestRuntimeProfilePathMutationFailsClosedInTaskContext(t *testing.T) {
}
func TestRunRuntimeProfileCreateOmpTarget(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")
var body map[string]any
diff --git a/server/cmd/multica/cmd_runtime_test.go b/server/cmd/multica/cmd_runtime_test.go
index 9257ae6c08..16bddb2b7d 100644
--- a/server/cmd/multica/cmd_runtime_test.go
+++ b/server/cmd/multica/cmd_runtime_test.go
@@ -59,7 +59,7 @@ func captureRuntimeStdout(t *testing.T, fn func() error) (string, error) {
}
func TestRunRuntimeDeleteStrictSuccessPrintsJSON(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
var deleteCount int
@@ -100,7 +100,7 @@ func TestRunRuntimeDeleteStrictSuccessPrintsJSON(t *testing.T) {
}
func TestRunRuntimeDeleteConflictSuggestsCascade(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -129,7 +129,7 @@ func TestRunRuntimeDeleteConflictSuggestsCascade(t *testing.T) {
}
func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
var gotExpectedIDs []string
@@ -198,7 +198,7 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
// HTTPError.Error() used to print the whole JSON response at the user, burying
// that guidance (GH #8456).
func TestRunRuntimeDeleteProfileInstanceConflictShowsServerGuidance(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
const guidance = `cannot delete "MSI-S3TEST" on its own: it is registered from the custom runtime profile "Devin CLI (WSL)". It is offline, and Multica removes offline runtimes automatically after 7 days.`
@@ -229,7 +229,7 @@ func TestRunRuntimeDeleteProfileInstanceConflictShowsServerGuidance(t *testing.T
// A 409 with no readable sentence must still fall back to the wrapper rather
// than surfacing an empty error.
func TestRunRuntimeDeleteConflictWithoutMessageKeepsWrapper(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/cmd/multica/cmd_setup_test.go b/server/cmd/multica/cmd_setup_test.go
index 2d0062274a..ef8e178c38 100644
--- a/server/cmd/multica/cmd_setup_test.go
+++ b/server/cmd/multica/cmd_setup_test.go
@@ -17,7 +17,7 @@ import (
// probe and bailing — which left the user logged out with no recovery.
func TestPersistSelfHostConfigIfReachable(t *testing.T) {
t.Run("unreachable server preserves existing config and token", func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
existing := cli.CLIConfig{
ServerURL: "https://api.old.example",
AppURL: "https://old.example",
@@ -52,7 +52,7 @@ func TestPersistSelfHostConfigIfReachable(t *testing.T) {
})
t.Run("reachable server writes new self-host config", func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
proceed, err := persistSelfHostConfigIfReachable(
"https://api.new.example", "https://new.example", "",
@@ -403,7 +403,7 @@ func TestServerHostIsLocal(t *testing.T) {
func TestSetupCommandsFailClosedInTaskContext(t *testing.T) {
ownerHome := t.TempDir()
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
diff --git a/server/cmd/multica/cmd_skill_test.go b/server/cmd/multica/cmd_skill_test.go
index c8179edca0..6c4cc3228f 100644
--- a/server/cmd/multica/cmd_skill_test.go
+++ b/server/cmd/multica/cmd_skill_test.go
@@ -58,7 +58,7 @@ func captureStdout(t *testing.T, fn func() error) (string, error) {
}
func TestRunSkillImportJsonTreatsDuplicateAsConflictResult(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
@@ -127,7 +127,7 @@ func TestRunSkillImportJsonTreatsDuplicateAsConflictResult(t *testing.T) {
}
func TestRunSkillImportSendsOnConflictAndPrintsStructuredResult(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
@@ -475,7 +475,7 @@ func TestRunSkillInlineEmptyContentKeepsExistingBehavior(t *testing.T) {
}
func TestRunSkillRefreshPostsToRefreshEndpointAndPrintsTable(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
@@ -520,7 +520,7 @@ func TestRunSkillRefreshPostsToRefreshEndpointAndPrintsTable(t *testing.T) {
}
func TestRunSkillRefreshJsonPrintsSkill(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
@@ -604,7 +604,7 @@ func TestRunSkillGetAsksForMetadataUnlessContentRequested(t *testing.T) {
{"--with-content", true, "include=content"},
} {
t.Run(tc.name, func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
var gotQuery string
srv := newSkillQueryCaptureServer(t, "/api/skills/skill-123", &gotQuery, map[string]any{
"id": "skill-123",
@@ -634,7 +634,7 @@ func TestRunSkillFilesListAsksForMetadataUnlessContentRequested(t *testing.T) {
{"--with-content", true, "include=content"},
} {
t.Run(tc.name, func(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
var gotQuery string
srv := newSkillQueryCaptureServer(t, "/api/skills/skill-123/files", &gotQuery, []any{})
setSkillServerEnv(t, srv.URL)
@@ -655,7 +655,7 @@ func TestRunSkillFilesListAsksForMetadataUnlessContentRequested(t *testing.T) {
// strVal would print a 1.2MB file as "1.234567e+06" — JSON numbers decode as
// float64 — which is unreadable at exactly the sizes that matter.
func TestRunSkillFilesListRendersReadableSizes(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
var gotQuery string
srv := newSkillQueryCaptureServer(t, "/api/skills/skill-123/files", &gotQuery, []any{
map[string]any{"id": "f1", "path": "reference.md", "size": 1234567, "content_hash": "abc"},
@@ -691,7 +691,7 @@ func newSkillLabelTestCmd(action string) *cobra.Command {
}
func TestRunSkillLabelCommands(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
t.Setenv("MULTICA_TOKEN", "test-token")
diff --git a/server/cmd/multica/cmd_squad_test.go b/server/cmd/multica/cmd_squad_test.go
index 31ef9c98d0..add3481428 100644
--- a/server/cmd/multica/cmd_squad_test.go
+++ b/server/cmd/multica/cmd_squad_test.go
@@ -22,7 +22,7 @@ func newSquadMemberSetRoleTestCmd() *cobra.Command {
}
func TestRunSquadMemberSetRolePatchesRole(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
diff --git a/server/cmd/multica/cmd_workspace_mcp_test.go b/server/cmd/multica/cmd_workspace_mcp_test.go
index 424eee30f7..4bd5b44110 100644
--- a/server/cmd/multica/cmd_workspace_mcp_test.go
+++ b/server/cmd/multica/cmd_workspace_mcp_test.go
@@ -75,7 +75,7 @@ var workspaceMcpLeakMarkers = []string{
func mcpTestServer(t *testing.T, handler http.HandlerFunc) {
t.Helper()
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)
srv := httptest.NewServer(handler)
diff --git a/server/cmd/multica/cmd_workspace_test.go b/server/cmd/multica/cmd_workspace_test.go
index 824ed3ef5e..85996cd4d0 100644
--- a/server/cmd/multica/cmd_workspace_test.go
+++ b/server/cmd/multica/cmd_workspace_test.go
@@ -88,7 +88,7 @@ func TestRunWorkspaceCreatePostsWorkspaceAndDoesNotSwitchDefault(t *testing.T) {
}))
defer srv.Close()
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", srv.URL)
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "existing-workspace")
@@ -243,7 +243,7 @@ func TestRunWorkspaceCreatePrintsTable(t *testing.T) {
}))
defer srv.Close()
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", srv.URL)
t.Setenv("MULTICA_TOKEN", "test-token")
@@ -280,7 +280,7 @@ func TestRunWorkspaceSwitch(t *testing.T) {
defer srv.Close()
// Isolate HOME so the test never touches the developer's ~/.multica.
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_SERVER_URL", srv.URL)
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "")
@@ -348,7 +348,7 @@ func TestRunWorkspaceSwitch(t *testing.T) {
}
func TestRunWorkspaceSwitchFailsClosedInTaskContext(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_AGENT_ID", "agent-test")
t.Setenv("MULTICA_TASK_ID", "task-test")
t.Setenv("MULTICA_TOKEN", "mat_task_sentinel")
@@ -364,7 +364,7 @@ func TestRunWorkspaceSwitchFailsClosedInTaskContext(t *testing.T) {
func TestFetchWorkspacesExplainsPortOnlyFailClosedContext(t *testing.T) {
t.Chdir(t.TempDir())
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_AGENT_ID", "")
t.Setenv("MULTICA_TASK_ID", "")
t.Setenv(cli.TaskConfigRootEnv, "")
@@ -689,7 +689,7 @@ func newWorkspaceMemberInviteTestCmd() *cobra.Command {
}
func TestRunWorkspaceMemberInvitePostsInvitation(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
@@ -734,7 +734,7 @@ func TestRunWorkspaceMemberInvitePostsInvitation(t *testing.T) {
}
func TestRunWorkspaceMemberInviteUsesWorkspaceArgAndRoleFlag(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
const wsUUID = "11111111-1111-1111-1111-111111111111"
@@ -766,7 +766,7 @@ func TestRunWorkspaceMemberInviteUsesWorkspaceArgAndRoleFlag(t *testing.T) {
}
func TestRunWorkspaceMemberInviteRejectsOwnerRole(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
@@ -788,7 +788,7 @@ func TestRunWorkspaceMemberInviteRejectsOwnerRole(t *testing.T) {
}
func TestRunWorkspaceMemberInviteRejectsUnknownRole(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
diff --git a/server/internal/cli/config_test.go b/server/internal/cli/config_test.go
index c71e96ce00..e40b5ea792 100644
--- a/server/internal/cli/config_test.go
+++ b/server/internal/cli/config_test.go
@@ -15,7 +15,7 @@ import (
// continue to work byte-for-byte.
func TestCLIConfig_BackwardCompat_OldFileLoadsWithNilBackends(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
// Write a 4-field config exactly as the historical daemon would have.
cfgDir := filepath.Join(tmp, ".multica")
@@ -55,7 +55,7 @@ func TestCLIConfig_BackwardCompat_OldFileLoadsWithNilBackends(t *testing.T) {
// an older daemon doesn't trip on an empty `backends: null` line.
func TestCLIConfig_BackwardCompat_NilBackendsOmittedFromJSON(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
cfg := CLIConfig{
ServerURL: "https://api.multica.ai",
@@ -87,7 +87,7 @@ func TestCLIConfig_BackwardCompat_NilBackendsOmittedFromJSON(t *testing.T) {
// and StateDir survives a save/load cycle.
func TestCLIConfig_OpenClawOverride_RoundTrip(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
original := CLIConfig{
ServerURL: "https://api.multica.ai",
@@ -128,7 +128,7 @@ func TestCLIConfig_OpenClawOverride_RoundTrip(t *testing.T) {
// without an empty string overriding env-var precedence.
func TestCLIConfig_OpenClawOverride_PartialFieldsOmitted(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
cfg := CLIConfig{
ServerURL: "https://api.multica.ai",
@@ -173,7 +173,7 @@ func TestCLIConfig_OpenClawOverride_PartialFieldsOmitted(t *testing.T) {
// load->modify->save cycle never dropping config the user already had.
func TestCLIConfig_ProfileCommandOverrides_RoundTrip(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
original := CLIConfig{
ServerURL: "https://api.multica.ai",
@@ -232,7 +232,7 @@ func TestCLIConfig_ProfileCommandOverrides_RoundTrip(t *testing.T) {
// set, so configs for users who never pin a path stay byte-stable.
func TestCLIConfig_ProfileCommandOverrides_OmittedWhenEmpty(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
cfg := CLIConfig{ServerURL: "https://api.multica.ai", Token: "mul_xyz"}
if err := SaveCLIConfig(cfg); err != nil {
@@ -265,7 +265,7 @@ func TestCLIConfig_UnknownFieldsArePreserved(t *testing.T) {
t.Skip("documenting known limitation: encoding/json drops unknown fields on round-trip; future PR can switch to a preserving encoder")
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
cfgDir := filepath.Join(tmp, ".multica")
if err := os.MkdirAll(cfgDir, 0o755); err != nil {
@@ -306,7 +306,7 @@ func TestCLIConfig_UnknownFieldsArePreserved(t *testing.T) {
// time instead of silently losing the operator's config on restart.
func TestCLIConfig_DaemonKnobs_RoundTrip(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
zero := "0s"
original := CLIConfig{
@@ -340,7 +340,7 @@ func TestCLIConfig_DaemonKnobs_RoundTrip(t *testing.T) {
func TestCLIConfig_TaskRootOverridesOwnerHome(t *testing.T) {
ownerHome := t.TempDir()
taskRoot := filepath.Join(t.TempDir(), "task-multica")
- t.Setenv("HOME", ownerHome)
+ redirectTestHome(t, ownerHome)
t.Setenv("MULTICA_TASK_CONFIG_ROOT", taskRoot)
ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
@@ -401,7 +401,7 @@ func TestCLIConfig_TaskRootOverridesOwnerHome(t *testing.T) {
func TestCLIConfig_NoTaskRootKeepsInteractiveHomeResolution(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("MULTICA_TASK_CONFIG_ROOT", "")
path, err := CLIConfigPathForProfile("dev")
@@ -441,7 +441,7 @@ func TestCLIConfig_TaskRootMustBeAbsolute(t *testing.T) {
// daemon never sees.
func TestCLIConfig_OpenClawCLITimeout_RoundTrip(t *testing.T) {
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
original := CLIConfig{
ServerURL: "https://api.multica.ai",
diff --git a/server/internal/cli/testmain_test.go b/server/internal/cli/testmain_test.go
new file mode 100644
index 0000000000..2fc893d8fe
--- /dev/null
+++ b/server/internal/cli/testmain_test.go
@@ -0,0 +1,45 @@
+// Copyright 2026 Multica. All rights reserved.
+
+package cli
+
+import (
+ "fmt"
+ "os"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// TestMain redirects both home environment variables to one scratch directory
+// for the whole binary before any test runs. This package owns SaveCLIConfig,
+// which resolves ~/.multica through os.UserHomeDir — USERPROFILE on Windows,
+// HOME elsewhere. Tests that only redirect HOME therefore split the fixture's
+// write path from the code's read path on Windows: SaveCLIConfig writes test
+// fixtures over a real default-profile config.json. Process-wide redirection
+// isolates tests that forget their own redirect on every platform; per-test
+// t.Setenv overrides still take precedence.
+func TestMain(m *testing.M) {
+ for _, key := range []string{
+ "MULTICA_AGENT_ID",
+ "MULTICA_TASK_ID",
+ "MULTICA_TOKEN",
+ "MULTICA_DAEMON_PORT",
+ "MULTICA_WORKSPACE_ID",
+ "MULTICA_SERVER_URL",
+ "MULTICA_TASK_CONFIG_ROOT",
+ } {
+ os.Unsetenv(key)
+ }
+
+ scratchHome, err := testutil.IsolateUserHome("multica-cli-config-tests-home-")
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "isolate internal/cli test home: %v\n", err)
+ os.Exit(1)
+ }
+
+ code := m.Run()
+ _ = os.RemoveAll(scratchHome)
+ os.Exit(code)
+}
+
+var redirectTestHome = testutil.RedirectUserHome
diff --git a/server/internal/daemon/agents_probe_codearts_test.go b/server/internal/daemon/agents_probe_codearts_test.go
index 622049f10d..13162d1235 100644
--- a/server/internal/daemon/agents_probe_codearts_test.go
+++ b/server/internal/daemon/agents_probe_codearts_test.go
@@ -29,7 +29,7 @@ func TestProbeAgentCLIsDiscoversCodeArtsDefaultInstallPath(t *testing.T) {
resolveAgentsViaLoginShell = func([]string) map[string]string { return map[string]string{} }
resetShellResolveCacheForTest(t)
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
t.Setenv("PATH", t.TempDir())
t.Setenv("MULTICA_CODEARTS_PATH", "")
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 5be99274e0..76a3d648ae 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -111,7 +111,7 @@ func TestPatternsFromEnv_DefaultsWhenUnset(t *testing.T) {
// an operator opts in, and a daemon upgrade never starts deleting on its own.
func TestLoadConfig_CompletedTaskTTLDefaultsDisabledOnSelfHostAndReadsEnv(t *testing.T) {
stageFakeAgent(t)
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("SHELL", filepath.Join(t.TempDir(), "missing-shell"))
t.Setenv("MULTICA_GC_COMPLETED_TASK_TTL", "")
@@ -144,7 +144,7 @@ func TestLoadConfig_CompletedTaskTTLDefaultsDisabledOnSelfHostAndReadsEnv(t *tes
func TestLoadConfig_WSClaimPollIntervalPrecedence(t *testing.T) {
stageFakeAgent(t)
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("SHELL", filepath.Join(t.TempDir(), "missing-shell"))
t.Setenv("MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL", "")
base := Overrides{ServerURL: "http://localhost:0", WorkspacesRoot: t.TempDir()}
@@ -184,7 +184,7 @@ func TestLoadConfig_WSClaimPollIntervalPrecedence(t *testing.T) {
func TestLoadConfig_CompletedTaskTTLDefaultsBoundedOnOfficialCloud(t *testing.T) {
stageFakeAgent(t)
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
t.Setenv("SHELL", filepath.Join(t.TempDir(), "missing-shell"))
t.Setenv("MULTICA_GC_COMPLETED_TASK_TTL", "")
@@ -518,7 +518,7 @@ func TestLoadConfig_SkipsMulticaHooksShadowingAgentBinaries(t *testing.T) {
}
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
hooksDir := filepath.Join(home, ".multica", "hooks")
if err := os.MkdirAll(hooksDir, 0o755); err != nil {
t.Fatalf("create hooks dir: %v", err)
@@ -578,7 +578,7 @@ func TestLoadConfig_SkipsMulticaHooksFromLoginShellFallback(t *testing.T) {
}
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
hooksDir := filepath.Join(home, ".multica", "hooks")
if err := os.MkdirAll(hooksDir, 0o755); err != nil {
t.Fatalf("create hooks dir: %v", err)
@@ -1637,7 +1637,7 @@ func pinNonCodexAgentsToMissingPaths(t *testing.T) {
func writeCLIConfigForProfile(t *testing.T, profile string, cfg cli.CLIConfig) {
t.Helper()
tmp := t.TempDir()
- t.Setenv("HOME", tmp)
+ redirectTestHome(t, tmp)
if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {
t.Fatalf("write cli config: %v", err)
}
@@ -1782,7 +1782,7 @@ func TestLoadConfig_AppliesBackendOverridesFromConfigFile(t *testing.T) {
// Drop a CLI config under the user's HOME (already pointed at TempDir
// by stageFakeAgent's t.Setenv chain — but reassert here for clarity).
homeForCLIConfig := t.TempDir()
- t.Setenv("HOME", homeForCLIConfig)
+ redirectTestHome(t, homeForCLIConfig)
cfg := cli.CLIConfig{
ServerURL: "http://localhost:8080",
Backends: &cli.BackendOverrides{
@@ -1824,7 +1824,7 @@ func TestLoadConfig_BackendOverrides_BackwardCompat_NoConfigFile(t *testing.T) {
stageFakeAgent(t)
// Point HOME at an empty dir — no config.json present.
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
os.Unsetenv("MULTICA_OPENCLAW_PATH")
os.Unsetenv("OPENCLAW_STATE_DIR")
t.Cleanup(func() {
@@ -1853,7 +1853,7 @@ func TestLoadConfig_BackendOverrides_BackwardCompat_NoConfigFile(t *testing.T) {
func TestLoadConfig_BackendOverrides_MalformedConfigFileNonFatal(t *testing.T) {
stageFakeAgent(t)
homeDir := t.TempDir()
- t.Setenv("HOME", homeDir)
+ redirectTestHome(t, homeDir)
// Write malformed JSON.
cfgDir := filepath.Join(homeDir, ".multica")
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index d2c550f7fa..34080d36f7 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -187,7 +187,7 @@ func TestIsBlockedEnvKey(t *testing.T) {
func TestPrepareReasonixTaskStateHome(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
got, err := prepareReasonixTaskStateHome("work", "runtime-1", "agent_2")
@@ -209,7 +209,7 @@ func TestPrepareReasonixTaskStateHome(t *testing.T) {
func TestPrepareDshTaskSessionRoot(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
got, err := prepareDshTaskSessionRoot("work", "runtime-1", "agent_2")
@@ -2067,7 +2067,7 @@ func TestHermesPreparedSessionReachability(t *testing.T) {
// Keep profile/store resolution inside synthetic homes, never the user's.
t.Setenv("MULTICA_TASK_CONFIG_ROOT", "")
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
sourceHome, root := t.TempDir(), t.TempDir()
taskNumber := 0
diff --git a/server/internal/daemon/dsh_bundle_paths_test.go b/server/internal/daemon/dsh_bundle_paths_test.go
index dc20e98121..e816dee0fd 100644
--- a/server/internal/daemon/dsh_bundle_paths_test.go
+++ b/server/internal/daemon/dsh_bundle_paths_test.go
@@ -241,7 +241,7 @@ func TestDshPluginPathDirs_FindsBothLayouts(t *testing.T) {
t.Skip("no app-data location on this platform")
}
want := mkShim(t, filepath.Join(appData, "runtime-commands", "generations", "gen-1"), time.Now())
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
got := dshPluginPathDirs()
@@ -260,7 +260,7 @@ func TestDshPluginPathDirs_FindsBothLayouts(t *testing.T) {
if err := os.MkdirAll(flat, 0o755); err != nil {
t.Fatal(err)
}
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
got := dshPluginPathDirs()
diff --git a/server/internal/daemon/identity_test.go b/server/internal/daemon/identity_test.go
index 0e351d7370..c805a22684 100644
--- a/server/internal/daemon/identity_test.go
+++ b/server/internal/daemon/identity_test.go
@@ -13,7 +13,7 @@ import (
func TestEnsureDaemonID_Persists(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
first, err := EnsureDaemonID("")
if err != nil {
@@ -43,7 +43,7 @@ func TestEnsureDaemonID_Persists(t *testing.T) {
func TestEnsureDaemonID_SharedAcrossProfiles(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
defaultID, err := EnsureDaemonID("")
if err != nil {
@@ -67,7 +67,7 @@ func TestEnsureDaemonID_SharedAcrossProfiles(t *testing.T) {
func TestEnsureDaemonID_PromotesPreChangeProfileFile(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
// Seed a per-profile daemon.id the way pre-#1220 daemons laid it out.
legacyID := uuid.Must(uuid.NewV7()).String()
@@ -102,7 +102,7 @@ func TestEnsureDaemonID_PromotesPreChangeProfileFile(t *testing.T) {
func TestEnsureDaemonID_RegeneratesCorruptFile(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
dir := filepath.Join(home, ".multica")
if err := os.MkdirAll(dir, 0o755); err != nil {
@@ -129,7 +129,7 @@ func TestEnsureDaemonID_RegeneratesCorruptFile(t *testing.T) {
func TestLegacyDaemonUUIDs_ScansProfileDirs(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
uuidA := uuid.Must(uuid.NewV7()).String()
uuidB := uuid.Must(uuid.NewV7()).String()
@@ -166,7 +166,7 @@ func TestLegacyDaemonUUIDs_ScansProfileDirs(t *testing.T) {
func TestLegacyDaemonUUIDs_MissingProfilesDirIsNil(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
ids, err := LegacyDaemonUUIDs()
if err != nil {
diff --git a/server/internal/daemon/local_skills_test.go b/server/internal/daemon/local_skills_test.go
index f3762aa769..3ddc4b8eb9 100644
--- a/server/internal/daemon/local_skills_test.go
+++ b/server/internal/daemon/local_skills_test.go
@@ -32,8 +32,7 @@ func writeTestLocalSkill(t *testing.T, root, rel string, files map[string]string
// Windows: os.UserHomeDir reads USERPROFILE and Hermes uses LOCALAPPDATA.
func setTestUserHome(t *testing.T, home string) {
t.Helper()
- t.Setenv("HOME", home)
- t.Setenv("USERPROFILE", home)
+ redirectTestHome(t, home)
t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local"))
}
@@ -73,7 +72,7 @@ func writeTestClaudePlugin(t *testing.T, home, id, name string, enabled bool) st
func TestListRuntimeLocalSkills_Claude(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "review-helper", map[string]string{
"SKILL.md": "---\nname: Review Helper\ndescription: Review pull requests\n---\n# Review Helper\n",
@@ -120,7 +119,7 @@ func TestListRuntimeLocalSkills_Claude(t *testing.T) {
func TestListRuntimeLocalSkills_Mcode(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".minimax", "skills"), "mcode-review", map[string]string{
"SKILL.md": "---\nname: MCode Review\ndescription: Review code with MiniMax Code\n---\n",
@@ -147,7 +146,7 @@ func TestListRuntimeLocalSkills_Mcode(t *testing.T) {
// ~/.codebuddy/skills/"). Discovery must use ~/.codebuddy/skills instead.
func TestListRuntimeLocalSkills_Codebuddy(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".codebuddy", "skills"), "review-helper", map[string]string{
"SKILL.md": "---\nname: CodeBuddy Review\ndescription: Review code with CodeBuddy\n---\n# CodeBuddy Review\n",
@@ -186,7 +185,7 @@ func TestListRuntimeLocalSkills_Codebuddy(t *testing.T) {
func TestRuntimeLocalSkills_CodebuddyExcludesClaudePluginSkills(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".codebuddy", "skills"), "codebuddy-only", map[string]string{
"SKILL.md": "---\nname: CodeBuddy Only\n---\n",
@@ -221,7 +220,7 @@ func TestRuntimeLocalSkills_CodebuddyExcludesClaudePluginSkills(t *testing.T) {
func TestListRuntimeLocalSkills_ClaudeEnabledPlugin(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
"SKILL.md": "---\nname: Design to code\ndescription: Turn a design into code\n---\n# Design\n",
@@ -253,7 +252,7 @@ func TestListRuntimeLocalSkills_ClaudeEnabledPlugin(t *testing.T) {
func TestListRuntimeLocalSkills_ClaudeDisabledPluginIsHidden(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", false)
writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
"SKILL.md": "---\nname: Design to code\n---\n",
@@ -270,7 +269,7 @@ func TestListRuntimeLocalSkills_ClaudeDisabledPluginIsHidden(t *testing.T) {
func TestListRuntimeLocalSkills_Kiro(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".kiro", "skills"), "review-helper", map[string]string{
"SKILL.md": "---\nname: Kiro Review\ndescription: Review code with Kiro\n---\n# Kiro Review\n",
@@ -536,7 +535,7 @@ func writeTestHermesActiveProfile(t *testing.T, hermesHome, name string) {
func TestListRuntimeLocalSkills_GrokUsesGROKHOME(t *testing.T) {
home := t.TempDir()
grokHome := filepath.Join(t.TempDir(), "custom-grok-home")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("GROK_HOME", grokHome)
writeTestLocalSkill(t, filepath.Join(grokHome, "skills"), "review-helper", map[string]string{
"SKILL.md": "---\nname: Grok Home Review\ndescription: Review code\n---\n# Review\n",
@@ -571,7 +570,7 @@ func TestListRuntimeLocalSkills_GrokUsesGROKHOME(t *testing.T) {
func TestListRuntimeLocalSkills_QwenUsesQWENHOME(t *testing.T) {
home := t.TempDir()
qwenHome := filepath.Join(t.TempDir(), "custom-qwen-home")
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("QWEN_HOME", qwenHome)
writeTestLocalSkill(t, filepath.Join(qwenHome, "skills"), "review-helper", map[string]string{
"SKILL.md": "---\nname: Qwen Home Review\ndescription: Review code\n---\n# Review\n",
@@ -611,7 +610,7 @@ func TestListRuntimeLocalSkills_QwenUsesQWENHOME(t *testing.T) {
// listRuntimeLocalSkills must follow those symlinks.
func TestListRuntimeLocalSkills_FollowsSymlinkedSkillDirs(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
// Real skill lives outside the runtime root.
target := writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "lark-doc", map[string]string{
@@ -666,7 +665,7 @@ func TestListRuntimeLocalSkills_FollowsSymlinkedSkillDirs(t *testing.T) {
func TestListRuntimeLocalSkills_CodexUsesSharedCODEXHOME(t *testing.T) {
home := t.TempDir()
codexHome := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("CODEX_HOME", codexHome)
writeTestLocalSkill(t, filepath.Join(codexHome, "skills"), "debugger", map[string]string{
@@ -706,7 +705,7 @@ func TestListRuntimeLocalSkills_CodexUsesSharedCODEXHOME(t *testing.T) {
// bundle, not separate skills.
func TestListRuntimeLocalSkills_DescendsIntoNestedSkillDirs(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
root := filepath.Join(home, ".config", "opencode", "skills")
@@ -745,7 +744,7 @@ func TestListRuntimeLocalSkills_DescendsIntoNestedSkillDirs(t *testing.T) {
func TestLoadRuntimeLocalSkillBundle_OpenCode(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".config", "opencode", "skills"), "release/reporter", map[string]string{
"SKILL.md": "---\nname: Release Reporter\ndescription: Summarize release notes\n---\n# Release Reporter\n",
@@ -782,7 +781,7 @@ func TestLoadRuntimeLocalSkillBundle_OpenCode(t *testing.T) {
func TestListRuntimeLocalSkills_OpenClaw(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".openclaw", "skills"), "planner", map[string]string{
"SKILL.md": "# Planner\n",
@@ -805,7 +804,7 @@ func TestListRuntimeLocalSkills_OpenClaw(t *testing.T) {
func TestLoadRuntimeLocalSkillBundle_Cursor(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".cursor", "skills"), "docs-helper", map[string]string{
"SKILL.md": "---\nname: Docs Helper\n---\n# Docs Helper\n",
@@ -840,7 +839,7 @@ func TestLoadRuntimeLocalSkillBundle_Cursor(t *testing.T) {
// directory at all) must be discovered and tagged Root="universal".
func TestListRuntimeLocalSkills_DiscoversUniversalAgentsRoot(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "universal-helper", map[string]string{
"SKILL.md": "---\nname: Universal Helper\ndescription: Cross-tool skill\n---\n# Universal Helper\n",
@@ -880,7 +879,7 @@ func TestListRuntimeLocalSkills_DiscoversUniversalAgentsRoot(t *testing.T) {
// can't fetch.
func TestLoadRuntimeLocalSkillBundle_ImportsFromUniversalRoot(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "shared-skill", map[string]string{
"SKILL.md": "---\nname: Shared Skill\ndescription: Imported from agents root\n---\n# Shared Skill\n",
@@ -913,7 +912,7 @@ func TestLoadRuntimeLocalSkillBundle_ImportsFromUniversalRoot(t *testing.T) {
// provider-root key resolves to.
func TestLocalSkills_ProviderRootWinsOnKeyConflict(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "dup", map[string]string{
"SKILL.md": "---\nname: Provider Copy\n---\n# provider\n",
@@ -955,7 +954,7 @@ func TestLocalSkills_ProviderRootWinsOnKeyConflict(t *testing.T) {
// Both roots contribute their non-conflicting skills, merged and sorted once.
func TestListRuntimeLocalSkills_MergesBothRoots(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "provider-only", map[string]string{
"SKILL.md": "---\nname: Provider Only\n---\n",
@@ -992,7 +991,7 @@ func TestListRuntimeLocalSkills_MergesBothRoots(t *testing.T) {
// returns empty" guarantee, now per-root.)
func TestListRuntimeLocalSkills_MissingUniversalRootIsNotAnError(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "only-provider", map[string]string{
"SKILL.md": "---\nname: Only Provider\n---\n",
@@ -1014,7 +1013,7 @@ func TestListRuntimeLocalSkills_MissingUniversalRootIsNotAnError(t *testing.T) {
// Both roots missing → empty list, no error.
func TestListRuntimeLocalSkills_BothRootsMissing(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
skills, supported, err := listRuntimeLocalSkills("claude")
if err != nil {
@@ -1031,7 +1030,7 @@ func TestListRuntimeLocalSkills_BothRootsMissing(t *testing.T) {
// Nested layouts (a skill two levels deep) work in the universal root too.
func TestListRuntimeLocalSkills_NestedSkillInUniversalRoot(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "release/reporter", map[string]string{
"SKILL.md": "---\nname: Release Reporter\n---\n",
@@ -1061,7 +1060,7 @@ func TestListRuntimeLocalSkills_NestedSkillInUniversalRoot(t *testing.T) {
// the provider root genuinely lacks the key (IsNotExist).
func TestLoadRuntimeLocalSkillBundle_FallsThroughToUniversalOnNotExist(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
// Provider root exists but does NOT contain "only-universal".
writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "something-else", map[string]string{
@@ -1090,7 +1089,7 @@ func TestLoadRuntimeLocalSkillBundle_FallsThroughToUniversalOnNotExist(t *testin
// the read fails ("is a directory") while the dir itself exists.
func TestLoadRuntimeLocalSkillBundle_DoesNotMaskReadErrorWithUniversalFallback(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
clashDir := filepath.Join(home, ".claude", "skills", "clash")
if err := os.MkdirAll(filepath.Join(clashDir, "SKILL.md"), 0o755); err != nil {
@@ -1116,7 +1115,7 @@ func TestLoadRuntimeLocalSkillBundle_DoesNotMaskReadErrorWithUniversalFallback(t
// root) and `foo` (from the agents root). A shared visited set would drop one.
func TestListRuntimeLocalSkills_PerRootVisitedAllowsCrossRootSymlinkAlias(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
target := writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "foo", map[string]string{
"SKILL.md": "---\nname: Foo\n---\n",
@@ -1162,7 +1161,7 @@ func TestListRuntimeLocalSkills_PerRootVisitedAllowsCrossRootSymlinkAlias(t *tes
// disagree.
func TestLoadRuntimeLocalSkillBundle_ProviderDirWithoutSkillMdFallsThrough(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
// Provider root has a same-key directory but NO SKILL.md (just a stray
// file), so it is NOT a valid skill.
@@ -1209,7 +1208,7 @@ func TestLoadRuntimeLocalSkillBundle_ProviderDirWithoutSkillMdFallsThrough(t *te
// a non-dir, so load must fall through too.
func TestLoadRuntimeLocalSkillBundle_ProviderNonDirFallsThrough(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
claudeRoot := filepath.Join(home, ".claude", "skills")
if err := os.MkdirAll(claudeRoot, 0o755); err != nil {
diff --git a/server/internal/daemon/pi_busy_retry_unix_test.go b/server/internal/daemon/pi_busy_retry_unix_test.go
index f663455732..38bb1b6cd7 100644
--- a/server/internal/daemon/pi_busy_retry_unix_test.go
+++ b/server/internal/daemon/pi_busy_retry_unix_test.go
@@ -23,7 +23,7 @@ import (
// from every future session lookup.
func TestRunTaskPiBusyRetryDoesNotRetireHealthySession(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
priorSessionID := filepath.Join(t.TempDir(), "busy-session.jsonl")
claim, err := os.OpenFile(priorSessionID, os.O_CREATE|os.O_RDWR, 0o600)
diff --git a/server/internal/daemon/runtime_mcp_test.go b/server/internal/daemon/runtime_mcp_test.go
index 3c42f28f59..3eff173acb 100644
--- a/server/internal/daemon/runtime_mcp_test.go
+++ b/server/internal/daemon/runtime_mcp_test.go
@@ -10,7 +10,7 @@ import (
func TestListRuntimeLocalMcpServersCodexRedactsDetails(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("CODEX_HOME", "")
configDir := filepath.Join(home, ".codex")
if err := os.MkdirAll(configDir, 0o755); err != nil {
@@ -44,7 +44,7 @@ enabled = false
}
func TestListRuntimeLocalMcpServersClaudeMissingConfig(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
servers, supported, err := listRuntimeLocalMcpServers("claude")
if err != nil {
t.Fatal(err)
@@ -56,7 +56,7 @@ func TestListRuntimeLocalMcpServersClaudeMissingConfig(t *testing.T) {
func TestListRuntimeLocalMcpServersOmpReadsNativeConfig(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
configDir := filepath.Join(home, ".omp", "agent")
if err := os.MkdirAll(configDir, 0o755); err != nil {
t.Fatal(err)
@@ -80,7 +80,7 @@ func TestListRuntimeLocalMcpServersOmpReadsNativeConfig(t *testing.T) {
func TestListRuntimeLocalMcpServersClaudeEnabledPlugin(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
config := `{"mcpServers":{"paper":{"type":"http","url":"http://127.0.0.1:29979/mcp"}}}`
if err := os.WriteFile(filepath.Join(installPath, "mcp.json"), []byte(config), 0o600); err != nil {
@@ -103,7 +103,7 @@ func TestListRuntimeLocalMcpServersClaudeEnabledPlugin(t *testing.T) {
}
func TestListRuntimeLocalMcpServersUnknownProvider(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
servers, supported, err := listRuntimeLocalMcpServers("future-runtime")
if err != nil {
t.Fatal(err)
@@ -114,7 +114,7 @@ func TestListRuntimeLocalMcpServersUnknownProvider(t *testing.T) {
}
func TestMergeRuntimeAndAgentMcpConfigOmpUsesAgentConfig(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
merged, err := mergeRuntimeAndAgentMcpConfig("omp", json.RawMessage(`{"mcpServers":{"agent":{"command":"agent-server"}}}`))
if err != nil {
t.Fatal(err)
@@ -132,7 +132,7 @@ func TestMergeRuntimeAndAgentMcpConfigOmpUsesAgentConfig(t *testing.T) {
func TestMergeRuntimeAndAgentMcpConfigClaudeCombinesAndAgentWins(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
runtimeConfig := `{"mcpServers":{"runtime-only":{"command":"runtime-cmd","env":{"TOKEN":"local-secret"}},"shared":{"command":"runtime-shared"}}}`
if err := os.WriteFile(filepath.Join(home, ".claude.json"), []byte(runtimeConfig), 0o600); err != nil {
t.Fatal(err)
@@ -171,7 +171,7 @@ func TestMergeRuntimeAndAgentMcpConfigClaudeCombinesAndAgentWins(t *testing.T) {
func TestMergeRuntimeAndAgentMcpConfigCodexNormalizesHeaders(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("CODEX_HOME", "")
configDir := filepath.Join(home, ".codex")
if err := os.MkdirAll(configDir, 0o755); err != nil {
@@ -212,7 +212,7 @@ args = ["mcp-server-fetch"]
}
func TestMergeRuntimeAndAgentMcpConfigNullKeepsNativeInheritance(t *testing.T) {
- t.Setenv("HOME", t.TempDir())
+ redirectTestHome(t, t.TempDir())
for _, raw := range []json.RawMessage{nil, json.RawMessage("null"), json.RawMessage(" null ")} {
merged, err := mergeRuntimeAndAgentMcpConfig("claude", raw)
if err != nil {
@@ -226,7 +226,7 @@ func TestMergeRuntimeAndAgentMcpConfigNullKeepsNativeInheritance(t *testing.T) {
func TestCodeArtsMcpConfigLoadsJSONCAndAgentWins(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("USERPROFILE", home)
configDir := filepath.Join(home, ".codeartsdoer")
if err := os.MkdirAll(configDir, 0o755); err != nil {
@@ -348,7 +348,7 @@ func TestCodebuddyUserMcpConfigPathHonorsConfigDirEnv(t *testing.T) {
func TestListRuntimeLocalMcpServersCodebuddyReadsItsOwnConfig(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("CODEBUDDY_CONFIG_DIR", "")
configDir := filepath.Join(home, ".codebuddy")
if err := os.MkdirAll(configDir, 0o755); err != nil {
@@ -383,7 +383,7 @@ func TestListRuntimeLocalMcpServersCodebuddyReadsItsOwnConfig(t *testing.T) {
// while losing scope precedence and the project-scope approval gate.
func TestMergeRuntimeAndAgentMcpConfigCodebuddyIsPassthrough(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("CODEBUDDY_CONFIG_DIR", "")
configDir := filepath.Join(home, ".codebuddy")
if err := os.MkdirAll(configDir, 0o755); err != nil {
@@ -512,7 +512,7 @@ func TestStripJSONCRejectsUnterminatedBlockComment(t *testing.T) {
// surfaces the problem rather than silently reporting zero servers.
func TestListRuntimeLocalMcpServersCodebuddyRejectsUnterminatedComment(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("CODEBUDDY_CONFIG_DIR", "")
configDir := filepath.Join(home, ".codebuddy")
if err := os.MkdirAll(configDir, 0o755); err != nil {
@@ -530,7 +530,7 @@ func TestListRuntimeLocalMcpServersCodebuddyRejectsUnterminatedComment(t *testin
func TestListRuntimeLocalMcpServersKimi(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("KIMI_CODE_HOME", "")
kimiHome := filepath.Join(home, ".kimi-code")
if err := os.MkdirAll(kimiHome, 0o755); err != nil {
@@ -555,7 +555,7 @@ func TestListRuntimeLocalMcpServersKimi(t *testing.T) {
// config untouched.
func TestMergeRuntimeAndAgentMcpConfigKimiIsPassthrough(t *testing.T) {
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("KIMI_CODE_HOME", "")
kimiHome := filepath.Join(home, ".kimi-code")
if err := os.MkdirAll(kimiHome, 0o755); err != nil {
diff --git a/server/internal/daemon/runtime_mcp_workspace_test.go b/server/internal/daemon/runtime_mcp_workspace_test.go
index bfe5c940b4..5d0bd39171 100644
--- a/server/internal/daemon/runtime_mcp_workspace_test.go
+++ b/server/internal/daemon/runtime_mcp_workspace_test.go
@@ -43,7 +43,7 @@ func writeOpencodeRuntimeConfig(t *testing.T, servers string) {
t.Helper()
home := t.TempDir()
- t.Setenv("HOME", home)
+ redirectTestHome(t, home)
t.Setenv("XDG_CONFIG_HOME", "")
dir := filepath.Join(home, ".config", "opencode")
if err := os.MkdirAll(dir, 0o755); err != nil {
diff --git a/server/internal/daemon/testmain_test.go b/server/internal/daemon/testmain_test.go
new file mode 100644
index 0000000000..1a91c5abf1
--- /dev/null
+++ b/server/internal/daemon/testmain_test.go
@@ -0,0 +1,48 @@
+// Copyright 2026 Multica. All rights reserved.
+
+package daemon
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// TestMain redirects the home environment variables to one scratch directory
+// for the whole binary before any test runs. Config paths resolve through
+// os.UserHomeDir — USERPROFILE on Windows, HOME elsewhere — while Hermes uses
+// LOCALAPPDATA on Windows. Process-wide redirection isolates tests that forget
+// their own redirect; per-test t.Setenv overrides still take precedence.
+func TestMain(m *testing.M) {
+ for _, key := range []string{
+ "MULTICA_AGENT_ID",
+ "MULTICA_TASK_ID",
+ "MULTICA_TOKEN",
+ "MULTICA_DAEMON_PORT",
+ "MULTICA_WORKSPACE_ID",
+ "MULTICA_SERVER_URL",
+ "MULTICA_TASK_CONFIG_ROOT",
+ } {
+ os.Unsetenv(key)
+ }
+
+ scratchHome, err := testutil.IsolateUserHome("multica-daemon-tests-home-")
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "isolate internal/daemon test home: %v\n", err)
+ os.Exit(1)
+ }
+ if err := os.Setenv("LOCALAPPDATA", filepath.Join(scratchHome, "AppData", "Local")); err != nil {
+ fmt.Fprintf(os.Stderr, "isolate internal/daemon LOCALAPPDATA: %v\n", err)
+ _ = os.RemoveAll(scratchHome)
+ os.Exit(1)
+ }
+
+ code := m.Run()
+ _ = os.RemoveAll(scratchHome)
+ os.Exit(code)
+}
+
+var redirectTestHome = testutil.RedirectUserHome
diff --git a/server/internal/integrations/ghsnapshot/refresh_db_test.go b/server/internal/integrations/ghsnapshot/refresh_db_test.go
index 62c3f001c2..3929287230 100644
--- a/server/internal/integrations/ghsnapshot/refresh_db_test.go
+++ b/server/internal/integrations/ghsnapshot/refresh_db_test.go
@@ -117,11 +117,19 @@ func TestListStaleUndecidedGitHubPRsExcludesDecidedAndRotatesCursor(t *testing.T
q := db.New(pool)
ctx := context.Background()
now := time.Unix(1_700_010_000, 0)
-
- settled := seedPRAt(t, pool, q, 111, "settled", 1, "S")
- oldest := seedPRAt(t, pool, q, 111, "oldest", 2, "O")
- running := seedPRAt(t, pool, q, 222, "running", 3, "R")
- newer := seedPRAt(t, pool, q, 222, "newer", 4, "N")
+ // Go runs DB-backed packages concurrently against one database. Keep this
+ // cursor test at the top of the BIGINT address space so ordinary fixtures
+ // from another package sort only after this test's bounded page wraps.
+ const (
+ firstInstallationID int64 = 1<<63 - 2
+ secondInstallationID int64 = 1<<63 - 1
+ beforeFixtures int64 = firstInstallationID - 1
+ )
+
+ settled := seedPRAt(t, pool, q, firstInstallationID, "settled", 1, "S")
+ oldest := seedPRAt(t, pool, q, firstInstallationID, "oldest", 2, "O")
+ running := seedPRAt(t, pool, q, secondInstallationID, "running", 3, "R")
+ newer := seedPRAt(t, pool, q, secondInstallationID, "newer", 4, "N")
prs := []db.GithubPullRequest{settled, oldest, running, newer}
t.Cleanup(func() {
for _, pr := range prs {
@@ -155,7 +163,7 @@ func TestListStaleUndecidedGitHubPRsExcludesDecidedAndRotatesCursor(t *testing.T
rows, err := q.ListStaleUndecidedGitHubPRs(ctx, db.ListStaleUndecidedGitHubPRsParams{
OlderThan: tsFromTime(now.Add(-10 * time.Minute)),
- AfterInstallationID: 0,
+ AfterInstallationID: beforeFixtures,
AfterRepoOwner: "",
AfterRepoName: "",
AfterPrNumber: 0,
@@ -179,7 +187,7 @@ func TestListStaleUndecidedGitHubPRsExcludesDecidedAndRotatesCursor(t *testing.T
first, err := q.ListStaleUndecidedGitHubPRs(ctx, db.ListStaleUndecidedGitHubPRsParams{
OlderThan: tsFromTime(now.Add(-10 * time.Minute)),
- AfterInstallationID: 0,
+ AfterInstallationID: beforeFixtures,
AfterRepoOwner: "",
AfterRepoName: "",
AfterPrNumber: 0,
diff --git a/server/internal/testutil/doc.go b/server/internal/testutil/doc.go
index 0d40196b21..cb3fdfe3f8 100644
--- a/server/internal/testutil/doc.go
+++ b/server/internal/testutil/doc.go
@@ -1,7 +1,5 @@
-// Package testutil holds the fixtures the server's DB-backed tests build
-// their scenarios from: row builders that insert a fixture row and delete it
-// again when the test ends, and HTTP helpers that run one handler and assert
-// on what it wrote.
+// Package testutil holds shared server test infrastructure: DB fixture
+// builders, HTTP assertions, and process-environment isolation helpers.
//
// It exists because the cost of changing shared behaviour was scaling with
// the number of test files. Before this package `internal/handler` alone held
diff --git a/server/internal/testutil/home.go b/server/internal/testutil/home.go
new file mode 100644
index 0000000000..1412c42047
--- /dev/null
+++ b/server/internal/testutil/home.go
@@ -0,0 +1,50 @@
+// Copyright 2026 Multica. All rights reserved.
+
+package testutil
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+// EnvTB is the part of testing.T needed to redirect environment variables.
+type EnvTB interface {
+ Helper()
+ Setenv(key, value string)
+}
+
+// IsolateUserHome creates and installs a process-wide scratch home. Callers
+// must exit without running tests when this returns an error: continuing would
+// let home-relative test writes reach the user's real files.
+func IsolateUserHome(pattern string) (string, error) {
+ home, err := os.MkdirTemp("", pattern)
+ if err != nil {
+ return "", fmt.Errorf("create scratch home: %w", err)
+ }
+ cleanupError := func(err error) (string, error) {
+ _ = os.RemoveAll(home)
+ return "", err
+ }
+ for _, key := range []string{"HOME", "USERPROFILE"} {
+ if err := os.Setenv(key, home); err != nil {
+ return cleanupError(fmt.Errorf("set %s: %w", key, err))
+ }
+ }
+ resolved, err := os.UserHomeDir()
+ if err != nil {
+ return cleanupError(fmt.Errorf("verify scratch home: %w", err))
+ }
+ if filepath.Clean(resolved) != filepath.Clean(home) {
+ return cleanupError(fmt.Errorf("verify scratch home: os.UserHomeDir returned %q, want %q", resolved, home))
+ }
+ return home, nil
+}
+
+// RedirectUserHome points both home environment variables at dir. Go reads
+// HOME on Unix and USERPROFILE on Windows, so tests must always set the pair.
+func RedirectUserHome(t EnvTB, dir string) {
+ t.Helper()
+ t.Setenv("HOME", dir)
+ t.Setenv("USERPROFILE", dir)
+}