Skip to content

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

Go

fix(daemon): resume Claude sessions across continued local worktrees (MUL-8413) (#9734)

小七f75db6ad55fb
diff --git a/server/internal/daemon/claude_worktree_resume_test.go b/server/internal/daemon/claude_worktree_resume_test.go
new file mode 100644
index 0000000000..75766d45f2
--- /dev/null
+++ b/server/internal/daemon/claude_worktree_resume_test.go
@@ -0,0 +1,209 @@
+package daemon
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+func TestMigrateClaudeWorktreeTranscriptConfiguredDir(t *testing.T) {
+ home, configDir := t.TempDir(), t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("CLAUDE_CONFIG_DIR", configDir)
+ priorDir, workDir := t.TempDir(), t.TempDir()
+ const sessionID = "session-configured-dir"
+ src := filepath.Join(configDir, "projects", encodeClaudeCwd(priorDir), sessionID+".jsonl")
+ if err := os.MkdirAll(filepath.Dir(src), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ const transcript = "{\"type\":\"user\",\"message\":{\"content\":\"prior discussion\"}}\n"
+ if err := os.WriteFile(src, []byte(transcript), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ env := &execenv.Environment{WorkDir: workDir, LocalWorktree: &execenv.LocalWorktree{Continued: true}}
+ if !migrateClaudeWorktreeTranscript(env, sessionID, workDir, priorDir, nil, slog.Default()) {
+ t.Fatal("continued worktree did not migrate the transcript from CLAUDE_CONFIG_DIR")
+ }
+ dst := filepath.Join(configDir, "projects", encodeClaudeCwd(workDir), sessionID+".jsonl")
+ data, err := os.ReadFile(dst)
+ if err != nil || string(data) != transcript {
+ t.Fatalf("migrated transcript = %q, %v; want %q", data, err, transcript)
+ }
+}
+
+func TestMigrateClaudeWorktreeTranscriptRelativeConfigDir(t *testing.T) {
+ t.Parallel()
+ root := t.TempDir()
+ priorDir, workDir := filepath.Join(root, "prior", "worktree"), filepath.Join(root, "next", "worktree")
+ priorConfig, configDir := filepath.Join(root, "prior", "config"), filepath.Join(root, "next", "config")
+ const sessionID = "session-relative-config"
+ src := filepath.Join(priorConfig, "projects", encodeClaudeCwd(priorDir), sessionID+".jsonl")
+ if err := os.MkdirAll(filepath.Dir(src), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(src, []byte("prior history"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ env := &execenv.Environment{WorkDir: workDir, LocalWorktree: &execenv.LocalWorktree{Continued: true}}
+ if !migrateClaudeWorktreeTranscript(env, sessionID, workDir, priorDir, map[string]string{"CLAUDE_CONFIG_DIR": "../config"}, slog.Default()) {
+ t.Fatal("relative config directory was not resolved separately for each worktree")
+ }
+ dst := filepath.Join(configDir, "projects", encodeClaudeCwd(workDir), sessionID+".jsonl")
+ if data, err := os.ReadFile(dst); err != nil || string(data) != "prior history" {
+ t.Fatalf("migrated transcript = %q, %v", data, err)
+ }
+}
+
+func TestMigrateClaudeWorktreeTranscriptFailureLogs(t *testing.T) {
+ t.Parallel()
+ for _, blockedDestination := range []bool{false, true} {
+ t.Run(map[bool]string{false: "missing source", true: "unwritable destination"}[blockedDestination], func(t *testing.T) {
+ t.Parallel()
+ configDir, priorDir, workDir := t.TempDir(), t.TempDir(), t.TempDir()
+ src := filepath.Join(configDir, "projects", encodeClaudeCwd(priorDir), "session-1.jsonl")
+ wantMessage, wantPath := "claude: cannot read prior session transcript", src
+ if blockedDestination {
+ if err := os.MkdirAll(filepath.Dir(src), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(src, []byte("history"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ wantPath = filepath.Join(configDir, "projects", encodeClaudeCwd(workDir))
+ if err := os.WriteFile(wantPath, []byte("blocking file"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ wantMessage = "claude: cannot create transcript directory"
+ }
+ var logs bytes.Buffer
+ logger := slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ env := &execenv.Environment{WorkDir: workDir, LocalWorktree: &execenv.LocalWorktree{Continued: true}}
+ if migrateClaudeWorktreeTranscript(env, "session-1", workDir, priorDir, map[string]string{"CLAUDE_CONFIG_DIR": configDir}, logger) {
+ t.Fatal("migration failure was treated as resumable")
+ }
+ var entry map[string]any
+ if err := json.Unmarshal(logs.Bytes(), &entry); err != nil {
+ t.Fatalf("decode migration log: %v (%s)", err, &logs)
+ }
+ if entry["msg"] != wantMessage || entry["path"] != wantPath || entry["error"] == nil || entry["error"] == "" {
+ t.Fatalf("migration diagnostic = %v", entry)
+ }
+ })
+ }
+}
+
+func TestMigrateClaudeWorktreeTranscriptRejectsUnsafeSessionID(t *testing.T) {
+ t.Parallel()
+ configDir, priorDir, workDir := t.TempDir(), t.TempDir(), t.TempDir()
+ projectsDir := filepath.Join(configDir, "projects")
+ if err := os.MkdirAll(projectsDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ // Without validation, ../victim resolves to this unrelated existing file
+ // from both the source and destination project directories.
+ victim := filepath.Join(projectsDir, "victim.jsonl")
+ if err := os.WriteFile(victim, []byte("unrelated history"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ env := &execenv.Environment{WorkDir: workDir, LocalWorktree: &execenv.LocalWorktree{Continued: true}}
+ for _, sessionID := range []string{".", "..", "../victim", `..\victim`, "C:session", "session\x00"} {
+ if migrateClaudeWorktreeTranscript(env, sessionID, workDir, priorDir, map[string]string{"CLAUDE_CONFIG_DIR": configDir}, slog.Default()) {
+ t.Fatalf("unsafe session id %q was accepted", sessionID)
+ }
+ }
+ if entries, err := os.ReadDir(projectsDir); err != nil || len(entries) != 1 || entries[0].Name() != "victim.jsonl" {
+ t.Fatalf("unsafe session id wrote into config directory: %v, %v", entries, err)
+ }
+ if data, err := os.ReadFile(victim); err != nil || string(data) != "unrelated history" {
+ t.Fatalf("unrelated history was modified: %q, %v", data, err)
+ }
+}
+
+// Exercise real task preparation and launch with a fake CLI, so custom_env
+// must reach both the migration gate and the subprocess without using an account.
+func TestRunTask_ClaudeWorktreeResumeUsesCustomConfigDir(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script agent fixture is POSIX-only")
+ }
+ home, configDir := t.TempDir(), t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, "inherited-config"))
+ repo := createDaemonTestRepo(t)
+ captureFile := filepath.Join(t.TempDir(), "args.txt")
+ fakeBin := filepath.Join(t.TempDir(), "claude")
+ writeTestExecutable(t, fakeBin, []byte(`#!/bin/sh
+printf '%s\n' "$@" > "$CAPTURE_FILE"
+printf '%s\n' "$CLAUDE_CONFIG_DIR" "$HOME" >> "$CAPTURE_FILE"
+printf 'first turn work\n' > task-work.txt
+IFS= read -r _
+printf '%s\n' '{"type":"system","session_id":"session-custom-config"}'
+printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"session-custom-config","result":"done"}'
+`))
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ t.Cleanup(srv.Close)
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d := &Daemon{
+ client: NewClient(srv.URL), logger: logger, localPathLocks: NewLocalPathLocker(),
+ workspaces: make(map[string]*workspaceState), activeEnvRoots: make(map[string]int),
+ cfg: Config{
+ DaemonID: "daemon-config", WorkspacesRoot: t.TempDir(), AgentTimeout: 5 * time.Second,
+ ServerBaseURL: srv.URL, Agents: map[string]AgentEntry{"claude": {Path: fakeBin}},
+ },
+ }
+ ref, err := json.Marshal(localDirectoryRef{LocalPath: repo, DaemonID: d.cfg.DaemonID, ExecutionMode: localDirectoryModeWorktree})
+ if err != nil {
+ t.Fatal(err)
+ }
+ task := Task{
+ ID: "task-config-first", WorkspaceID: "ws-config", IssueID: "issue-config", IssueIdentifier: "MUL-8413",
+ RuntimeID: "runtime-config", AgentID: "agent-config", AuthToken: "mat_config_test",
+ Agent: &AgentData{ID: "agent-config", Name: "config-agent", CustomEnv: map[string]string{
+ "CLAUDE_CONFIG_DIR": configDir, "HOME": filepath.Join(home, "blocked-home"), "CAPTURE_FILE": captureFile,
+ }},
+ ProjectResources: []ProjectResourceData{{ID: "repo-config", ResourceType: localDirectoryResourceType, ResourceRef: ref}},
+ }
+ first, err := d.runTask(context.Background(), task, "claude", 0, logger)
+ if err != nil || first.Status != "completed" || first.BranchName == "" {
+ t.Fatalf("first turn = %+v, %v", first, err)
+ }
+ if _, err := os.Stat(first.WorkDir); !os.IsNotExist(err) {
+ t.Fatalf("prior worktree was not removed: %v", err)
+ }
+ src := filepath.Join(configDir, "projects", encodeClaudeCwd(first.WorkDir), first.SessionID+".jsonl")
+ if err := os.MkdirAll(filepath.Dir(src), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ const transcript = "{\"type\":\"user\",\"message\":{\"content\":\"prior discussion\"}}\n"
+ if err := os.WriteFile(src, []byte(transcript), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ task.ID, task.PriorSessionID, task.PriorWorkDir = "task-config-second", first.SessionID, first.WorkDir
+ second, err := d.runTask(context.Background(), task, "claude", 0, logger)
+ if err != nil || second.Status != "completed" || second.BranchName != first.BranchName {
+ t.Fatalf("second turn = %+v, %v", second, err)
+ }
+ args, err := os.ReadFile(captureFile)
+ if err != nil || !strings.Contains(string(args), "--resume\n"+first.SessionID+"\n") || !strings.HasSuffix(string(args), configDir+"\n"+home+"\n") {
+ t.Fatalf("second turn did not receive the resume and effective env: %s, %v", args, err)
+ }
+ dst := filepath.Join(configDir, "projects", encodeClaudeCwd(second.WorkDir), first.SessionID+".jsonl")
+ if data, err := os.ReadFile(dst); err != nil || string(data) != transcript {
+ t.Fatalf("second turn transcript = %q, %v", data, err)
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index baee8accd2..eec74cc5d5 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -6596,6 +6596,10 @@ func providerNeedsInlineSystemPrompt(provider string) bool {
// Codex also has a conversation-scoped store for local_directory tasks. A
// continued worktree may use a new cwd while retaining its branch and rollout.
// Managed Codex tasks still require the same existing directory.
+// Claude is cwd-keyed and has no conversation-scoped store, but a continued
+// worktree can bring the prior transcript with it: when the transcript has
+// been migrated into this run's encoded projects directory (#9731), the same
+// relaxed rule applies. Everywhere else Claude keeps the strict rule.
// sameExistingDir reports whether two paths name the same existing directory.
// False when either cannot be stat'd, which is the safe answer for cwd-keyed
// providers: an absent prior workdir means there is nothing to resume from.
@@ -6622,7 +6626,83 @@ func codexWorktreeResumeEligible(env *execenv.Environment, store string) bool {
return env != nil && env.LocalWorktree != nil && env.LocalWorktree.Continued && env.CodexHome != "" && store != ""
}
-func gateResumeToReachableSession(task *Task, taskCtx *execenv.TaskContextForEnv, provider, envWorkDir string, sessionHomeReachable, refusesMissingSessionCwd, codexWorktreeResumeEligible bool, taskLog *slog.Logger) bool {
+// encodeClaudeCwd mirrors Claude Code's on-disk projects directory naming: it
+// flattens the task's cwd by replacing every non-alphanumeric character with a
+// dash, so /home/u/repo resolves to ~/.claude/projects/-home-u-repo. The
+// mapping is lossy (two cwds can flatten to the same name), which is fine —
+// the CLI resolves sessions through the same mapping.
+// Long-path truncation/hashing and Windows drive-letter normalization are not
+// modeled here; paths requiring them may fall back to a fresh session.
+func encodeClaudeCwd(cwd string) string {
+ return strings.Map(func(r rune) rune {
+ if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' {
+ return r
+ }
+ return '-'
+ }, cwd)
+}
+
+// migrateClaudeWorktreeTranscript copies the prior session's transcript into
+// this run's encoded projects directory so Claude Code can resolve it from the
+// continued worktree's new cwd (#9731). Claude Code looks sessions up under
+// <config-dir>/projects/<encoded-cwd>/ and only falls back to a global search
+// when the local directory misses; copying the transcript in makes the resume
+// take the primary path instead of depending on that fallback. Idempotent: a
+// transcript already present from an earlier migration is left as-is. Reports
+// whether this run's directory now holds the transcript — anything else
+// (changed cwd outside a continued worktree, missing source, unwritable
+// destination) reports false and the gate keeps the strict same-directory
+// rule. The copy left behind in the prior task's directory is orphaned until
+// the operator or a future GC pass reclaims it.
+func migrateClaudeWorktreeTranscript(env *execenv.Environment, sessionID, envWorkDir, priorWorkDir string, childEnv map[string]string, taskLog *slog.Logger) bool {
+ if env == nil || env.LocalWorktree == nil || !env.LocalWorktree.Continued {
+ return false
+ }
+ if sessionID == "" || priorWorkDir == "" || envWorkDir == "" || priorWorkDir == envWorkDir {
+ return false
+ }
+ if sessionID == "." || sessionID == ".." || strings.ContainsAny(sessionID, "/\\:\x00") {
+ taskLog.Debug("claude: invalid session id for transcript migration")
+ return false
+ }
+ priorConfigDir, err := agent.ClaudeConfigDir(childEnv, priorWorkDir)
+ if err != nil {
+ taskLog.Debug("claude: cannot resolve prior transcript config directory", "error", err)
+ return false
+ }
+ configDir, err := agent.ClaudeConfigDir(childEnv, envWorkDir)
+ if err != nil {
+ taskLog.Debug("claude: cannot resolve transcript config directory", "error", err)
+ return false
+ }
+ src := filepath.Join(priorConfigDir, "projects", encodeClaudeCwd(priorWorkDir), sessionID+".jsonl")
+ dstDir := filepath.Join(configDir, "projects", encodeClaudeCwd(envWorkDir))
+ dst := filepath.Join(dstDir, sessionID+".jsonl")
+ if info, err := os.Stat(dst); err == nil && info.Mode().IsRegular() {
+ return true
+ }
+ data, err := os.ReadFile(src)
+ if err != nil {
+ taskLog.Debug("claude: cannot read prior session transcript", "path", src, "error", err)
+ return false
+ }
+ if err := os.MkdirAll(dstDir, 0o755); err != nil {
+ taskLog.Debug("claude: cannot create transcript directory", "path", dstDir, "error", err)
+ return false
+ }
+ if err := os.WriteFile(dst, data, 0o600); err != nil {
+ taskLog.Debug("claude: cannot write migrated transcript", "path", dst, "error", err)
+ return false
+ }
+ taskLog.Info("claude: migrated prior session transcript into the continued worktree cwd",
+ "session_id", sessionID,
+ "prior_workdir", priorWorkDir,
+ "workdir", envWorkDir,
+ )
+ return true
+}
+
+func gateResumeToReachableSession(task *Task, taskCtx *execenv.TaskContextForEnv, provider, envWorkDir string, sessionHomeReachable, refusesMissingSessionCwd, codexWorktreeResumeEligible, claudeResumeReady bool, taskLog *slog.Logger) bool {
var reachable bool
if providerUsesPiSessionFile(provider) {
reachable = piSessionResumable(task.PriorSessionID, refusesMissingSessionCwd)
@@ -6630,6 +6710,8 @@ func gateResumeToReachableSession(task *Task, taskCtx *execenv.TaskContextForEnv
reachable = sessionHomeReachable
} else if provider == "codex" && codexWorktreeResumeEligible {
reachable = sessionHomeReachable
+ } else if provider == "claude" && claudeResumeReady {
+ reachable = sessionHomeReachable
} else {
// Compare the directories, not the spelling. Reuse runs in the canonical
// path it validated and locked, which need not be character-identical to
@@ -8537,11 +8619,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// agent.Config.BuiltinRuntime: it separates the provider's own discovered
// binary from an arbitrary command speaking its protocol. Reused here so
// the gate and the backend cannot disagree about which one is running.
+ // Claude's config lookup needs only the inherited environment plus allowed
+ // custom_env; taskMulticaEnvironment below does not override its config or
+ // home variables. Apply the same blocklist as the eventual child env.
+ claudeResumeReady := provider == "claude" && migrateClaudeWorktreeTranscript(
+ env, task.PriorSessionID, env.WorkDir, task.PriorWorkDir, sanitizeAgentEnv(agentEnvOverrides), taskLog,
+ )
resumeReachable := gateResumeToReachableSession(
&task, &taskCtx, provider, env.WorkDir,
sessionHomeReachable(provider, env, envReused),
providerRefusesMissingSessionCwd(provider, !usesCustomProfileCommand),
provider == "codex" && codexWorktreeResumeEligible(env, execenv.CodexSessionStorePath(d.cfg.Profile, taskCtx)),
+ claudeResumeReady,
taskLog,
)
// A reachable workdir or continued local worktree is not sufficient for a
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 41c76fe646..f6f760f799 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2083,7 +2083,7 @@ func TestGateResumeToReachableSession(t *testing.T) {
task := Task{PriorSessionID: tt.sessionID, PriorWorkDir: priorDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: tt.sessionID != ""}
- reachable := gateResumeToReachableSession(&task, &taskCtx, "claude", envDir, !tt.sessionHomeUnreachable, false, false, slog.Default())
+ reachable := gateResumeToReachableSession(&task, &taskCtx, "claude", envDir, !tt.sessionHomeUnreachable, false, false, false, slog.Default())
if reachable != tt.wantReused {
t.Fatalf("reachable = %v, want %v", reachable, tt.wantReused)
@@ -2132,7 +2132,7 @@ func TestGateCodexResumeAcrossLocalWorktrees(t *testing.T) {
{name: "managed workdir", provider: "codex", stableStore: true, codexHome: true, rolloutPresent: true},
{name: "in-place changed workdir", provider: "codex", localDirectory: true, stableStore: true, codexHome: true, rolloutPresent: true},
{name: "in-place same workdir", provider: "codex", localDirectory: true, stableStore: true, codexHome: true, sameWorkdir: true, rolloutPresent: true, wantResume: true},
- {name: "other provider", provider: "claude", localWorktree: &execenv.LocalWorktree{Continued: true}, stableStore: true, codexHome: true, rolloutPresent: true},
+ {name: "other provider", provider: "cursor", localWorktree: &execenv.LocalWorktree{Continued: true}, stableStore: true, codexHome: true, rolloutPresent: true},
} {
t.Run(tt.name, func(t *testing.T) {
task := Task{PriorSessionID: "session-1", PriorWorkDir: priorDir}
@@ -2149,7 +2149,7 @@ func TestGateCodexResumeAcrossLocalWorktrees(t *testing.T) {
}
store := execenv.CodexSessionStorePath("test", taskCtx)
eligible := codexWorktreeResumeEligible(env, store)
- if got := gateResumeToReachableSession(&task, &taskCtx, tt.provider, env.WorkDir, true, false, eligible, slog.Default()); got {
+ if got := gateResumeToReachableSession(&task, &taskCtx, tt.provider, env.WorkDir, true, false, eligible, false, slog.Default()); got {
if tt.provider == "codex" && !tt.rolloutPresent {
gateCodexResumeToRolloutPresence(&task, &taskCtx, tt.provider, t.TempDir(), slog.Default())
} else {
@@ -2166,6 +2166,73 @@ func TestGateCodexResumeAcrossLocalWorktrees(t *testing.T) {
}
}
+// Claude Code keys its session store to the cwd, but a continued local
+// worktree runs in a fresh directory every turn (#9731). The gate accepts the
+// resume only when the prior transcript has been migrated into this run's
+// encoded projects directory first; a missing transcript still drops it,
+// fail-closed like the cwd-keyed default.
+func TestGateClaudeResumeAcrossLocalWorktrees(t *testing.T) {
+ t.Parallel()
+ for _, tt := range []struct {
+ name string
+ continued bool
+ transcript bool
+ sameWorkdir bool
+ wantResume bool
+ }{
+ {name: "continued worktree with migrated transcript", continued: true, transcript: true, wantResume: true},
+ {name: "continued worktree without transcript", continued: true},
+ {name: "new forked branch", continued: false, transcript: true},
+ {name: "in-place same workdir", sameWorkdir: true, transcript: true, wantResume: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ prior, work, configDir := t.TempDir(), t.TempDir(), t.TempDir()
+ if tt.sameWorkdir {
+ work = prior
+ }
+ if tt.transcript {
+ projectDir := filepath.Join(configDir, "projects", encodeClaudeCwd(prior))
+ if err := os.MkdirAll(projectDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(projectDir, "session-1.jsonl"), []byte("{}"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ task := Task{PriorSessionID: "session-1", PriorWorkDir: prior}
+ taskCtx := execenv.TaskContextForEnv{AgentID: "agent-1", PriorSessionResumed: true}
+ env := &execenv.Environment{WorkDir: work, LocalWorktree: &execenv.LocalWorktree{Continued: tt.continued}}
+
+ ready := migrateClaudeWorktreeTranscript(env, task.PriorSessionID, env.WorkDir, task.PriorWorkDir, map[string]string{"CLAUDE_CONFIG_DIR": configDir}, slog.Default())
+ reachable := gateResumeToReachableSession(&task, &taskCtx, "claude", env.WorkDir, true, false, false, ready, slog.Default())
+
+ if reachable != tt.wantResume {
+ t.Fatalf("reachable = %v, want %v", reachable, tt.wantResume)
+ }
+ if got := task.PriorSessionID != ""; got != tt.wantResume {
+ t.Fatalf("resume=%v, want %v", got, tt.wantResume)
+ }
+ if taskCtx.PriorSessionResumed != tt.wantResume || task.PriorSessionResumeUnavailable == tt.wantResume || taskCtx.PriorSessionResumeUnavailable == tt.wantResume {
+ t.Fatalf("inconsistent resume state: task=%+v taskCtx=%+v", task, taskCtx)
+ }
+ })
+ }
+}
+
+func TestEncodeClaudeCwd(t *testing.T) {
+ for _, tt := range []struct{ in, want string }{
+ {"/home/user/repo", "-home-user-repo"},
+ {"/tmp/dir with space", "-tmp-dir-with-space"},
+ {"/a/b.c/d", "-a-b-c-d"},
+ {`C:\Users\dev`, "C--Users-dev"},
+ } {
+ if got := encodeClaudeCwd(tt.in); got != tt.want {
+ t.Fatalf("encodeClaudeCwd(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ }
+}
+
// Hermes resumes from HERMES_HOME, independently of the task's cwd (#9062).
func TestGateHermesResumeToSessionHome(t *testing.T) {
t.Parallel()
@@ -2197,7 +2264,7 @@ func TestGateHermesResumeToSessionHome(t *testing.T) {
task := Task{PriorSessionID: "session-1", PriorWorkDir: priorDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
got := gateResumeToReachableSession(&task, &taskCtx, "hermes", workDir,
- sessionHomeReachable("hermes", env, tt.envReused), false, false, slog.Default())
+ sessionHomeReachable("hermes", env, tt.envReused), false, false, false, slog.Default())
if got != tt.want || (task.PriorSessionID == "session-1") != tt.want || taskCtx.PriorSessionResumed != tt.want {
t.Fatalf("resume = %v, session = %q, resumed = %v; want %v", got, task.PriorSessionID, taskCtx.PriorSessionResumed, tt.want)
}
@@ -2259,7 +2326,7 @@ func TestHermesPreparedSessionReachability(t *testing.T) {
task := Task{PriorSessionID: "session-1", PriorWorkDir: first.WorkDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
if got := gateResumeToReachableSession(&task, &taskCtx, "hermes", env.WorkDir,
- sessionHomeReachable("hermes", env, false), false, false, slog.Default()); got != tt.want {
+ sessionHomeReachable("hermes", env, false), false, false, false, slog.Default()); got != tt.want {
t.Fatalf("reachable = %v, want %v", got, tt.want)
}
})
@@ -2290,7 +2357,7 @@ func TestGatePiResumeToSessionFile(t *testing.T) {
task := Task{PriorSessionID: sessionFile, PriorWorkDir: priorDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
- reachable := gateResumeToReachableSession(&task, &taskCtx, provider, envDir, true, providerRefusesMissingSessionCwd(provider, true), false, slog.Default())
+ reachable := gateResumeToReachableSession(&task, &taskCtx, provider, envDir, true, providerRefusesMissingSessionCwd(provider, true), false, false, slog.Default())
if !reachable {
t.Fatal("Pi-family session file should remain reachable across workdirs")
@@ -2350,7 +2417,7 @@ func TestGatePiResumeDropsUnusableSessionFile(t *testing.T) {
task := Task{PriorSessionID: sessionPath, PriorWorkDir: workDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
- reachable := gateResumeToReachableSession(&task, &taskCtx, "pi", workDir, true, providerRefusesMissingSessionCwd("pi", true), false, slog.Default())
+ reachable := gateResumeToReachableSession(&task, &taskCtx, "pi", workDir, true, providerRefusesMissingSessionCwd("pi", true), false, false, slog.Default())
if reachable {
t.Fatalf("%s Pi session was treated as reachable", test.name)
@@ -2521,7 +2588,7 @@ func TestGatePiResumeChecksRecordedCwd(t *testing.T) {
task := Task{PriorSessionID: sessionPath, PriorWorkDir: liveDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
- reachable := gateResumeToReachableSession(&task, &taskCtx, provider, workDir, true, runtime.refusesMissingCwd, false, slog.Default())
+ reachable := gateResumeToReachableSession(&task, &taskCtx, provider, workDir, true, runtime.refusesMissingCwd, false, false, slog.Default())
if reachable != wantReachable {
t.Fatalf("reachable = %v, want %v", reachable, wantReachable)
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 327fb86801..9086486e8b 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -929,6 +929,12 @@ func (s *claudeUsageSnapshot) appendedCostStateUsage() (map[string]TokenUsage, b
return readLastClaudeCostStateUsage(f, s.offset, info.Size())
}
+// ClaudeConfigDir resolves Claude's config directory using the same inherited
+// environment and task overrides as the backend's child process.
+func ClaudeConfigDir(extraEnv map[string]string, cwd string) (string, error) {
+ return claudeConfigDir(buildEnv(extraEnv), cwd)
+}
+
func claudeConfigDir(env []string, cwd string) (string, error) {
if value, ok := lastClaudeEnvValue(env, "CLAUDE_CONFIG_DIR"); ok && value != "" {
return resolveClaudeConfigPath(value, cwd)
diff --git a/server/pkg/agent/claude_config_test.go b/server/pkg/agent/claude_config_test.go
new file mode 100644
index 0000000000..579b9d6fec
--- /dev/null
+++ b/server/pkg/agent/claude_config_test.go
@@ -0,0 +1,33 @@
+package agent
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+func TestClaudeConfigDir(t *testing.T) {
+ home, inheritedConfig, taskHome, taskConfig, cwd := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ for _, tt := range []struct {
+ name string
+ inherited string
+ overrides map[string]string
+ want string
+ }{
+ {name: "inherited config", inherited: inheritedConfig, want: inheritedConfig},
+ {name: "task config wins", inherited: inheritedConfig, overrides: map[string]string{"CLAUDE_CONFIG_DIR": taskConfig}, want: taskConfig},
+ {name: "empty task config uses home", inherited: inheritedConfig, overrides: map[string]string{"CLAUDE_CONFIG_DIR": ""}, want: filepath.Join(home, ".claude")},
+ {name: "inherited home", want: filepath.Join(home, ".claude")},
+ {name: "child home", overrides: map[string]string{"HOME": taskHome, "USERPROFILE": taskHome}, want: filepath.Join(taskHome, ".claude")},
+ {name: "relative config", overrides: map[string]string{"CLAUDE_CONFIG_DIR": "../claude-config"}, want: filepath.Join(filepath.Dir(cwd), "claude-config")},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Setenv("CLAUDE_CONFIG_DIR", tt.inherited)
+ got, err := ClaudeConfigDir(tt.overrides, cwd)
+ if err != nil || got != tt.want {
+ t.Fatalf("ClaudeConfigDir() = %q, %v; want %q", got, err, tt.want)
+ }
+ })
+ }
+}