Skip to content

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

Go

fix(daemon): writable per-task HOME for Linux Codex sandbox (MUL-4856) (#5508)

Bohan Jiangb13b6d06bc0e
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 3a7803b09c..842021a1c0 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4128,6 +4128,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if env.CodexHome != "" {
agentEnv["CODEX_HOME"] = env.CodexHome
}
+ // Redirect HOME/XDG/npm_config_cache to the per-task writable home under the
+ // Linux codex workspace-write sandbox, where the real home is read-only. This
+ // lets tools that write to `~` (npm, Prisma, …) succeed without per-tool env
+ // tweaks. Set before custom_env below so a user override still wins for the
+ // non-blocklisted XDG keys; HOME itself stays blocklisted. Empty TaskHome
+ // (macOS/Windows, non-sandboxed providers) leaves the real HOME untouched
+ // (MUL-4856).
+ if env.TaskHome != "" {
+ for k, v := range execenv.TaskHomeEnv(env.TaskHome) {
+ agentEnv[k] = v
+ }
+ }
// (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/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.go
index a2867fb8c6..6879fd0eab 100644
--- a/server/internal/daemon/execenv/codex_home.go
+++ b/server/internal/daemon/execenv/codex_home.go
@@ -62,6 +62,12 @@ type CodexHomeOptions struct {
// task with no issue), in which case sessions/ stays task-local. See
// codexSessionStoreDir and prepareCodexSessionsDir (MUL-4424).
SessionStoreKey string
+ // WritableRoots are extra absolute paths written into the config.toml
+ // `[sandbox_workspace_write] writable_roots` so the workspace-write sandbox
+ // (Linux) can write outside the task workdir — the per-task writable HOME.
+ // Only meaningful when the policy resolves to workspace-write; ignored on
+ // darwin danger-full-access. See task_home.go and MUL-4856.
+ WritableRoots []string
}
// prepareCodexHome is a thin wrapper around prepareCodexHomeWithOpts kept for
@@ -136,6 +142,7 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *s
// need to fall back to danger-full-access because of openai/codex#10390;
// see codex_sandbox.go for the full rationale.
policy := codexSandboxPolicyFor(opts.GOOS, opts.CodexVersion)
+ policy.WritableRoots = opts.WritableRoots
if err := ensureCodexSandboxConfig(filepath.Join(codexHome, "config.toml"), policy, opts.CodexVersion, logger); err != nil {
logger.Warn("execenv: codex-home ensure sandbox config failed", "error", err)
}
diff --git a/server/internal/daemon/execenv/codex_sandbox.go b/server/internal/daemon/execenv/codex_sandbox.go
index bfea36f825..4f08be61ca 100644
--- a/server/internal/daemon/execenv/codex_sandbox.go
+++ b/server/internal/daemon/execenv/codex_sandbox.go
@@ -38,6 +38,15 @@ type codexSandboxPolicy struct {
// NetworkAccess controls `[sandbox_workspace_write] network_access`.
// Only meaningful when Mode is "workspace-write".
NetworkAccess bool
+ // WritableRoots are extra absolute paths added to
+ // `[sandbox_workspace_write] writable_roots`, granting write access outside
+ // the sandbox cwd (the task workdir). Under workspace-write (Linux Landlock)
+ // everything outside the cwd is read-only, which breaks tools that write to
+ // $HOME (npm, Prisma). The daemon points this at the per-task writable HOME.
+ // Only emitted when Mode is "workspace-write"; empty on darwin
+ // danger-full-access, where the filesystem is not sandboxed at all. See
+ // task_home.go.
+ WritableRoots []string
// Reason is a short human-readable label used in warn-level logs.
Reason string
}
@@ -45,12 +54,12 @@ type codexSandboxPolicy struct {
// codexSandboxPolicyFor picks the right policy for the given platform and
// detected Codex CLI version.
//
-// - Non-darwin: always workspace-write with network access (Landlock is not
-// affected by the macOS Seatbelt bug).
-// - darwin with a version at or above CodexDarwinNetworkAccessFixedVersion:
-// workspace-write with network access (upstream bug fixed).
-// - darwin otherwise (including when the version is unknown): fall back to
-// danger-full-access so the Multica CLI can reach the API.
+// - Non-darwin: always workspace-write with network access (Landlock is not
+// affected by the macOS Seatbelt bug).
+// - darwin with a version at or above CodexDarwinNetworkAccessFixedVersion:
+// workspace-write with network access (upstream bug fixed).
+// - darwin otherwise (including when the version is unknown): fall back to
+// danger-full-access so the Multica CLI can reach the API.
func codexSandboxPolicyFor(goos, detectedVersion string) codexSandboxPolicy {
if goos == "" {
goos = runtime.GOOS
@@ -134,12 +143,29 @@ func renderMulticaManagedBlock(policy codexSandboxPolicy) string {
b.WriteString(fmt.Sprintf("sandbox_mode = %q\n", policy.Mode))
if policy.Mode == "workspace-write" {
b.WriteString(fmt.Sprintf("sandbox_workspace_write.network_access = %t\n", policy.NetworkAccess))
+ if len(policy.WritableRoots) > 0 {
+ b.WriteString("sandbox_workspace_write.writable_roots = ")
+ b.WriteString(renderTomlStringArray(policy.WritableRoots))
+ b.WriteString("\n")
+ }
}
b.WriteString(multicaManagedEndMarker)
b.WriteString("\n")
return b.String()
}
+// renderTomlStringArray renders a TOML inline array of basic strings, e.g.
+// ["/a/b", "/c d"]. Each element is quoted with Go's %q, whose escaping (\\,
+// \", \n, …) is a subset of TOML basic-string escaping, so ordinary
+// filesystem paths — including ones with spaces — round-trip safely.
+func renderTomlStringArray(vals []string) string {
+ parts := make([]string, len(vals))
+ for i, v := range vals {
+ parts[i] = fmt.Sprintf("%q", v)
+ }
+ return "[" + strings.Join(parts, ", ") + "]"
+}
+
// managedBlockRe captures the daemon-owned block (including the surrounding
// markers and any trailing blank lines) so it can be replaced idempotently.
// `\n*` rather than `\n?` so reruns don't accumulate blank lines when the
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 14805edbc4..6f1b3f6666 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -186,6 +186,14 @@ type Environment struct {
LocalDirectory bool
// CodexHome is the path to the per-task CODEX_HOME directory (set only for codex provider).
CodexHome string
+ // TaskHome is the per-task writable HOME directory (set only for the codex
+ // provider on Linux, where the workspace-write Landlock sandbox makes the
+ // real HOME read-only). When non-empty the daemon redirects
+ // HOME/XDG/npm_config_cache here so tools that write to `~` (npm, Prisma, …)
+ // land in a sandbox-writable location. Empty on macOS/Windows and for
+ // non-sandboxed providers, where the real HOME stays in place. See
+ // task_home.go and MUL-4856.
+ TaskHome string
// OpenclawConfigPath is the path to the per-task synthesized OpenClaw
// config (set only for openclaw provider). The daemon exports this as
// OPENCLAW_CONFIG_PATH on the openclaw subprocess so its native skill
@@ -300,7 +308,15 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// For Codex, set up a per-task CODEX_HOME seeded from ~/.codex/ with skills.
if params.Provider == "codex" {
codexHome := filepath.Join(envRoot, "codex-home")
- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "", SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID)}, logger); err != nil {
+ // Under the Linux workspace-write sandbox the real HOME is read-only;
+ // give the task a writable HOME and grant write access to it in the
+ // Codex config so npm/Prisma can write their caches (MUL-4856).
+ taskHome, writableRoots, err := prepareCodexSandboxHome(envRoot, "", params.CodexVersion, logger)
+ if err != nil {
+ return nil, fmt.Errorf("execenv: prepare task home: %w", err)
+ }
+ env.TaskHome = taskHome
+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "", SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID), WritableRoots: writableRoots}, logger); err != nil {
return nil, fmt.Errorf("execenv: prepare codex-home: %w", err)
}
if err := hydrateCodexSkills(codexHome, params.Task.AgentSkills, logger); err != nil {
@@ -504,7 +520,15 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
// config (especially sandbox/network access) is up to date.
if params.Provider == "codex" {
codexHome := filepath.Join(env.RootDir, "codex-home")
- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, ResumeSessionID: params.ResumeSessionID, IsLocalDirectory: params.LocalDirectory, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID)}, logger); err != nil {
+ // Refresh the per-task writable HOME (re-seed credential symlinks in
+ // case the user's real home changed) and recompute the sandbox
+ // writable_roots on reuse, mirroring the fresh Prepare path (MUL-4856).
+ taskHome, writableRoots, err := prepareCodexSandboxHome(env.RootDir, "", params.CodexVersion, logger)
+ if err != nil {
+ logger.Warn("execenv: refresh task home failed", "error", err)
+ }
+ env.TaskHome = taskHome
+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, ResumeSessionID: params.ResumeSessionID, IsLocalDirectory: params.LocalDirectory, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID), WritableRoots: writableRoots}, logger); err != nil {
logger.Warn("execenv: refresh codex-home failed", "error", err)
} else {
env.CodexHome = codexHome
diff --git a/server/internal/daemon/execenv/task_home.go b/server/internal/daemon/execenv/task_home.go
new file mode 100644
index 0000000000..89145deee1
--- /dev/null
+++ b/server/internal/daemon/execenv/task_home.go
@@ -0,0 +1,169 @@
+package execenv
+
+import (
+ "fmt"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+// Background (MUL-4856)
+//
+// On Linux the Codex sandbox runs in `workspace-write` mode (Landlock): every
+// path outside the task workdir (the sandbox cwd) is read-only. The agent's
+// real $HOME is therefore read-only, which breaks the standard tools that write
+// under `~` by default:
+//
+// - npm writes `~/.npm/_cacache` → EROFS on `npm install`.
+// - Prisma hardcodes `os.homedir()/.cache/prisma` (it ignores XDG) → EROFS on
+// `prisma generate`. Only redirecting HOME can fix Prisma.
+//
+// Reads are unrestricted under workspace-write — only writes are sandboxed — so
+// the fix is to (1) give each task a writable HOME under its env root, (2) point
+// HOME/XDG/npm_config_cache at it, and (3) add that home to the Codex
+// `writable_roots` (it lives outside the cwd, so it needs an explicit grant).
+// Because the redirected HOME is otherwise empty, we seed it with symlinks to
+// the user's real credential/identity files so private-registry `npm install`
+// (and git/gh reads, when git is usable) keep working — reads through the
+// symlink resolve the real file, which stays read-only, and those flows only
+// read them. This mirrors the existing per-task CODEX_HOME seeding precedent.
+//
+// Scope: Linux codex only. macOS Codex uses danger-full-access (no filesystem
+// sandbox), and Windows has no Landlock sandbox (and unreliable symlink
+// permissions), so neither needs — nor should get — a redirected HOME. Other
+// providers are not sandboxed either.
+//
+// NOT covered here: `git commit` inside a checked-out worktree. Codex's
+// workspace-write reads the worktree's `.git` pointer file, resolves the real
+// gitdir, and keeps that gitdir read-only even when it sits inside a
+// writable_root (see codex-rs default_read_only_subpaths_for_writable_root), so
+// `writable_roots` cannot unblock it. That needs a Codex metadata-write
+// permission path and is tracked separately (GitHub multica-ai/multica#2925).
+
+// taskHomeSeedEntries are top-level entries symlinked from the user's real home
+// into the per-task HOME so credential/identity reads keep resolving after HOME
+// is redirected. Best-effort: missing sources are skipped. Writable cache dirs
+// (.npm, .cache, .local) are intentionally NOT seeded — tools create them fresh
+// inside the writable task home.
+var taskHomeSeedEntries = []string{
+ ".gitconfig", // git identity, aliases, credential.helper, url rewrites
+ ".npmrc", // npm registry + auth token
+ ".netrc", // https credentials for git/curl
+ ".git-credentials", // git credential store helper
+ ".ssh", // ssh keys/config for git over ssh (directory)
+}
+
+// taskHomeConfigSeedEntries are `~/.config/<name>` subdirectories symlinked into
+// the per-task `.config` (XDG_CONFIG_HOME) so config-in-XDG tools keep their
+// auth after XDG_CONFIG_HOME is redirected. Best-effort: missing sources are
+// skipped.
+var taskHomeConfigSeedEntries = []string{
+ "gh", // GitHub CLI auth (hosts.yml) used as a git credential helper
+ "git", // XDG git config location
+}
+
+// prepareTaskHome creates a writable per-task HOME directory and seeds it with
+// symlinks to the user's real credential/identity files so tools that write to
+// `~` land in a sandbox-writable location while still reading the user's real
+// git/npm/ssh credentials. Best-effort: seeding failures are logged, not fatal —
+// the writable home still resolves the EROFS problem for cache writes even if a
+// particular credential source is absent.
+func prepareTaskHome(taskHome string, logger *slog.Logger) error {
+ if err := os.MkdirAll(taskHome, 0o700); err != nil {
+ return fmt.Errorf("create task home: %w", err)
+ }
+
+ sharedHome, err := os.UserHomeDir()
+ if err != nil || sharedHome == "" {
+ // No real home to seed from — the writable home still fixes cache
+ // writes; git identity / credentials simply aren't seeded.
+ if logger != nil {
+ logger.Warn("execenv: task home: no user home to seed credentials from", "error", err)
+ }
+ return nil
+ }
+
+ for _, name := range taskHomeSeedEntries {
+ src := filepath.Join(sharedHome, name)
+ if _, err := os.Lstat(src); err != nil {
+ continue // best-effort: skip missing sources
+ }
+ if err := ensureSymlink(src, filepath.Join(taskHome, name)); err != nil && logger != nil {
+ logger.Warn("execenv: task home: seed symlink failed", "entry", name, "error", err)
+ }
+ }
+
+ // Seed read-shared XDG config subdirs (gh auth, git config) under a real,
+ // writable .config so other tools can still create new config there while
+ // gh/git resolve the user's existing auth through the symlinks.
+ configDir := filepath.Join(taskHome, ".config")
+ if err := os.MkdirAll(configDir, 0o700); err != nil {
+ if logger != nil {
+ logger.Warn("execenv: task home: create .config failed", "error", err)
+ }
+ return nil
+ }
+ sharedConfig := filepath.Join(sharedHome, ".config")
+ for _, name := range taskHomeConfigSeedEntries {
+ src := filepath.Join(sharedConfig, name)
+ if _, err := os.Lstat(src); err != nil {
+ continue // best-effort: skip missing sources
+ }
+ if err := ensureSymlink(src, filepath.Join(configDir, name)); err != nil && logger != nil {
+ logger.Warn("execenv: task home: seed .config symlink failed", "entry", name, "error", err)
+ }
+ }
+
+ return nil
+}
+
+// TaskHomeEnv returns the environment overrides that redirect a task's HOME and
+// XDG base dirs into the per-task writable home. The daemon layers these onto
+// the agent's environment so npm, Prisma, and other tools that default to `~`
+// write into the sandbox-writable home instead of the read-only real one.
+//
+// XDG_* are set explicitly (not left to derive from HOME) so an inherited
+// XDG_CACHE_HOME/etc. pointing at the read-only real home cannot win. Likewise
+// npm_config_cache is set explicitly to override any inherited value.
+func TaskHomeEnv(taskHome string) map[string]string {
+ return map[string]string{
+ "HOME": taskHome,
+ "XDG_CACHE_HOME": filepath.Join(taskHome, ".cache"),
+ "XDG_CONFIG_HOME": filepath.Join(taskHome, ".config"),
+ "XDG_DATA_HOME": filepath.Join(taskHome, ".local", "share"),
+ "XDG_STATE_HOME": filepath.Join(taskHome, ".local", "state"),
+ "npm_config_cache": filepath.Join(taskHome, ".npm"),
+ }
+}
+
+// prepareCodexSandboxHome sets up the per-task writable HOME and computes the
+// Codex `writable_roots`, but only for Linux codex under the workspace-write
+// sandbox. On macOS (danger-full-access) and Windows (no Landlock sandbox) it
+// returns an empty home and nil roots, and the caller leaves the real HOME in
+// place. goos defaults to runtime.GOOS; it is a parameter so tests can exercise
+// each platform deterministically.
+//
+// It returns the task home path (empty when no redirect is needed) and the
+// writable roots to add to the config.toml — just the task home, which lives
+// outside the sandbox cwd and is not a git metadata dir, so Codex does not
+// re-protect it.
+func prepareCodexSandboxHome(envRoot, goos, codexVersion string, logger *slog.Logger) (taskHome string, writableRoots []string, err error) {
+ if envRoot == "" {
+ // No task env root to anchor the home under (legacy local_directory
+ // reuse fallback). Leave the real HOME in place.
+ return "", nil, nil
+ }
+ if goos == "" {
+ goos = runtime.GOOS
+ }
+ if goos != "linux" || codexSandboxPolicyFor(goos, codexVersion).Mode != "workspace-write" {
+ return "", nil, nil
+ }
+
+ taskHome = filepath.Join(envRoot, "home")
+ if err := prepareTaskHome(taskHome, logger); err != nil {
+ return "", nil, err
+ }
+ return taskHome, []string{taskHome}, nil
+}
diff --git a/server/internal/daemon/execenv/task_home_test.go b/server/internal/daemon/execenv/task_home_test.go
new file mode 100644
index 0000000000..ff8fe58224
--- /dev/null
+++ b/server/internal/daemon/execenv/task_home_test.go
@@ -0,0 +1,253 @@
+package execenv
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pelletier/go-toml/v2"
+)
+
+// TestRenderManagedBlockWritableRoots verifies the workspace-write managed block
+// emits writable_roots as a top-level dotted key (never a table header) and that
+// the result — including the network_access dotted key sharing the same implicit
+// table — is valid TOML.
+func TestRenderManagedBlockWritableRoots(t *testing.T) {
+ t.Parallel()
+ policy := codexSandboxPolicyFor("linux", "0.121.0")
+ policy.WritableRoots = []string{"/home/u/multica_workspaces/ws/abc/home", "/home/u/multica_workspaces/.repos/ws"}
+
+ block := renderMulticaManagedBlock(policy)
+
+ if !strings.Contains(block, `sandbox_workspace_write.writable_roots = ["/home/u/multica_workspaces/ws/abc/home", "/home/u/multica_workspaces/.repos/ws"]`) {
+ t.Errorf("missing dotted-key writable_roots array, got:\n%s", block)
+ }
+ if strings.Contains(block, "[sandbox_workspace_write]") {
+ t.Errorf("must not open a [sandbox_workspace_write] table header, got:\n%s", block)
+ }
+
+ // Both network_access and writable_roots build the same implicit table via
+ // dotted keys — assert the parser accepts it.
+ var parsed map[string]any
+ if err := toml.Unmarshal([]byte(block[strings.Index(block, "sandbox_mode"):]), &parsed); err != nil {
+ t.Fatalf("generated block is invalid TOML: %v\nblock:\n%s", err, block)
+ }
+ sww, ok := parsed["sandbox_workspace_write"].(map[string]any)
+ if !ok {
+ t.Fatalf("sandbox_workspace_write not parsed as a table: %#v", parsed["sandbox_workspace_write"])
+ }
+ roots, ok := sww["writable_roots"].([]any)
+ if !ok || len(roots) != 2 {
+ t.Fatalf("writable_roots did not round-trip as a 2-element array: %#v", sww["writable_roots"])
+ }
+}
+
+// TestRenderManagedBlockNoWritableRoots verifies that with no writable roots (or
+// under danger-full-access), the writable_roots key is omitted entirely.
+func TestRenderManagedBlockNoWritableRoots(t *testing.T) {
+ t.Parallel()
+
+ linux := renderMulticaManagedBlock(codexSandboxPolicyFor("linux", "0.121.0"))
+ if strings.Contains(linux, "writable_roots") {
+ t.Errorf("workspace-write with no roots must omit writable_roots, got:\n%s", linux)
+ }
+
+ // danger-full-access must never emit workspace-write keys even if roots set.
+ darwin := codexSandboxPolicyFor("darwin", "0.121.0")
+ darwin.WritableRoots = []string{"/should/not/appear"}
+ block := renderMulticaManagedBlock(darwin)
+ if strings.Contains(block, "writable_roots") || strings.Contains(block, "sandbox_workspace_write") {
+ t.Errorf("danger-full-access must omit all workspace-write keys, got:\n%s", block)
+ }
+}
+
+// TestEnsureCodexSandboxConfigWritableRoots verifies the writable_roots flow all
+// the way through ensureCodexSandboxConfig into the on-disk config.toml.
+func TestEnsureCodexSandboxConfigWritableRoots(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ configPath := filepath.Join(dir, "config.toml")
+
+ policy := codexSandboxPolicyFor("linux", "0.121.0")
+ policy.WritableRoots = []string{filepath.Join(dir, "home"), filepath.Join(dir, "repos")}
+ if err := ensureCodexSandboxConfig(configPath, policy, "0.121.0", testLogger()); err != nil {
+ t.Fatalf("ensureCodexSandboxConfig failed: %v", err)
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config.toml: %v", err)
+ }
+ if !strings.Contains(string(data), "sandbox_workspace_write.writable_roots = [") {
+ t.Errorf("config.toml missing writable_roots, got:\n%s", data)
+ }
+ // Whole file must be valid TOML (the managed block coexists with any user
+ // content — here there is none, so parsing the file directly is enough).
+ var parsed map[string]any
+ if err := toml.Unmarshal(data, &parsed); err != nil {
+ t.Fatalf("on-disk config.toml is invalid TOML: %v", err)
+ }
+}
+
+// TestPrepareCodexSandboxHomeLinux verifies the Linux path creates a writable
+// home and returns exactly that home as the only writable root (no repo cache —
+// Codex re-protects resolved gitdirs, so writable_roots can't unblock git; see
+// task_home.go / #2925).
+func TestPrepareCodexSandboxHomeLinux(t *testing.T) {
+ // Not parallel: mutates HOME via os.UserHomeDir seeding in prepareTaskHome.
+ fakeHome := t.TempDir()
+ t.Setenv("HOME", fakeHome)
+
+ envRoot := t.TempDir()
+ home, roots, err := prepareCodexSandboxHome(envRoot, "linux", "", testLogger())
+ if err != nil {
+ t.Fatalf("prepareCodexSandboxHome: %v", err)
+ }
+
+ wantHome := filepath.Join(envRoot, "home")
+ if home != wantHome {
+ t.Errorf("home = %q, want %q", home, wantHome)
+ }
+ if fi, err := os.Stat(home); err != nil || !fi.IsDir() {
+ t.Errorf("task home dir not created: err=%v", err)
+ }
+ if len(roots) != 1 || roots[0] != wantHome {
+ t.Errorf("writable roots = %v, want [%q]", roots, wantHome)
+ }
+}
+
+// TestPrepareCodexSandboxHomeNonLinux verifies macOS and Windows skip the
+// redirect entirely (real HOME stays writable / no Landlock sandbox), and that
+// no home directory is created.
+func TestPrepareCodexSandboxHomeNonLinux(t *testing.T) {
+ for _, goos := range []string{"darwin", "windows"} {
+ t.Run(goos, func(t *testing.T) {
+ envRoot := t.TempDir()
+ home, roots, err := prepareCodexSandboxHome(envRoot, goos, "", testLogger())
+ if err != nil {
+ t.Fatalf("prepareCodexSandboxHome(%s): %v", goos, err)
+ }
+ if home != "" || roots != nil {
+ t.Fatalf("%s should skip the writable home, got home=%q roots=%v", goos, home, roots)
+ }
+ if _, err := os.Stat(filepath.Join(envRoot, "home")); !os.IsNotExist(err) {
+ t.Errorf("%s must not create a task home dir, stat err=%v", goos, err)
+ }
+ })
+ }
+}
+
+// TestPrepareTaskHomeSeedsCredentials verifies the per-task home is created
+// writable and seeded with symlinks to the user's real credential/config files,
+// skipping missing sources.
+func TestPrepareTaskHomeSeedsCredentials(t *testing.T) {
+ fakeHome := t.TempDir()
+ // Present sources (writeFile creates parent dirs, so .ssh and .config/gh
+ // become directories).
+ writeFile(t, filepath.Join(fakeHome, ".gitconfig"), "[user]\n\tname = X\n")
+ writeFile(t, filepath.Join(fakeHome, ".npmrc"), "//registry/:_authToken=abc\n")
+ writeFile(t, filepath.Join(fakeHome, ".ssh", "id_ed25519"), "KEY\n")
+ writeFile(t, filepath.Join(fakeHome, ".config", "gh", "hosts.yml"), "github.com: {}\n")
+ // .netrc and .config/git deliberately absent — must be skipped.
+
+ t.Setenv("HOME", fakeHome)
+
+ taskHome := filepath.Join(t.TempDir(), "home")
+ if err := prepareTaskHome(taskHome, testLogger()); err != nil {
+ t.Fatalf("prepareTaskHome: %v", err)
+ }
+
+ assertSymlinkTo(t, filepath.Join(taskHome, ".gitconfig"), filepath.Join(fakeHome, ".gitconfig"))
+ assertSymlinkTo(t, filepath.Join(taskHome, ".npmrc"), filepath.Join(fakeHome, ".npmrc"))
+ assertSymlinkTo(t, filepath.Join(taskHome, ".ssh"), filepath.Join(fakeHome, ".ssh"))
+ assertSymlinkTo(t, filepath.Join(taskHome, ".config", "gh"), filepath.Join(fakeHome, ".config", "gh"))
+
+ // A read through the .gitconfig symlink resolves the real content.
+ if b, err := os.ReadFile(filepath.Join(taskHome, ".gitconfig")); err != nil || !strings.Contains(string(b), "name = X") {
+ t.Errorf("gitconfig not readable through symlink: %q err=%v", b, err)
+ }
+
+ // Missing sources are skipped, not linked as broken symlinks.
+ if _, err := os.Lstat(filepath.Join(taskHome, ".netrc")); !os.IsNotExist(err) {
+ t.Errorf(".netrc should be skipped (missing source), lstat err=%v", err)
+ }
+ if _, err := os.Lstat(filepath.Join(taskHome, ".config", "git")); !os.IsNotExist(err) {
+ t.Errorf(".config/git should be skipped (missing source), lstat err=%v", err)
+ }
+
+ // .config must be a real, writable directory (not a symlink) so other tools
+ // can write new config there.
+ fi, err := os.Lstat(filepath.Join(taskHome, ".config"))
+ if err != nil {
+ t.Fatalf(".config not created: %v", err)
+ }
+ if fi.Mode()&os.ModeSymlink != 0 {
+ t.Error(".config must be a real directory, not a symlink")
+ }
+ // The task home is writable: creating a cache file under it succeeds.
+ if err := os.MkdirAll(filepath.Join(taskHome, ".cache", "prisma"), 0o755); err != nil {
+ t.Errorf("task home not writable: %v", err)
+ }
+}
+
+// TestPrepareTaskHomeNoRealHome verifies prepareTaskHome degrades gracefully when
+// there is no user home to seed from — the writable home is still created.
+func TestPrepareTaskHomeNoRealHome(t *testing.T) {
+ // An empty HOME makes os.UserHomeDir fail on unix.
+ t.Setenv("HOME", "")
+
+ taskHome := filepath.Join(t.TempDir(), "home")
+ if err := prepareTaskHome(taskHome, testLogger()); err != nil {
+ t.Fatalf("prepareTaskHome should not fail without a real home: %v", err)
+ }
+ if fi, err := os.Stat(taskHome); err != nil || !fi.IsDir() {
+ t.Errorf("task home not created without a real home: err=%v", err)
+ }
+}
+
+func TestTaskHomeEnv(t *testing.T) {
+ t.Parallel()
+ home := filepath.FromSlash("/tmp/task/home")
+ env := TaskHomeEnv(home)
+
+ want := map[string]string{
+ "HOME": home,
+ "XDG_CACHE_HOME": filepath.Join(home, ".cache"),
+ "XDG_CONFIG_HOME": filepath.Join(home, ".config"),
+ "XDG_DATA_HOME": filepath.Join(home, ".local", "share"),
+ "XDG_STATE_HOME": filepath.Join(home, ".local", "state"),
+ "npm_config_cache": filepath.Join(home, ".npm"),
+ }
+ for k, v := range want {
+ if env[k] != v {
+ t.Errorf("TaskHomeEnv[%q] = %q, want %q", k, env[k], v)
+ }
+ }
+ if len(env) != len(want) {
+ t.Errorf("TaskHomeEnv returned %d keys, want %d: %v", len(env), len(want), env)
+ }
+}
+
+// --- helpers ---
+
+func assertSymlinkTo(t *testing.T, link, wantTarget string) {
+ t.Helper()
+ fi, err := os.Lstat(link)
+ if err != nil {
+ t.Errorf("expected symlink %s: %v", link, err)
+ return
+ }
+ if fi.Mode()&os.ModeSymlink == 0 {
+ t.Errorf("%s is not a symlink", link)
+ return
+ }
+ target, err := os.Readlink(link)
+ if err != nil {
+ t.Errorf("readlink %s: %v", link, err)
+ return
+ }
+ if target != wantTarget {
+ t.Errorf("symlink %s -> %s, want %s", link, target, wantTarget)
+ }
+}