Skip to content

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

Go

fix(cli): isolate task profile state (#6407)

rongchenzheng586a624aa5f8
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx
index 9204307bb6..12512ee497 100644
--- a/apps/docs/content/docs/cli.mdx
+++ b/apps/docs/content/docs/cli.mdx
@@ -212,6 +212,10 @@ multica config show
multica config show --profile staging
```
+When the CLI runs inside a daemon-managed agent task, it does not load or modify these human-owned profile files. Multica API commands authenticate with the task-scoped credential injected by the daemon. `config show` and `config set` use private task-local state; human/local commands such as `login`, `logout`, `setup`, `workspace switch`, local runtime profile path changes, and `daemon` lifecycle or diagnostic commands are unavailable. `auth status` does not print token material in this context.
+
+This protects implicit Multica CLI profile resolution while preserving the normal `HOME` and XDG variables used by other provider tools. It is not an OS filesystem boundary: processes running as the same system user may still open an explicitly known path. Use a dedicated user, container, VM, or equivalent isolation when that stronger guarantee is required.
+
<Callout type="warning">
CLI configuration files contain tokens that can access Multica as you. Don't commit them to a repository, upload them to logs, or share them with others.
</Callout>
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.go
index f0fbc59d68..f26f59e6be 100644
--- a/server/cmd/multica/cmd_agent.go
+++ b/server/cmd/multica/cmd_agent.go
@@ -252,14 +252,9 @@ func resolveProfile(cmd *cobra.Command) string {
}
func newAPIClient(cmd *cobra.Command) (*cli.APIClient, error) {
- serverURL := resolveServerURL(cmd)
- workspaceID := resolveWorkspaceID(cmd)
+ taskContext := inDaemonManagedExecutionContext()
token := resolveToken(cmd)
-
- if serverURL == "" {
- return nil, fmt.Errorf("server URL not set: use --server-url flag, MULTICA_SERVER_URL env, or 'multica config set server_url <url>'")
- }
- if inDaemonManagedExecutionContext() && !strings.HasPrefix(token, "mat_") {
+ if taskContext && !strings.HasPrefix(token, "mat_") {
// When the ONLY daemon signal is a workdir marker (no MULTICA_AGENT_ID /
// MULTICA_TASK_ID / MULTICA_DAEMON_PORT), the likeliest cause outside a
// real task is a leftover marker from a crashed daemon task in a
@@ -273,6 +268,12 @@ func newAPIClient(cmd *cobra.Command) (*cli.APIClient, error) {
return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token")
}
+ serverURL := resolveServerURL(cmd)
+ workspaceID := resolveWorkspaceID(cmd)
+ if serverURL == "" {
+ return nil, fmt.Errorf("server URL not set: use --server-url flag, MULTICA_SERVER_URL env, or 'multica config set server_url <url>'")
+ }
+
client := cli.NewAPIClient(serverURL, workspaceID, token)
// When running inside a daemon task, attribute actions to the agent.
if agentID := os.Getenv("MULTICA_AGENT_ID"); agentID != "" {
@@ -294,6 +295,9 @@ func tryResolveServerURL(cmd *cobra.Command) string {
if val != "" {
return normalizeAPIBaseURL(val)
}
+ if inDaemonManagedExecutionContext() && strings.TrimSpace(os.Getenv(cli.TaskConfigRootEnv)) == "" {
+ return ""
+ }
profile := resolveProfile(cmd)
cfg, err := cli.LoadCLIConfigForProfile(profile)
if err == nil && cfg.ServerURL != "" {
@@ -342,6 +346,30 @@ func inDaemonManagedExecutionContext() bool {
return inAgentExecutionContext() || os.Getenv("MULTICA_DAEMON_PORT") != "" || hasDaemonTaskContextMarker()
}
+// requireTaskLocalConfigRoot prevents daemon-managed subprocesses that lost
+// part of their injected environment from silently resolving Multica state
+// below the daemon owner's HOME. Commands that intentionally support task-local
+// config (currently config show/set and auth status) call this before any load.
+func requireTaskLocalConfigRoot() error {
+ if !inDaemonManagedExecutionContext() {
+ return nil
+ }
+ if strings.TrimSpace(os.Getenv(cli.TaskConfigRootEnv)) == "" {
+ return fmt.Errorf("daemon-managed task requires a task-local Multica config root in %s", cli.TaskConfigRootEnv)
+ }
+ return nil
+}
+
+// requireHumanLocalCommand rejects commands whose purpose is to authenticate,
+// set up, or operate the human-owned local daemon/profile. Task API commands
+// remain available with the injected mat_ token; these local commands do not.
+func requireHumanLocalCommand(command string) error {
+ if inDaemonManagedExecutionContext() {
+ return fmt.Errorf("%s is not available inside a daemon-managed task", command)
+ }
+ return nil
+}
+
func hasDaemonTaskContextMarker() bool {
return daemonTaskContextMarkerPath() != ""
}
diff --git a/server/cmd/multica/cmd_auth.go b/server/cmd/multica/cmd_auth.go
index e930089d06..a7c7ae488c 100644
--- a/server/cmd/multica/cmd_auth.go
+++ b/server/cmd/multica/cmd_auth.go
@@ -122,6 +122,9 @@ func openBrowser(url string) error {
}
func runAuthLogin(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("login"); err != nil {
+ return err
+ }
if cmd.Flags().Changed("token") {
tokenFlag, _ := cmd.Flags().GetString("token")
// `--token mul_xxx` (space form) is what users actually type — that's
@@ -461,7 +464,14 @@ func runAuthLoginToken(cmd *cobra.Command, providedToken string) error {
}
func runAuthStatus(cmd *cobra.Command, _ []string) error {
+ if err := requireTaskLocalConfigRoot(); err != nil {
+ return err
+ }
+ taskContext := inDaemonManagedExecutionContext()
token := resolveToken(cmd)
+ if taskContext && !strings.HasPrefix(token, "mat_") {
+ return fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token")
+ }
serverURL := resolveServerURL(cmd)
if token == "" {
@@ -483,11 +493,15 @@ func runAuthStatus(cmd *cobra.Command, _ []string) error {
return nil
}
+ if taskContext {
+ fmt.Fprintf(os.Stderr, "Server: %s\nUser: %s (%s)\n", serverURL, me.Name, me.Email)
+ return nil
+ }
+
prefix := token
if len(prefix) > 12 {
prefix = prefix[:12] + "..."
}
-
fmt.Fprintf(os.Stderr, "Server: %s\nUser: %s (%s)\nToken: %s\n", serverURL, me.Name, me.Email, prefix)
return nil
}
@@ -532,6 +546,9 @@ const callbackSuccessHTML = `<!DOCTYPE html>
</html>`
func runAuthLogout(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("logout"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
cfg, _ := cli.LoadCLIConfigForProfile(profile)
if cfg.Token == "" {
diff --git a/server/cmd/multica/cmd_auth_test.go b/server/cmd/multica/cmd_auth_test.go
index e1e8fa73d9..4e6d76336a 100644
--- a/server/cmd/multica/cmd_auth_test.go
+++ b/server/cmd/multica/cmd_auth_test.go
@@ -1,8 +1,12 @@
package main
import (
+ "encoding/json"
"net"
+ "net/http"
+ "net/http/httptest"
"os"
+ "path/filepath"
"strings"
"testing"
@@ -17,6 +21,7 @@ func TestMain(m *testing.M) {
"MULTICA_DAEMON_PORT",
"MULTICA_WORKSPACE_ID",
"MULTICA_SERVER_URL",
+ "MULTICA_TASK_CONFIG_ROOT",
} {
os.Unsetenv(key)
}
@@ -326,6 +331,145 @@ func TestLoginTokenFlagParsing(t *testing.T) {
}
}
+func TestRunAuthStatusTaskContextDoesNotPrintCredential(t *testing.T) {
+ const fakeTaskToken = "mat_task_status_sentinel"
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TOKEN", fakeTaskToken)
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/me" {
+ http.NotFound(w, r)
+ return
+ }
+ if got := r.Header.Get("Authorization"); got != "Bearer "+fakeTaskToken {
+ t.Errorf("Authorization = %q, want fake task token", got)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]string{"name": "Task Agent", "email": "[email protected]"})
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+
+ stderr := captureStderr(t)
+ if err := runAuthStatus(testCmd(), nil); err != nil {
+ stderr.restore()
+ t.Fatalf("runAuthStatus: %v", err)
+ }
+ out := stderr.read()
+ for _, forbidden := range []string{fakeTaskToken, fakeTaskToken[:12], "Token:"} {
+ if strings.Contains(out, forbidden) {
+ t.Fatalf("auth status exposed credential material %q:\n%s", forbidden, out)
+ }
+ }
+ for _, want := range []string{"Server:", "Task Agent", "[email protected]"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("auth status output missing %q:\n%s", want, out)
+ }
+ }
+}
+
+func TestRunAuthStatusTaskContextRequiresTaskToken(t *testing.T) {
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", 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"))
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ requestCount := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requestCount++
+ _ = json.NewEncoder(w).Encode(map[string]string{"name": "Unexpected", "email": "[email protected]"})
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+
+ for _, tc := range []struct {
+ name string
+ token string
+ }{
+ {name: "missing token", token: ""},
+ {name: "human token", token: "mul_owner_sentinel"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("MULTICA_TOKEN", tc.token)
+ requestCount = 0
+ stderr := captureStderr(t)
+ err := runAuthStatus(testCmd(), nil)
+ stderr.restore()
+ out := stderr.read()
+ if err == nil || !strings.Contains(err.Error(), "task-scoped mat_ token") {
+ t.Fatalf("runAuthStatus error = %v, want task token requirement", err)
+ }
+ if requestCount != 0 {
+ t.Fatalf("auth status made %d request(s) without a task token", requestCount)
+ }
+ for _, forbidden := range []string{tc.token, "Token:"} {
+ if forbidden != "" && strings.Contains(out, forbidden) {
+ t.Fatalf("auth status exposed credential material %q: %s", forbidden, out)
+ }
+ }
+ })
+ }
+
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config content changed: got %q", after)
+ }
+}
+
+func TestHumanAuthCommandsFailClosedInTaskContext(t *testing.T) {
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", ownerHome)
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TOKEN", "mat_task_sentinel")
+ t.Setenv("MULTICA_SERVER_URL", "https://task.invalid")
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ loginCmd := testCmd()
+ loginCmd.Flags().String("token", "mul_fake_login", "")
+ _ = loginCmd.Flags().Set("token", "mul_fake_login")
+ for name, run := range map[string]func() error{
+ "login": func() error { return runAuthLogin(loginCmd, nil) },
+ "logout": func() error { return runAuthLogout(testCmd(), nil) },
+ } {
+ err := run()
+ if err == nil || !strings.Contains(err.Error(), "not available inside a daemon-managed task") {
+ t.Fatalf("%s error = %v, want task-context guard", name, err)
+ }
+ }
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config content changed: got %q", after)
+ }
+}
+
func TestNormalizeAPIBaseURL(t *testing.T) {
t.Run("converts websocket base URL", func(t *testing.T) {
if got := normalizeAPIBaseURL("ws://localhost:18106/ws"); got != "http://localhost:18106" {
diff --git a/server/cmd/multica/cmd_config.go b/server/cmd/multica/cmd_config.go
index 69321a6ba3..5f611a0ffb 100644
--- a/server/cmd/multica/cmd_config.go
+++ b/server/cmd/multica/cmd_config.go
@@ -78,6 +78,9 @@ func init() {
}
func runConfigShow(cmd *cobra.Command, _ []string) error {
+ if err := requireTaskLocalConfigRoot(); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
cfg, err := cli.LoadCLIConfigForProfile(profile)
if err != nil {
@@ -107,6 +110,9 @@ func runConfigShow(cmd *cobra.Command, _ []string) error {
}
func runConfigSet(cmd *cobra.Command, args []string) error {
+ if err := requireTaskLocalConfigRoot(); err != nil {
+ return err
+ }
key, value := args[0], args[1]
profile := resolveProfile(cmd)
diff --git a/server/cmd/multica/cmd_config_test.go b/server/cmd/multica/cmd_config_test.go
index 266967b63c..eec152c1bd 100644
--- a/server/cmd/multica/cmd_config_test.go
+++ b/server/cmd/multica/cmd_config_test.go
@@ -1,6 +1,8 @@
package main
import (
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -87,6 +89,92 @@ func TestRunConfigShowIncludesProfileAndDefaults(t *testing.T) {
}
}
+func TestRunConfigCommandsUseTaskLocalConfigWithoutTouchingOwner(t *testing.T) {
+ ownerHome := t.TempDir()
+ taskRoot := filepath.Join(t.TempDir(), "task-multica")
+ t.Setenv("HOME", ownerHome)
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", taskRoot)
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"workspace_id\": \"owner-workspace-sentinel\",\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ownerBefore, err := os.Stat(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ cmd := newConfigTestCmd()
+ if err := runConfigSet(cmd, []string{"server_url", "https://task.invalid"}); err != nil {
+ t.Fatalf("runConfigSet: %v", err)
+ }
+ out, err := captureStdout(t, func() error { return runConfigShow(cmd, nil) })
+ if err != nil {
+ t.Fatalf("runConfigShow: %v", err)
+ }
+ for _, forbidden := range []string{ownerHome, "https://owner.invalid", "owner-workspace-sentinel", "mul_owner_sentinel"} {
+ if strings.Contains(out, forbidden) {
+ t.Fatalf("task config output exposed owner sentinel %q:\n%s", forbidden, out)
+ }
+ }
+ if !strings.Contains(out, filepath.Join(taskRoot, "config.json")) || !strings.Contains(out, "https://task.invalid") {
+ t.Fatalf("task config output missing task-local state:\n%s", out)
+ }
+
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ownerAfter, err := os.Stat(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config content changed: got %q", after)
+ }
+ if !ownerAfter.ModTime().Equal(ownerBefore.ModTime()) {
+ t.Fatalf("owner config mtime changed: before %v after %v", ownerBefore.ModTime(), ownerAfter.ModTime())
+ }
+}
+
+func TestRunConfigCommandsFailClosedWithoutTaskRoot(t *testing.T) {
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", ownerHome)
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", "")
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ cmd := newConfigTestCmd()
+ if _, err := captureStdout(t, func() error { return runConfigShow(cmd, nil) }); err == nil || !strings.Contains(err.Error(), "task-local") {
+ t.Fatalf("runConfigShow error = %v, want missing task-local config root", err)
+ }
+ if err := runConfigSet(cmd, []string{"server_url", "https://task.invalid"}); err == nil || !strings.Contains(err.Error(), "task-local") {
+ t.Fatalf("runConfigSet error = %v, want missing task-local config root", err)
+ }
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config content changed: got %q", after)
+ }
+}
+
func TestRunConfigSetRejectsUnknownKey(t *testing.T) {
t.Setenv("HOME", t.TempDir())
@@ -272,7 +360,7 @@ func TestApplyConfigSetPollIntervalZeroDoesNotOverwrite(t *testing.T) {
}
// TestApplyConfigSetEmptyStringClearsTypedKeys — parity with the existing
-// "set server_url ''" clearing behavior. For int and duration keys, ""
+// "set server_url ”" clearing behavior. For int and duration keys, ""
// resets to the zero value rather than surfacing an Atoi/ParseDuration
// error the user didn't ask for.
func TestApplyConfigSetEmptyStringClearsTypedKeys(t *testing.T) {
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 33387f1f92..0dfa065405 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -151,6 +151,9 @@ type daemonRuntimeProbe struct {
}
func runDaemonProbeRuntimes(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("daemon probe-runtimes"); err != nil {
+ return err
+ }
cfg, err := daemon.LoadConfig(daemon.Overrides{
Profile: resolveProfile(cmd),
AllowNoAgents: true,
@@ -309,6 +312,9 @@ func requireDaemonAuth(profile string) error {
}
func runDaemonStart(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("daemon start"); err != nil {
+ return err
+ }
foreground, _ := cmd.Flags().GetBool("foreground")
if foreground {
return runDaemonForeground(cmd)
@@ -947,6 +953,9 @@ func requireDaemonRestartPreflight(cmd *cobra.Command, profile string) error {
}
func runDaemonRestart(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("daemon restart"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
healthPort := healthPortForProfile(profile)
@@ -993,6 +1002,9 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {
// --- daemon stop ---
func runDaemonStop(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("daemon stop"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
healthPort := healthPortForProfile(profile)
@@ -1075,6 +1087,9 @@ func requestDaemonShutdown(healthPort int) error {
// --- daemon status ---
func runDaemonStatus(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("daemon status"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
healthPort := healthPortForProfile(profile)
@@ -1145,6 +1160,9 @@ func printDaemonStatusReport(w io.Writer, label string, health map[string]any) {
// --- daemon logs ---
func runDaemonLogs(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("daemon logs"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
logPath := daemonLogPathForProfile(profile)
if _, err := os.Stat(logPath); os.IsNotExist(err) {
@@ -1338,6 +1356,9 @@ func resolveDaemonDisableSignal(flagValue bool, envName string, cfgValue bool) b
// --- daemon disk-usage ---
func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
+ if err := requireHumanLocalCommand("daemon disk-usage"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
rootOverride, _ := cmd.Flags().GetString("workspaces-root")
byWorkspace, _ := cmd.Flags().GetBool("by-workspace")
diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.go
index 963ac063c5..a46c7e12e7 100644
--- a/server/cmd/multica/cmd_daemon_test.go
+++ b/server/cmd/multica/cmd_daemon_test.go
@@ -49,6 +49,28 @@ func TestDaemonAlive(t *testing.T) {
}
}
+func TestDaemonLocalCommandsFailClosedInTaskContext(t *testing.T) {
+ 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"))
+
+ cases := map[string]func() error{
+ "probe-runtimes": func() error { return runDaemonProbeRuntimes(daemonProbeRuntimesCmd, nil) },
+ "start": func() error { return runDaemonStart(daemonStartCmd, nil) },
+ "restart": func() error { return runDaemonRestart(daemonRestartCmd, nil) },
+ "stop": func() error { return runDaemonStop(daemonStopCmd, nil) },
+ "status": func() error { return runDaemonStatus(daemonStatusCmd, nil) },
+ "logs": func() error { return runDaemonLogs(daemonLogsCmd, nil) },
+ "disk-usage": func() error { return runDaemonDiskUsage(daemonDiskUsageCmd, nil) },
+ }
+ for name, run := range cases {
+ err := run()
+ if err == nil || !strings.Contains(err.Error(), "not available inside a daemon-managed task") {
+ t.Fatalf("daemon %s error = %v, want task-context guard", name, err)
+ }
+ }
+}
+
func TestPrintDaemonStatusIncludesCLIVersion(t *testing.T) {
t.Parallel()
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index cf8de61b58..2a908b3bfb 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"net/url"
"os"
+ "path/filepath"
"strconv"
"strings"
"testing"
@@ -2879,6 +2880,98 @@ func TestRunIssueUpdateSendsPosition(t *testing.T) {
}
}
+func TestIssueReadCommandsUseInjectedTaskToken(t *testing.T) {
+ const fakeTaskToken = "mat_task_issue_sentinel"
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", ownerHome)
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TOKEN", fakeTaskToken)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-task")
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", t.TempDir())
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(ownerPath, []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"workspace_id\": \"owner-workspace-sentinel\",\n \"token\": \"mul_owner_sentinel\"\n}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ var gotPaths []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Authorization"); got != "Bearer "+fakeTaskToken {
+ t.Errorf("Authorization = %q, want injected fake task token", got)
+ }
+ gotPaths = append(gotPaths, r.URL.RequestURI())
+ switch r.URL.Path {
+ case "/api/issues":
+ if got := r.URL.Query().Get("workspace_id"); got != "ws-task" {
+ t.Errorf("workspace_id = %q, want task workspace", got)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"issues": []any{}, "total": 0})
+ case "/api/issues/MUL-46":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-uuid", "identifier": "MUL-46", "title": "Task isolation"})
+ case "/api/issues/issue-uuid":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-uuid", "identifier": "MUL-46", "title": "Task isolation"})
+ case "/api/issues/issue-uuid/task-runs":
+ _ = json.NewEncoder(w).Encode([]map[string]any{})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+
+ listCmd := newIssueListTestCmd()
+ _ = listCmd.Flags().Set("output", "json")
+ if _, err := captureStdout(t, func() error { return runIssueList(listCmd, nil) }); err != nil {
+ t.Fatalf("issue list: %v", err)
+ }
+
+ getCmd := &cobra.Command{Use: "get"}
+ getCmd.Flags().String("output", "json", "")
+ if _, err := captureStdout(t, func() error { return runIssueGet(getCmd, []string{"MUL-46"}) }); err != nil {
+ t.Fatalf("issue get: %v", err)
+ }
+
+ runsCmd := &cobra.Command{Use: "runs"}
+ runsCmd.Flags().String("output", "json", "")
+ runsCmd.Flags().Bool("full-id", false, "")
+ if _, err := captureStdout(t, func() error { return runIssueRuns(runsCmd, []string{"MUL-46"}) }); err != nil {
+ t.Fatalf("issue runs: %v", err)
+ }
+
+ if len(gotPaths) != 5 {
+ t.Fatalf("request paths = %v, want issue list + get resolution/get + runs resolution/list", gotPaths)
+ }
+}
+
+func TestIssueReadCommandsFailClosedWithoutTaskToken(t *testing.T) {
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", ownerHome)
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TOKEN", "")
+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:1")
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-task")
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", t.TempDir())
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(ownerPath, []byte("{\n \"token\": \"mul_owner_sentinel\"\n}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ cmd := newIssueListTestCmd()
+ err := runIssueList(cmd, nil)
+ if err == nil || !strings.Contains(err.Error(), "task-scoped mat_ token") {
+ t.Fatalf("issue list error = %v, want missing task token failure", err)
+ }
+}
+
func TestRunIssueListSendsSortAndDirection(t *testing.T) {
var gotQuery url.Values
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/cmd/multica/cmd_login.go b/server/cmd/multica/cmd_login.go
index 4da0ce9e89..88662ba8a1 100644
--- a/server/cmd/multica/cmd_login.go
+++ b/server/cmd/multica/cmd_login.go
@@ -64,6 +64,9 @@ func init() {
}
func runLogin(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("login"); err != nil {
+ return err
+ }
// Run the standard auth login flow.
if err := runAuthLogin(cmd, args); err != nil {
return err
diff --git a/server/cmd/multica/cmd_runtime_profile.go b/server/cmd/multica/cmd_runtime_profile.go
index 5992057669..1b84a16b55 100644
--- a/server/cmd/multica/cmd_runtime_profile.go
+++ b/server/cmd/multica/cmd_runtime_profile.go
@@ -287,6 +287,9 @@ func runRuntimeProfileDelete(cmd *cobra.Command, args []string) error {
}
func runRuntimeProfileSetPath(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("runtime profile set-path"); err != nil {
+ return err
+ }
profileID := args[0]
path, _ := cmd.Flags().GetString("path")
path = strings.TrimSpace(path)
@@ -315,6 +318,9 @@ func runRuntimeProfileSetPath(cmd *cobra.Command, args []string) error {
}
func runRuntimeProfileUnsetPath(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("runtime profile unset-path"); err != nil {
+ return err
+ }
profileID := args[0]
profile := resolveProfile(cmd)
diff --git a/server/cmd/multica/cmd_runtime_profile_test.go b/server/cmd/multica/cmd_runtime_profile_test.go
index 805535e7ae..c4cdac8243 100644
--- a/server/cmd/multica/cmd_runtime_profile_test.go
+++ b/server/cmd/multica/cmd_runtime_profile_test.go
@@ -4,6 +4,8 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
@@ -358,3 +360,36 @@ func TestRunRuntimeProfileSetPathPreservesExistingConfig(t *testing.T) {
t.Errorf("override not written: %#v", cfg.ProfileCommandOverrides)
}
}
+
+func TestRuntimeProfilePathMutationFailsClosedInTaskContext(t *testing.T) {
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", 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"))
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"profile_command_overrides\": {\"owner-prof\": \"/owner/bin\"},\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ setCmd := newProfileSetPathTestCmd()
+ _ = setCmd.Flags().Set("path", "/task/bin")
+ if err := runRuntimeProfileSetPath(setCmd, []string{"prof-1"}); err == nil || !strings.Contains(err.Error(), "not available inside a daemon-managed task") {
+ t.Fatalf("set-path error = %v, want task-context guard", err)
+ }
+ if err := runRuntimeProfileUnsetPath(newProfileUnsetPathTestCmd(), []string{"owner-prof"}); err == nil || !strings.Contains(err.Error(), "not available inside a daemon-managed task") {
+ t.Fatalf("unset-path error = %v, want task-context guard", err)
+ }
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config content changed: got %q", after)
+ }
+}
diff --git a/server/cmd/multica/cmd_setup.go b/server/cmd/multica/cmd_setup.go
index 0e0e656c8b..43b042f092 100644
--- a/server/cmd/multica/cmd_setup.go
+++ b/server/cmd/multica/cmd_setup.go
@@ -139,6 +139,9 @@ func formatURLChange(oldVal, newVal string) string {
}
func runSetupCloud(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("setup"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
cfg := cli.CLIConfig{
@@ -178,6 +181,9 @@ func runSetupCloud(cmd *cobra.Command, args []string) error {
}
func runSetupSelfHost(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("setup"); err != nil {
+ return err
+ }
profile := resolveProfile(cmd)
// Resolve the target URLs before confirming the overwrite so the prompt can
diff --git a/server/cmd/multica/cmd_setup_test.go b/server/cmd/multica/cmd_setup_test.go
index 8ff430de10..a82c29d63f 100644
--- a/server/cmd/multica/cmd_setup_test.go
+++ b/server/cmd/multica/cmd_setup_test.go
@@ -2,6 +2,8 @@ package main
import (
"bytes"
+ "os"
+ "path/filepath"
"strings"
"testing"
@@ -433,3 +435,37 @@ func TestServerHostIsLocal(t *testing.T) {
})
}
}
+
+func TestSetupCommandsFailClosedInTaskContext(t *testing.T) {
+ ownerHome := t.TempDir()
+ t.Setenv("HOME", 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"))
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ for name, run := range map[string]func() error{
+ "cloud": func() error { return runSetupCloud(setupCmd, nil) },
+ "self-host": func() error { return runSetupSelfHost(setupSelfHostCmd, nil) },
+ } {
+ err := run()
+ if err == nil || !strings.Contains(err.Error(), "not available inside a daemon-managed task") {
+ t.Fatalf("setup %s error = %v, want task-context guard", name, err)
+ }
+ }
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config content changed: got %q", after)
+ }
+}
diff --git a/server/cmd/multica/cmd_workspace.go b/server/cmd/multica/cmd_workspace.go
index 17b9cacbf3..c47daf8138 100644
--- a/server/cmd/multica/cmd_workspace.go
+++ b/server/cmd/multica/cmd_workspace.go
@@ -352,6 +352,9 @@ func resolveWorkspaceRef(ctx context.Context, cmd *cobra.Command, input string)
}
func runWorkspaceSwitch(cmd *cobra.Command, args []string) error {
+ if err := requireHumanLocalCommand("workspace switch"); err != nil {
+ return err
+ }
ctx, cancel := cli.APIContext(context.Background())
defer cancel()
diff --git a/server/cmd/multica/cmd_workspace_test.go b/server/cmd/multica/cmd_workspace_test.go
index a212bff855..3b7c436cce 100644
--- a/server/cmd/multica/cmd_workspace_test.go
+++ b/server/cmd/multica/cmd_workspace_test.go
@@ -177,8 +177,8 @@ func TestRunWorkspaceCreateRequiresSlug(t *testing.T) {
func TestRunWorkspaceCreateRejectsDualStdin(t *testing.T) {
cmd := newWorkspaceCreateTestCmd()
for name, value := range map[string]string{
- "name": "Growth Team",
- "slug": "growth-team",
+ "name": "Growth Team",
+ "slug": "growth-team",
"description-stdin": "true",
"context-stdin": "true",
} {
@@ -198,8 +198,8 @@ func TestRunWorkspaceCreateRejectsDualStdin(t *testing.T) {
func TestRunWorkspaceCreateReadsDescriptionFromStdin(t *testing.T) {
cmd := newWorkspaceCreateTestCmd()
for name, value := range map[string]string{
- "name": "Growth Team",
- "slug": "growth-team",
+ "name": "Growth Team",
+ "slug": "growth-team",
"description-stdin": "true",
} {
if err := cmd.Flags().Set(name, value); err != nil {
@@ -347,6 +347,21 @@ func TestRunWorkspaceSwitch(t *testing.T) {
})
}
+func TestRunWorkspaceSwitchFailsClosedInTaskContext(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("MULTICA_AGENT_ID", "agent-test")
+ t.Setenv("MULTICA_TASK_ID", "task-test")
+ t.Setenv("MULTICA_TOKEN", "mat_task_sentinel")
+ t.Setenv("MULTICA_SERVER_URL", "https://task.invalid")
+ t.Setenv("MULTICA_WORKSPACE_ID", "task-workspace")
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
+
+ err := runWorkspaceSwitch(newWorkspaceSwitchTestCmd(), []string{"target"})
+ if err == nil || !strings.Contains(err.Error(), "not available inside a daemon-managed task") {
+ t.Fatalf("runWorkspaceSwitch error = %v, want task-context guard before API or profile access", err)
+ }
+}
+
func TestResolveWorkspaceByIDOrSlug(t *testing.T) {
workspaces := []workspaceSummary{
{ID: "11111111-1111-1111-1111-111111111111", Name: "Alpha", Slug: "alpha"},
diff --git a/server/internal/cli/config.go b/server/internal/cli/config.go
index 3dae2d2d34..ca40535bf9 100644
--- a/server/internal/cli/config.go
+++ b/server/internal/cli/config.go
@@ -6,9 +6,18 @@ import (
"fmt"
"os"
"path/filepath"
+ "strings"
)
-const defaultCLIConfigPath = ".multica/config.json"
+const (
+ defaultCLIConfigPath = ".multica/config.json"
+
+ // TaskConfigRootEnv points daemon-managed CLI invocations at a private,
+ // per-task Multica config directory. It is deliberately Multica-specific:
+ // phase-one hardening keeps the real HOME/XDG environment available to
+ // provider tooling while preventing implicit Owner-profile discovery.
+ TaskConfigRootEnv = "MULTICA_TASK_CONFIG_ROOT"
+)
// CLIConfig holds persistent CLI settings.
type CLIConfig struct {
@@ -192,28 +201,78 @@ func CLIConfigPath() (string, error) {
// CLIConfigPathForProfile returns the config file path for the given profile.
// An empty profile returns the default path (~/.multica/config.json).
// A named profile returns ~/.multica/profiles/<name>/config.json.
+// When TaskConfigRootEnv is set by the daemon, the same profile layout is
+// rooted directly below that private task directory instead of the user's home.
func CLIConfigPathForProfile(profile string) (string, error) {
- home, err := os.UserHomeDir()
+ root, taskLocal, err := multicaConfigRoot()
if err != nil {
return "", fmt.Errorf("resolve CLI config path: %w", err)
}
+ if taskLocal {
+ if err := validateTaskLocalProfile(profile); err != nil {
+ return "", fmt.Errorf("resolve CLI config path: %w", err)
+ }
+ }
if profile == "" {
- return filepath.Join(home, defaultCLIConfigPath), nil
+ if taskLocal {
+ return filepath.Join(root, "config.json"), nil
+ }
+ return filepath.Join(root, defaultCLIConfigPath), nil
}
- return filepath.Join(home, ".multica", "profiles", profile, "config.json"), nil
+ if taskLocal {
+ return filepath.Join(root, "profiles", profile, "config.json"), nil
+ }
+ return filepath.Join(root, ".multica", "profiles", profile, "config.json"), nil
}
// ProfileDir returns the base directory for a profile's state files (pid, log).
// An empty profile returns ~/.multica/. A named profile returns ~/.multica/profiles/<name>/.
+// Task invocations resolve the equivalent paths below TaskConfigRootEnv.
func ProfileDir(profile string) (string, error) {
- home, err := os.UserHomeDir()
+ root, taskLocal, err := multicaConfigRoot()
if err != nil {
return "", fmt.Errorf("resolve profile dir: %w", err)
}
+ if taskLocal {
+ if err := validateTaskLocalProfile(profile); err != nil {
+ return "", fmt.Errorf("resolve profile dir: %w", err)
+ }
+ }
if profile == "" {
- return filepath.Join(home, ".multica"), nil
+ if taskLocal {
+ return root, nil
+ }
+ return filepath.Join(root, ".multica"), nil
+ }
+ if taskLocal {
+ return filepath.Join(root, "profiles", profile), nil
}
- return filepath.Join(home, ".multica", "profiles", profile), nil
+ return filepath.Join(root, ".multica", "profiles", profile), nil
+}
+
+func multicaConfigRoot() (root string, taskLocal bool, err error) {
+ if rawRoot := strings.TrimSpace(os.Getenv(TaskConfigRootEnv)); rawRoot != "" {
+ root := filepath.Clean(rawRoot)
+ if !filepath.IsAbs(root) {
+ return "", false, fmt.Errorf("%s must be an absolute path", TaskConfigRootEnv)
+ }
+ return root, true, nil
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", false, err
+ }
+ return home, false, nil
+}
+
+func validateTaskLocalProfile(profile string) error {
+ if profile == "" {
+ return nil
+ }
+ if profile == "." || profile == ".." || filepath.IsAbs(profile) || strings.ContainsAny(profile, `/\\`) || filepath.Clean(profile) != profile {
+ return fmt.Errorf("invalid task-local Multica profile name %q", profile)
+ }
+ return nil
}
// LoadCLIConfig reads the CLI config from disk (default profile).
@@ -253,9 +312,31 @@ func SaveCLIConfigForProfile(cfg CLIConfig, profile string) error {
return err
}
dir := filepath.Dir(path)
- if err := os.MkdirAll(dir, 0o755); err != nil {
+ dirMode := os.FileMode(0o755)
+ if strings.TrimSpace(os.Getenv(TaskConfigRootEnv)) != "" {
+ dirMode = 0o700
+ }
+ if err := os.MkdirAll(dir, dirMode); err != nil {
return fmt.Errorf("create CLI config directory: %w", err)
}
+ if dirMode == 0o700 {
+ root, _, err := multicaConfigRoot()
+ if err != nil {
+ return fmt.Errorf("resolve task-local CLI config root: %w", err)
+ }
+ for current := dir; ; current = filepath.Dir(current) {
+ if err := os.Chmod(current, 0o700); err != nil {
+ return fmt.Errorf("restrict task-local CLI config directory: %w", err)
+ }
+ if current == root {
+ break
+ }
+ parent := filepath.Dir(current)
+ if parent == current {
+ return fmt.Errorf("task-local CLI config directory %q escapes root %q", dir, root)
+ }
+ }
+ }
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("encode CLI config: %w", err)
diff --git a/server/internal/cli/config_test.go b/server/internal/cli/config_test.go
index 8b4a35dd8e..1e643a572d 100644
--- a/server/internal/cli/config_test.go
+++ b/server/internal/cli/config_test.go
@@ -336,3 +336,101 @@ func TestCLIConfig_DaemonKnobs_RoundTrip(t *testing.T) {
t.Errorf("AgentTimeout tri-state lost: got %v, want &\"0s\"", loaded.AgentTimeout)
}
}
+
+func TestCLIConfig_TaskRootOverridesOwnerHome(t *testing.T) {
+ ownerHome := t.TempDir()
+ taskRoot := filepath.Join(t.TempDir(), "task-multica")
+ t.Setenv("HOME", ownerHome)
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", taskRoot)
+
+ ownerPath := filepath.Join(ownerHome, ".multica", "config.json")
+ if err := os.MkdirAll(filepath.Dir(ownerPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ownerBytes := []byte("{\n \"server_url\": \"https://owner.invalid\",\n \"token\": \"mul_owner_sentinel\"\n}\n")
+ if err := os.WriteFile(ownerPath, ownerBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(taskRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := SaveCLIConfigForProfile(CLIConfig{ServerURL: "https://task.invalid"}, "dev"); err != nil {
+ t.Fatalf("SaveCLIConfigForProfile: %v", err)
+ }
+
+ path, err := CLIConfigPathForProfile("dev")
+ if err != nil {
+ t.Fatalf("CLIConfigPathForProfile: %v", err)
+ }
+ wantPath := filepath.Join(taskRoot, "profiles", "dev", "config.json")
+ if path != wantPath {
+ t.Fatalf("path = %q, want task-local path %q", path, wantPath)
+ }
+ loaded, err := LoadCLIConfigForProfile("dev")
+ if err != nil {
+ t.Fatalf("LoadCLIConfigForProfile: %v", err)
+ }
+ if loaded.ServerURL != "https://task.invalid" || loaded.Token != "" {
+ t.Fatalf("loaded task config = %#v, want task-only settings", loaded)
+ }
+ after, err := os.ReadFile(ownerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(ownerBytes) {
+ t.Fatalf("owner config was modified: got %q, want original sentinel", after)
+ }
+ for _, dir := range []string{taskRoot, filepath.Join(taskRoot, "profiles"), filepath.Join(taskRoot, "profiles", "dev")} {
+ info, err := os.Stat(dir)
+ if err != nil {
+ t.Fatalf("stat task config directory %q: %v", dir, err)
+ }
+ if got := info.Mode().Perm(); got != 0o700 {
+ t.Errorf("task config directory %q mode = %#o, want 0700", dir, got)
+ }
+ }
+ info, err := os.Stat(wantPath)
+ if err != nil {
+ t.Fatalf("stat task config file: %v", err)
+ }
+ if got := info.Mode().Perm(); got != 0o600 {
+ t.Errorf("task config file mode = %#o, want 0600", got)
+ }
+}
+
+func TestCLIConfig_NoTaskRootKeepsInteractiveHomeResolution(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", "")
+
+ path, err := CLIConfigPathForProfile("dev")
+ if err != nil {
+ t.Fatalf("CLIConfigPathForProfile: %v", err)
+ }
+ want := filepath.Join(home, ".multica", "profiles", "dev", "config.json")
+ if path != want {
+ t.Fatalf("path = %q, want interactive path %q", path, want)
+ }
+}
+
+func TestCLIConfig_TaskRootRejectsProfilePathTraversal(t *testing.T) {
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "task-multica"))
+
+ for _, profile := range []string{".", "..", "../owner", "nested/profile", filepath.Join(string(filepath.Separator), "owner")} {
+ if path, err := CLIConfigPathForProfile(profile); err == nil {
+ t.Errorf("CLIConfigPathForProfile(%q) = %q, want invalid task profile error", profile, path)
+ }
+ if dir, err := ProfileDir(profile); err == nil {
+ t.Errorf("ProfileDir(%q) = %q, want invalid task profile error", profile, dir)
+ }
+ }
+}
+
+func TestCLIConfig_TaskRootMustBeAbsolute(t *testing.T) {
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", "relative/task-multica")
+
+ if _, err := CLIConfigPath(); err == nil || !strings.Contains(err.Error(), "must be an absolute path") {
+ t.Fatalf("CLIConfigPath error = %v, want absolute path validation", err)
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index c7884232fc..df0985cb30 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -133,6 +133,23 @@ func taskScopedAuthToken(task Task) (string, error) {
return token, nil
}
+func taskMulticaEnvironment(task Task, agentName, token, configRoot, serverURL string, healthPort, slot int, tempDir string) map[string]string {
+ return map[string]string{
+ "MULTICA_TOKEN": token,
+ cli.TaskConfigRootEnv: configRoot,
+ "MULTICA_SERVER_URL": serverURL,
+ "MULTICA_DAEMON_PORT": strconv.Itoa(healthPort),
+ "MULTICA_WORKSPACE_ID": task.WorkspaceID,
+ "MULTICA_AGENT_NAME": agentName,
+ "MULTICA_AGENT_ID": task.AgentID,
+ "MULTICA_TASK_ID": task.ID,
+ "MULTICA_TASK_SLOT": strconv.Itoa(slot),
+ "TMPDIR": tempDir,
+ "TMP": tempDir,
+ "TEMP": tempDir,
+ }
+}
+
// taskRunner executes a single agent task and returns the result.
// Extracted as an interface so tests can inject a fake without spawning real
// agent processes, while keeping test scaffolding out of the production struct.
@@ -5990,19 +6007,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
taskLog.Error("task auth token invalid; refusing to start agent", "error", err)
return TaskResult{}, err
}
- agentEnv := map[string]string{
- "MULTICA_TOKEN": agentToken,
- "MULTICA_SERVER_URL": d.cfg.ServerBaseURL,
- "MULTICA_DAEMON_PORT": fmt.Sprintf("%d", d.cfg.HealthPort),
- "MULTICA_WORKSPACE_ID": task.WorkspaceID,
- "MULTICA_AGENT_NAME": agentName,
- "MULTICA_AGENT_ID": task.AgentID,
- "MULTICA_TASK_ID": task.ID,
- "MULTICA_TASK_SLOT": strconv.Itoa(slot),
- "TMPDIR": taskTempDir,
- "TMP": taskTempDir,
- "TEMP": taskTempDir,
- }
+ agentEnv := taskMulticaEnvironment(task, agentName, agentToken, env.MulticaConfigRoot, d.cfg.ServerBaseURL, d.cfg.HealthPort, slot, taskTempDir)
if checkoutMode := repoCheckoutModeFor(provider, runtime.GOOS); checkoutMode != "" {
agentEnv[repoCheckoutModeEnv] = checkoutMode
}
@@ -6039,10 +6044,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if env.CodexHome != "" {
agentEnv["CODEX_HOME"] = env.CodexHome
}
- // HOME and the XDG base dirs are deliberately not touched here: tasks run
- // with the daemon user's real home on every platform, so host CLI config
- // and credentials resolve inside a task exactly as they do in the daemon
- // user's shell (MUL-5578).
+ // HOME and the XDG base dirs are deliberately not touched here: provider
+ // tools such as gh, aws, kubectl, and npm continue resolving the daemon
+ // user's existing state (MUL-5578). The Multica CLI is the exception:
+ // MULTICA_TASK_CONFIG_ROOT above redirects its implicit profile lookup to
+ // private task-local state and prevents Owner-profile fallback.
// (Hermes HERMES_HOME is applied after custom_env below so the per-task
// overlay can win over a user-set HERMES_HOME; see
// layerCustomEnvAndHermesHome.)
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index bf5de16c3e..7fc42c9af8 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log/slog"
+ "maps"
"net/http"
"net/http/httptest"
"os"
@@ -339,11 +340,12 @@ func TestConfigureCodexTaskShellEnvironment(t *testing.T) {
"MULTICA_LLM_API_KEY=daemon-secret",
}
agentEnv := map[string]string{
- "CUSTOM_ACCESS_TOKEN": "agent-secret",
- "CUSTOM_FLAG": "enabled",
- "UNAUTHORIZED_TOKEN": "daemon-secret",
- "MULTICA_SERVER_URL": "https://task.example",
- "MULTICA_TOKEN": "mat_task",
+ "CUSTOM_ACCESS_TOKEN": "agent-secret",
+ "CUSTOM_FLAG": "enabled",
+ "UNAUTHORIZED_TOKEN": "daemon-secret",
+ "MULTICA_TASK_CONFIG_ROOT": "/task/multica-config",
+ "MULTICA_SERVER_URL": "https://task.example",
+ "MULTICA_TOKEN": "mat_task",
}
agentCustomEnv := map[string]string{
"CUSTOM_ACCESS_TOKEN": "agent-secret",
@@ -357,7 +359,7 @@ func TestConfigureCodexTaskShellEnvironment(t *testing.T) {
t.Fatalf("read config.toml: %v", err)
}
config := string(data)
- for _, want := range []string{"SystemRoot", "USERPROFILE", "CUSTOM_ACCESS_TOKEN", "CUSTOM_FLAG", "MULTICA_SERVER_URL", "MULTICA_TOKEN"} {
+ for _, want := range []string{"SystemRoot", "USERPROFILE", "CUSTOM_ACCESS_TOKEN", "CUSTOM_FLAG", "MULTICA_TASK_CONFIG_ROOT", "MULTICA_SERVER_URL", "MULTICA_TOKEN"} {
if !strings.Contains(config, want) {
t.Errorf("config.toml missing %q:\n%s", want, config)
}
@@ -401,9 +403,10 @@ func TestCodexTaskShellEnvInheritsRealHome(t *testing.T) {
// What runTask layers on top for a Codex task: task identity plus the
// task-scoped CODEX_HOME, and — since MUL-5578 — no HOME/XDG entry.
explicit := map[string]string{
- "CODEX_HOME": codexHome,
- "MULTICA_TOKEN": "mat_task",
- "MULTICA_SERVER_URL": "https://task.example",
+ "CODEX_HOME": codexHome,
+ "MULTICA_TASK_CONFIG_ROOT": "/task/multica-config",
+ "MULTICA_TOKEN": "mat_task",
+ "MULTICA_SERVER_URL": "https://task.example",
}
if err := configureCodexTaskShellEnvironment("codex", codexHome, inherited, explicit, nil, slog.Default()); err != nil {
@@ -435,6 +438,9 @@ func TestCodexTaskShellEnvInheritsRealHome(t *testing.T) {
if !slices.Contains(include, "CODEX_HOME") {
t.Errorf("include_only missing CODEX_HOME, got %v", include)
}
+ if !slices.Contains(include, "MULTICA_TASK_CONFIG_ROOT") {
+ t.Errorf("include_only missing MULTICA_TASK_CONFIG_ROOT, got %v", include)
+ }
}
func TestCodexShellAuthorizedCustomEnvNamesUsesDaemonBlocklist(t *testing.T) {
@@ -505,6 +511,50 @@ func TestTaskScopedAuthToken(t *testing.T) {
}
}
+func TestTaskMulticaEnvironmentIncludesPrivateConfigRoot(t *testing.T) {
+ t.Parallel()
+
+ const (
+ fakeToken = "mat_task_environment_sentinel"
+ taskRoot = "/task/private-multica-config"
+ )
+ task := Task{
+ ID: "task-test",
+ AgentID: "agent-test",
+ WorkspaceID: "workspace-test",
+ }
+ env := taskMulticaEnvironment(task, "agent-name", fakeToken, taskRoot, "https://task.example", 19514, 3, "/task/tmp")
+
+ want := map[string]string{
+ "MULTICA_TOKEN": fakeToken,
+ "MULTICA_TASK_CONFIG_ROOT": taskRoot,
+ "MULTICA_SERVER_URL": "https://task.example",
+ "MULTICA_DAEMON_PORT": "19514",
+ "MULTICA_WORKSPACE_ID": "workspace-test",
+ "MULTICA_AGENT_NAME": "agent-name",
+ "MULTICA_AGENT_ID": "agent-test",
+ "MULTICA_TASK_ID": "task-test",
+ "MULTICA_TASK_SLOT": "3",
+ "TMPDIR": "/task/tmp",
+ "TMP": "/task/tmp",
+ "TEMP": "/task/tmp",
+ }
+ if !maps.Equal(env, want) {
+ t.Fatalf("taskMulticaEnvironment() = %#v, want %#v", env, want)
+ }
+
+ layerCustomEnvAndHermesHome(env, map[string]string{
+ "MULTICA_TASK_CONFIG_ROOT": "/owner/config",
+ "MULTICA_TOKEN": "mul_owner_sentinel",
+ }, "", nil)
+ if env["MULTICA_TASK_CONFIG_ROOT"] != taskRoot {
+ t.Fatalf("custom env replaced task config root: %q", env["MULTICA_TASK_CONFIG_ROOT"])
+ }
+ if env["MULTICA_TOKEN"] != fakeToken {
+ t.Fatal("custom env replaced task-scoped token")
+ }
+}
+
// When `brew --prefix` is unavailable but the executable path is under a
// known Cellar root, triggerRestart must recover the prefix from the
// known-prefix list and target <prefix>/bin/multica.
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index e2f507cec0..8ebe7d67de 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -198,6 +198,10 @@ type Environment struct {
// on "may I remove WorkDir as scratch?" must check this — for example
// the GC loop never deletes the user's directory.
LocalDirectory bool
+ // MulticaConfigRoot is the private per-task config directory exported to
+ // child CLI invocations. It prevents implicit discovery of the daemon
+ // owner's ~/.multica profile without changing the provider-facing HOME.
+ MulticaConfigRoot string
// CodexHome is the path to the per-task CODEX_HOME directory (set only for codex provider).
CodexHome string
// ClaudeSettingsPath is a task-local --settings JSON file that applies
@@ -301,12 +305,20 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
return nil, fmt.Errorf("execenv: create directory %s: %w", dir, err)
}
}
+ multicaConfigRoot := filepath.Join(envRoot, "multica-config")
+ if err := os.MkdirAll(multicaConfigRoot, 0o700); err != nil {
+ return nil, fmt.Errorf("execenv: create task-local Multica config directory: %w", err)
+ }
+ if err := os.Chmod(multicaConfigRoot, 0o700); err != nil {
+ return nil, fmt.Errorf("execenv: restrict task-local Multica config directory: %w", err)
+ }
env := &Environment{
- RootDir: envRoot,
- WorkDir: workDir,
- LocalDirectory: params.LocalWorkDir != "",
- logger: logger,
+ RootDir: envRoot,
+ WorkDir: workDir,
+ LocalDirectory: params.LocalWorkDir != "",
+ MulticaConfigRoot: multicaConfigRoot,
+ logger: logger,
}
// Write context files into workdir (skills go to provider-native paths).
@@ -512,6 +524,17 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
LocalDirectory: params.LocalDirectory,
logger: logger,
}
+ if env.RootDir != "" {
+ env.MulticaConfigRoot = filepath.Join(env.RootDir, "multica-config")
+ if err := os.MkdirAll(env.MulticaConfigRoot, 0o700); err != nil {
+ logger.Warn("execenv: restore task-local Multica config directory failed; forcing fresh prepare", "error", err)
+ return nil
+ }
+ if err := os.Chmod(env.MulticaConfigRoot, 0o700); err != nil {
+ logger.Warn("execenv: restrict task-local Multica config directory failed; forcing fresh prepare", "error", err)
+ return nil
+ }
+ }
// Roll back the previous dispatch's sidecar writes before refreshing.
// On reuse the workdir still holds the prior run's issue_context.md and
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index bdf7940b25..f70b4a4dc6 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -118,12 +118,22 @@ func TestPrepareDirectoryMode(t *testing.T) {
defer env.Cleanup(true)
// Verify directory structure.
- for _, sub := range []string{"workdir", "output", "logs"} {
+ for _, sub := range []string{"workdir", "output", "logs", "multica-config"} {
path := filepath.Join(env.RootDir, sub)
if _, err := os.Stat(path); os.IsNotExist(err) {
t.Fatalf("expected %s to exist", path)
}
}
+ if env.MulticaConfigRoot != filepath.Join(env.RootDir, "multica-config") {
+ t.Fatalf("MulticaConfigRoot = %q, want task-local config directory", env.MulticaConfigRoot)
+ }
+ info, err := os.Stat(env.MulticaConfigRoot)
+ if err != nil {
+ t.Fatalf("stat MulticaConfigRoot: %v", err)
+ }
+ if got := info.Mode().Perm(); got != 0o700 {
+ t.Fatalf("MulticaConfigRoot mode = %o, want 700", got)
+ }
// Verify context file contains issue ID and CLI hints.
content, err := os.ReadFile(filepath.Join(env.WorkDir, ".agent_context", "issue_context.md"))
@@ -3963,6 +3973,14 @@ func TestReuseRestoresCodexHome(t *testing.T) {
if reused.CodexHome == "" {
t.Fatal("expected CodexHome to be restored after Reuse")
}
+ if reused.MulticaConfigRoot != filepath.Join(reused.RootDir, "multica-config") {
+ t.Fatalf("MulticaConfigRoot = %q, want restored task-local config directory", reused.MulticaConfigRoot)
+ }
+ if info, err := os.Stat(reused.MulticaConfigRoot); err != nil {
+ t.Fatalf("stat restored MulticaConfigRoot: %v", err)
+ } else if got := info.Mode().Perm(); got != 0o700 {
+ t.Fatalf("restored MulticaConfigRoot mode = %o, want 700", got)
+ }
// Verify config.toml has a managed block (exact mode depends on host
// platform; either workspace-write or danger-full-access is valid).
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
index 5b306e2a09..b0c6984f53 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
@@ -49,6 +49,17 @@ multica repo checkout <url> --ref <branch-or-sha>
`repo checkout` requires `MULTICA_DAEMON_PORT`; it is intended to run inside a daemon task. If absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.
+## Task CLI boundary
+
+The daemon injects a task-scoped `mat_` credential for Multica API commands and a private task-local Multica configuration root. Inside that managed task context:
+
+- API commands such as `issue list`, `issue get`, and `issue runs` use the injected task identity and never fall back to the daemon Owner's saved Multica profile.
+- `config show` and `config set` operate only on task-local Multica state. A missing task config root fails closed.
+- `auth status` may verify the task identity but omits all token material from its output.
+- Human/local profile and daemon commands — including `login`, `logout`, `setup`, `workspace switch`, local runtime profile path mutation, and daemon lifecycle/diagnostic commands — are unavailable.
+
+The daemon still preserves the real `HOME` and XDG variables for provider tools such as `gh`, `aws`, `kubectl`, and npm. This is CLI resolution hardening, not hard filesystem confidentiality: a process under the same OS user can still open an explicitly known Owner path. Dedicated Unix users, containers, VMs, or an equivalent OS boundary are required for that stronger isolation.
+
## Debugging an agent that did not run
Check in this order:
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
index ba3d408e7a..83518dee95 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
@@ -10,5 +10,8 @@
- `server/internal/daemon/daemon.go` injects `MULTICA_REPO_CHECKOUT_MODE=isolated` for Linux and Windows Codex tasks. Linux keeps the isolated checkout it already had; Windows Codex now uses the same layout to cover its native sandbox, where a linked worktree's external gitdir stays read-only and `git add` / `git commit` fail from inside the checkout (multica-ai/multica#6449). That failure only bites a Windows user who opted into `windows.sandbox` — `server/internal/daemon/execenv/codex_sandbox.go` defaults both Linux and Windows Codex to `danger-full-access` — but the checkout layout is chosen per platform, not per sandbox policy, so it does not depend on a task's resolved policy. `server/internal/daemon/repocache/cache.go` implements the mode as a local clone with task-local Git metadata and the real repository as `origin`; on Windows it clones with `--no-hardlinks` so the checkout's objects are private copies rather than NTFS links that share one file and security descriptor with the cache. Other runtimes keep the linked-worktree path.
- When the bare cache is a partial clone, that isolated checkout must have `remote.origin.promisor` / `partialclonefilter` restored before its first `checkout`: `git clone --local` neither inherits them nor errors on the missing objects it leaves behind, so the checkout would otherwise succeed with an empty working tree. The linked-worktree path shares the cache's own config and needs no such repair.
- `server/cmd/server/router.go` registers daemon APIs under `/api/daemon`, including workspace repos and task claim.
-- `server/internal/daemon/daemon.go` claims tasks, prepares workdirs, launches provider CLIs, and reports completion.
+- `server/internal/daemon/daemon.go` claims tasks, prepares workdirs, launches provider CLIs, and reports completion. It validates the task-scoped `mat_` credential, exports `MULTICA_TASK_CONFIG_ROOT`, and keeps that daemon-owned variable ahead of custom environment assembly so agents cannot override it.
+- `server/internal/daemon/execenv/execenv.go` creates and restores the private per-task `multica-config` directory with mode `0700`; it does not copy the daemon Owner's Multica profile into the directory.
+- `server/internal/cli/config.go` resolves Multica CLI profiles below `MULTICA_TASK_CONFIG_ROOT` when present while leaving ordinary `HOME`-based resolution unchanged outside tasks.
+- `server/cmd/multica/cmd_agent.go`, `cmd_config.go`, `cmd_auth.go`, `cmd_login.go`, `cmd_setup.go`, `cmd_workspace.go`, `cmd_runtime_profile.go`, and `cmd_daemon.go` enforce the task boundary: API calls require task authentication, task-local config commands fail closed without their root, auth status hides credential material, and human/local profile or daemon commands reject managed task context.
- `server/internal/daemon/execenv/runtime_config.go` injects task/project/repo context into agent workdirs.