Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): preserve host temp for Windows Claude Git Bash (#8985)
makesomethingshiteb59a69722ce
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a77d1c4c9e..4db3c43090 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -547,6 +547,13 @@ jobs:# real skills instead of the test directories.run: go test ./internal/daemon -v -run '^(TestListRuntimeLocalSkills_HermesFollowsTaskHome|TestLocalSkills_DiscoversACPProviderRoots)$' -count=1 -timeout=5m+ - name: Test Windows Claude Git Bash temp lifecycle+ working-directory: server+ run: |+ $env:MULTICA_TEST_GIT_BASH = "$env:ProgramFiles\Git\usr\bin\bash.exe"+ if (-not (Test-Path -LiteralPath $env:MULTICA_TEST_GIT_BASH)) { throw "Git for Windows is required" }+ go test -tags=gitbashintegration ./internal/daemon -v -run '^(TestWindowsClaudeGitBashTaskTempLifecycle|TestTaskMulticaEnvironment.*|TestTaskTempBaseDir)$' -count=1 -timeout=5m+- name: Test Windows agent launcher argv/stdin handlingworking-directory: server# Agent prompts must never reach a Windows launcher through argv: thediff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 8d7ad6983f..c1ef92debe 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -360,7 +360,7 @@ The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and applies several disk- **Hermes session store reclamation** — a conversation's Hermes transcript (`state.db`) lives at `<profile dir>/hermes-sessions/<agent-id>/<hermes-profile>/<conversation>/`, outside any task directory, so a follow-up turn can resume it (see [Hermes agent memory](#hermes-agent-memory)). A store untouched for `MULTICA_GC_HERMES_SESSION_TTL` is removed. The default matches the Codex session store rather than the memory store above: these hold full transcripts, and reclaiming an idle one costs a thread that starts fresh (with a continuity notice), not an agent that forgot what it learned. A store a running task holds is never reclaimed.- **Hermes memory store reclamation** — a Hermes agent's long-term memory (`memories/`) lives at `<profile dir>/hermes-state/<agent-id>/<hermes-profile>/`, outside any task directory, so it survives across tasks and issues (see [Hermes agent memory](#hermes-agent-memory)). A store untouched for `MULTICA_GC_HERMES_MEMORY_TTL` is removed, giving a deleted agent's memory an eventual-reclamation guarantee. The default is deliberately long: these are a handful of markdown files, and reclaiming one is user-visible amnesia rather than a cache miss. A store a running task holds is never reclaimed.-- **Task temp dir reclamation** — every task gets a private temp directory (`multica-task-*`) under the system temp base (`/tmp`, or `MULTICA_AGENT_TEMP_BASE`), exported to the agent as `TMPDIR`/`TMP`/`TEMP`. It is removed when the run ends, but that removal never happens when the daemon is killed and does not succeed while a file inside is still open — common on Windows, where an open handle makes the delete fail outright. These directories live outside `MULTICA_WORKSPACES_ROOT`, so nothing else reclaimed them and whatever the end-of-run removal missed accumulated forever. Every GC cycle now sweeps the temp base. Liveness is decided by the directory's `.task_lock` — the same OS advisory lock an env root uses, which the kernel releases when the holding process dies — not by age: a directory still in use is never removed however old it is, including one owned by a different daemon sharing the same temp base, and a directory whose owner is gone is removed on the next cycle however new it is. Directories left by a daemon predating that lock carry no lock file, so nothing can be proven about them and age is the only signal available. Reclaiming those is an operator's explicit decision: `MULTICA_GC_TASK_TEMP_LEGACY_TTL` defaults to `0`, which leaves them in place. Set it to a duration only once you know no pre-lock daemon is still running tasks on this machine — a task may legitimately run for weeks (there is no default agent timeout), a daemon on another profile can still be on the old binary, and every daemon on the machine shares one temp base, so a TTL here can delete a `TMPDIR` that is still in use. Each GC cycle logs how many such directories it left alone. Even with a TTL set, a directory holding no task content is never reclaimed on age — an old empty leftover, or a shell left by a daemon that died between creating the directory and publishing its lock — because holding no content is exactly what a directory currently being published looks like, and deleting one of those would take the `TMPDIR` of a task that is starting. Those shells are a few bytes each. Only entries carrying the `multica-task-` prefix are ever considered — the temp base itself is usually shared with other programs — and a directory this sweep cannot read is never touched.+- **Task temp dir reclamation** — every task gets a private temp directory (`multica-task-*`) under the system temp base (`/tmp`, or `MULTICA_AGENT_TEMP_BASE`), exported to the agent as `TMPDIR`/`TMP`/`TEMP`. Windows Claude Code instead inherits the daemon user's `TMP`/`TEMP` so Git Bash's shared `/tmp` does not point at a task directory that will be deleted; `TMPDIR` stays task-local and `CLAUDE_CODE_TMPDIR` defaults to that directory unless the user overrides it. It is removed when the run ends, but that removal never happens when the daemon is killed and does not succeed while a file inside is still open — common on Windows, where an open handle makes the delete fail outright. These directories live outside `MULTICA_WORKSPACES_ROOT`, so nothing else reclaimed them and whatever the end-of-run removal missed accumulated forever. Every GC cycle now sweeps the temp base. Liveness is decided by the directory's `.task_lock` — the same OS advisory lock an env root uses, which the kernel releases when the holding process dies — not by age: a directory still in use is never removed however old it is, including one owned by a different daemon sharing the same temp base, and a directory whose owner is gone is removed on the next cycle however new it is. Directories left by a daemon predating that lock carry no lock file, so nothing can be proven about them and age is the only signal available. Reclaiming those is an operator's explicit decision: `MULTICA_GC_TASK_TEMP_LEGACY_TTL` defaults to `0`, which leaves them in place. Set it to a duration only once you know no pre-lock daemon is still running tasks on this machine — a task may legitimately run for weeks (there is no default agent timeout), a daemon on another profile can still be on the old binary, and every daemon on the machine shares one temp base, so a TTL here can delete a `TMPDIR` that is still in use. Each GC cycle logs how many such directories it left alone. Even with a TTL set, a directory holding no task content is never reclaimed on age — an old empty leftover, or a shell left by a daemon that died between creating the directory and publishing its lock — because holding no content is exactly what a directory currently being published looks like, and deleting one of those would take the `TMPDIR` of a task that is starting. Those shells are a few bytes each. Only entries carrying the `multica-task-` prefix are ever considered — the temp base itself is usually shared with other programs — and a directory this sweep cannot read is never touched.Configured patterns are basename-only — entries containing `/` or `\` are silently dropped — and `.git` subtrees are never descended into. The managed Codex cache is matched by its exact relative path, so a repository's own `.sandbox-bin` is not removed unless an operator explicitly adds that basename to `MULTICA_GC_ARTIFACT_PATTERNS`. The default list (`node_modules`, `.next`, `.turbo`) is intentionally narrow; extend it per deployment if your repos consistently produce other regenerable directories (for example, `MULTICA_GC_ARTIFACT_PATTERNS=node_modules,.next,.turbo,target,__pycache__`). To disable artifact cleanup entirely, including the managed Codex cache, set `MULTICA_GC_ARTIFACT_TTL=0`.diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex b62b9bc358..490433631b 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -103,7 +103,7 @@ Le tableau liste les variables que les runtimes personnalisés peuvent utiliser| `MULTICA_AGENT_NAME` | Nom affiché de l'agent assigné | Indicatif || `MULTICA_DAEMON_PORT` | Port local de santé/API du daemon utilisé par les commandes réservées aux exécutions, comme `multica repo checkout` | Indicatif || `MULTICA_TASK_SLOT` | Emplacement dans le pool de parallélisme global du daemon ; utile pour les ressources indexées par emplacement, comme les GPU | Indicatif |-| `TMPDIR` | Répertoire temporaire privé de l'exécution en cours ; également fourni sous `TMP` et `TEMP` pour les outils multiplateformes | Indicatif |+| `TMPDIR` | Répertoire temporaire privé de l'exécution ; également fourni sous `TMP` et `TEMP`, sauf pour Claude Code sous Windows, qui hérite des chemins temporaires utilisateur pour le `/tmp` partagé de Git Bash et utilise par défaut le répertoire temporaire de la tâche pour `CLAUDE_CODE_TMPDIR` | Indicatif |Le serveur détermine l'auteur des requêtes effectuées avec `MULTICA_TOKEN` ; les écritures telles que les commentaires de tâche sont attribuées à l'agent assigné et à l'exécution en cours. Pour tout savoir sur le rattachement du jeton, ses permissions, l'attribution, sa durée de vie maximale de 24 heures et son nettoyage, consultez [Jetons temporaires pour les exécutions d'agents](/auth-tokens#jetons-temporaires-pour-les-exécutions-dagents).diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 75953ba7be..c5d8d49094 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -103,7 +103,7 @@ multica daemon start| `MULTICA_AGENT_NAME` | 割り当てられたエージェントの表示名 | 参考情報 || `MULTICA_DAEMON_PORT` | `multica repo checkout` など作業専用コマンドが使うローカルデーモンのヘルス/API ポート | 参考情報 || `MULTICA_TASK_SLOT` | デーモン全体の同時実行プール内のスロット。GPU などスロット番号付きリソースに使用可能 | 参考情報 |-| `TMPDIR` | 実行中の作業専用の一時ディレクトリ。クロスプラットフォームツール向けに `TMP` と `TEMP` でも提供 | 参考情報 |+| `TMPDIR` | 実行中の作業専用の一時ディレクトリ。`TMP` と `TEMP` でも提供しますが、Windows の Claude Code は Git Bash の共有 `/tmp` のためユーザーの一時パスを継承し、`CLAUDE_CODE_TMPDIR` の既定値を作業の一時ディレクトリに設定 | 参考情報 |`MULTICA_TOKEN` を使ったリクエストの作成者はサーバーが決定し、タスクへのコメントなどの書き込みは、割り当てられたエージェントと実行中の作業に帰属します。認証情報の完全な紐付け、権限、帰属、最長 24 時間の有効期間、クリーンアップについては、[エージェント実行用の一時トークン](/auth-tokens#エージェント実行用の一時トークン)を参照してください。diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex e039a390c5..e842e1600f 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -103,7 +103,7 @@ multica daemon start| `MULTICA_AGENT_NAME` | 할당된 에이전트의 표시 이름 | 참고 정보 || `MULTICA_DAEMON_PORT` | `multica repo checkout` 같은 작업 전용 명령이 사용하는 로컬 데몬 상태/API 포트 | 참고 정보 || `MULTICA_TASK_SLOT` | 데몬 전체 동시 실행 풀의 슬롯. GPU 같은 슬롯 번호 기반 리소스에 사용 가능 | 참고 정보 |-| `TMPDIR` | 실행 중인 작업의 비공개 임시 디렉터리. 크로스 플랫폼 도구를 위해 `TMP`와 `TEMP`로도 제공 | 참고 정보 |+| `TMPDIR` | 실행 중인 작업의 비공개 임시 디렉터리. `TMP`와 `TEMP`로도 제공하지만, Windows Claude Code는 Git Bash의 공유 `/tmp`를 위해 사용자 temp 경로를 상속하고 `CLAUDE_CODE_TMPDIR`의 기본값을 작업 임시 디렉터리로 지정 | 참고 정보 |`MULTICA_TOKEN`을 사용하는 요청의 작성자는 서버가 결정하며, 태스크 댓글 같은 쓰기는 할당된 에이전트와 실행 중인 작업에 귀속됩니다. 자격 증명의 전체 바인딩, 권한, 귀속, 최대 24시간의 유효 기간 및 정리 동작은 [에이전트 실행용 임시 토큰](/auth-tokens#에이전트-실행용-임시-토큰)을 참고하세요.diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex bfcbaeefed..b8478e2c7a 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -103,7 +103,7 @@ The table lists the variables that custom runtimes can use today. It is intentio| `MULTICA_AGENT_NAME` | Display name of the assigned agent | Informational || `MULTICA_DAEMON_PORT` | Local daemon health/API port used by task-only commands such as `multica repo checkout` | Informational || `MULTICA_TASK_SLOT` | Slot in the daemon-wide concurrency pool; useful for slot-indexed resources such as GPUs | Informational |-| `TMPDIR` | Private temporary directory for the active task; also supplied as `TMP` and `TEMP` for cross-platform tools | Informational |+| `TMPDIR` | Private temporary directory for the active task; also supplied as `TMP` and `TEMP` except for Windows Claude Code, which inherits user temp paths for Git Bash's shared `/tmp` and defaults `CLAUDE_CODE_TMPDIR` to the task temp directory | Informational |The server determines authorship for requests made with `MULTICA_TOKEN`; writes such as issue comments are attributed to the assigned agent and active task. For the token's complete binding, permissions, attribution, 24-hour maximum lifetime, and cleanup behavior, see [Temporary tokens for agent runs](/auth-tokens#temporary-tokens-for-agent-runs).diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 43cb763439..066ee2448e 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -103,7 +103,7 @@ multica daemon start| `MULTICA_AGENT_NAME` | 被指派智能体的显示名称 | 仅供参考 || `MULTICA_DAEMON_PORT` | 本地守护进程的健康检查/API 端口,供 `multica repo checkout` 等仅限 task 的命令使用 | 仅供参考 || `MULTICA_TASK_SLOT` | 守护进程全局并发池中的槽位,可用于 GPU 等按槽位编号的资源 | 仅供参考 |-| `TMPDIR` | 当前 task 的私有临时目录;也会以 `TMP` 和 `TEMP` 提供给跨平台工具 | 仅供参考 |+| `TMPDIR` | 当前 task 的私有临时目录;也会以 `TMP` 和 `TEMP` 提供,但 Windows 上的 Claude Code 会继承用户临时路径以维持 Git Bash 的共享 `/tmp`,并将 `CLAUDE_CODE_TMPDIR` 默认设为 task 临时目录 | 仅供参考 |使用 `MULTICA_TOKEN` 发起请求时,作者身份由服务端决定;任务评论等写入操作会归属到被指派的智能体和当前 task。令牌的完整绑定关系、权限、归属方式、最长 24 小时的有效期和清理规则见[智能体执行的临时令牌](/auth-tokens#智能体执行的临时令牌)。diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 6c1a843fa1..704267fddc 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -175,8 +175,8 @@ func taskScopedAuthToken(task Task) (string, error) {return token, nil}-func taskMulticaEnvironment(task Task, agentName, token, configRoot, workspacesRoot, serverURL string, healthPort, slot int, tempDir string) map[string]string {- return map[string]string{+func taskMulticaEnvironment(task Task, provider, agentName, token, configRoot, workspacesRoot, serverURL string, healthPort, slot int, tempDir string) map[string]string {+ env := map[string]string{"MULTICA_TOKEN": token,cli.TaskConfigRootEnv: configRoot,TaskWorkspacesRootEnv: workspacesRoot,@@ -191,6 +191,23 @@ func taskMulticaEnvironment(task Task, agentName, token, configRoot, workspacesR"TMP": tempDir,"TEMP": tempDir,}+ if runtime.GOOS == "windows" && provider == "claude" {+ // Git Bash shares its /tmp mount across processes. Keep its host temp+ // target alive while TMPDIR and Claude's internal files stay task-local.+ delete(env, "TMP")+ delete(env, "TEMP")+ if os.Getenv("CLAUDE_CODE_TMPDIR") == "" {+ env["CLAUDE_CODE_TMPDIR"] = tempDir+ if task.Agent != nil {+ for key := range task.Agent.CustomEnv {+ if strings.EqualFold(key, "CLAUDE_CODE_TMPDIR") {+ delete(env, "CLAUDE_CODE_TMPDIR")+ }+ }+ }+ }+ }+ return env}// taskRunner executes a single agent task and returns the result.@@ -8466,7 +8483,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot itaskLog.Error("task auth token invalid; refusing to start agent", "error", err)return TaskResult{}, err}- agentEnv := taskMulticaEnvironment(task, agentName, agentToken, env.MulticaConfigRoot, d.cfg.WorkspacesRoot, d.cfg.ServerBaseURL, d.cfg.HealthPort, slot, taskTempDir)+ agentEnv := taskMulticaEnvironment(task, provider, agentName, agentToken, env.MulticaConfigRoot, d.cfg.WorkspacesRoot, d.cfg.ServerBaseURL, d.cfg.HealthPort, slot, taskTempDir)if checkoutMode := repoCheckoutModeFor(provider, runtime.GOOS); checkoutMode != "" {agentEnv[repoCheckoutModeEnv] = checkoutMode}diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 34080d36f7..b8dbe96ba6 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -547,7 +547,7 @@ func TestTaskMulticaEnvironmentIncludesPrivateConfigRoot(t *testing.T) {AgentID: "agent-test",WorkspaceID: "workspace-test",}- env := taskMulticaEnvironment(task, "agent-name", fakeToken, taskRoot, workspacesRoot, "https://task.example", 19514, 3, "/task/tmp")+ env := taskMulticaEnvironment(task, "codex", "agent-name", fakeToken, taskRoot, workspacesRoot, "https://task.example", 19514, 3, "/task/tmp")want := map[string]string{"MULTICA_TOKEN": fakeToken,@@ -584,6 +584,61 @@ func TestTaskMulticaEnvironmentIncludesPrivateConfigRoot(t *testing.T) {}}+func TestTaskMulticaEnvironmentTempPolicy(t *testing.T) {+ t.Setenv("CLAUDE_CODE_TMPDIR", "")+ for _, provider := range []string{"claude", "codex", "pi"} {+ t.Run(provider, func(t *testing.T) {+ env := taskMulticaEnvironment(Task{}, provider, "", "", "", "", "", 0, 0, "/task/tmp")+ if env["TMPDIR"] != "/task/tmp" {+ t.Fatalf("TMPDIR = %q, want private task temp", env["TMPDIR"])+ }+ if runtime.GOOS == "windows" && provider == "claude" {+ for _, key := range []string{"TMP", "TEMP"} {+ if _, overridden := env[key]; overridden {+ t.Errorf("%s must inherit the host path for Git Bash's shared /tmp", key)+ }+ }+ if env["CLAUDE_CODE_TMPDIR"] != "/task/tmp" {+ t.Errorf("CLAUDE_CODE_TMPDIR = %q, want private task temp", env["CLAUDE_CODE_TMPDIR"])+ }+ } else {+ for _, key := range []string{"TMP", "TEMP"} {+ if env[key] != "/task/tmp" {+ t.Errorf("%s = %q, want existing private task temp", key, env[key])+ }+ }+ if _, overridden := env["CLAUDE_CODE_TMPDIR"]; overridden {+ t.Error("other platforms/providers must not override CLAUDE_CODE_TMPDIR")+ }+ }+ })+ }+}++func TestTaskMulticaEnvironmentRespectsClaudeTempOverride(t *testing.T) {+ t.Setenv("CLAUDE_CODE_TMPDIR", "/user/claude-temp")+ env := taskMulticaEnvironment(Task{}, "claude", "", "", "", "", "", 0, 0, "/task/tmp")+ if _, overridden := env["CLAUDE_CODE_TMPDIR"]; overridden {+ t.Fatal("inherited user CLAUDE_CODE_TMPDIR must remain authoritative")+ }+ t.Setenv("CLAUDE_CODE_TMPDIR", "")+ for _, key := range []string{"CLAUDE_CODE_TMPDIR", "claude_code_tmpdir"} {+ for _, value := range []string{"/custom/claude-temp", ""} {+ custom := map[string]string{key: value}+ env = taskMulticaEnvironment(Task{Agent: &AgentData{CustomEnv: custom}}, "claude", "", "", "", "", "", 0, 0, "/task/tmp")+ layerCustomEnvAndHermesHome(env, custom, "", nil)+ if env[key] != value {+ t.Fatalf("custom %s = %q, want user's %q", key, env[key], value)+ }+ for name := range env {+ if strings.EqualFold(name, key) && name != key {+ t.Errorf("duplicate Windows temp key %q conflicts with user's %q", name, key)+ }+ }+ }+ }+}+// 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/task_temp_git_bash_windows_test.go b/server/internal/daemon/task_temp_git_bash_windows_test.gonew file mode 100644index 0000000000..22d22f9b66--- /dev/null+++ b/server/internal/daemon/task_temp_git_bash_windows_test.go@@ -0,0 +1,192 @@+//go:build windows && gitbashintegration++package daemon++import (+ "bufio"+ "context"+ "io"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// This is an opt-in test of real Git for Windows, not an agent CLI or account.+// Run with -tags=gitbashintegration and MULTICA_TEST_GIT_BASH=<bash.exe>.+func TestWindowsClaudeGitBashTaskTempLifecycle(t *testing.T) {+ bash := os.Getenv("MULTICA_TEST_GIT_BASH")+ if bash == "" {+ t.Skip("set MULTICA_TEST_GIT_BASH to explicitly select Git for Windows")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ base := t.TempDir()+ hostTemp := filepath.Join(base, "user-temp")+ if err := os.Mkdir(hostTemp, 0o700); err != nil {+ t.Fatal(err)+ }+ t.Setenv("TMP", hostTemp)+ t.Setenv("TEMP", hostTemp)+ t.Setenv("CLAUDE_CODE_TMPDIR", "")++ newTask := func() (string, *os.File) {+ t.Helper()+ dir, err := os.MkdirTemp(base, execenv.TaskTempDirPrefix)+ if err != nil {+ t.Fatal(err)+ }+ lock, err := execenv.LockTaskTempDir(dir)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { execenv.ReleaseTaskTempLock(lock) })+ return dir, lock+ }++ start := func(dir string, orphan bool) (map[string]string, func()) {+ t.Helper()+ script := `printf 'PID='; /usr/bin/cat /proc/$$/winpid; printf '\n'+printf 'TMPDIR=%s\n' "$(/usr/bin/cygpath -w "$TMPDIR")"+printf 'TARGET=%s\n' "$(/usr/bin/cygpath -w /tmp)"+if file=$(/usr/bin/mktemp /tmp/multica-regression-XXXXXXXX); then+ /usr/bin/rm -- "$file"+ printf 'TMP_OK=yes\n'+else+ printf 'TMP_OK=no\n'+fi+printf 'READY\n'+IFS= read -r release+`+ if orphan {+ // The launcher's inherited stdin stays open in the Bash child.+ script = "exec 3<&0\n/usr/bin/bash --noprofile --norc -c '" + strings.ReplaceAll(script, "'", "'\"'\"'") + "' <&3 &\n"+ }+ input, feed, err := os.Pipe()+ if err != nil {+ t.Fatal(err)+ }+ output, sink, err := os.Pipe()+ if err != nil {+ t.Fatal(err)+ }+ stderr, err := os.CreateTemp(base, "bash-stderr-")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { feed.Close(); output.Close(); stderr.Close() })+ cmd := exec.CommandContext(ctx, bash, "--noprofile", "--norc", "-c", script)+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}+ cmd.Stdin, cmd.Stdout, cmd.Stderr = input, sink, stderr+ cmd.Env = os.Environ()+ for key, value := range taskMulticaEnvironment(Task{}, "claude", "", "", "", "", "", 0, 0, dir) {+ cmd.Env = append(cmd.Env, key+"="+value)+ }+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ input.Close()+ sink.Close()+ go func() { <-ctx.Done(); feed.Close(); output.Close() }()+ snapshot := map[string]string{}+ scanner := bufio.NewScanner(output)+ ready := false+ for scanner.Scan() {+ line := scanner.Text()+ if line == "READY" {+ ready = true+ break+ }+ if key, value, ok := strings.Cut(line, "="); ok {+ snapshot[key] = value+ }+ }+ if !ready {+ cmd.Process.Kill()+ cmd.Wait()+ t.Fatalf("Git Bash did not become ready: %v, snapshot=%v", scanner.Err(), snapshot)+ }+ pid, err := strconv.Atoi(snapshot["PID"])+ if err != nil {+ t.Fatal(err)+ }+ child, err := os.FindProcess(pid)+ if err != nil {+ t.Fatal(err)+ }+ if orphan {+ if err := cmd.Wait(); err != nil {+ t.Fatalf("Bash launcher did not exit successfully: %v", err)+ }+ }+ stopped := false+ stop := func() {+ if stopped {+ return+ }+ stopped = true+ io.WriteString(feed, "release\n")+ feed.Close()+ if orphan {+ child.Wait()+ } else {+ cmd.Wait()+ child.Release()+ }+ }+ t.Cleanup(stop)+ if !strings.EqualFold(snapshot["TMPDIR"], dir) {+ t.Fatalf("Bash TMPDIR=%q, want this task's %q", snapshot["TMPDIR"], dir)+ }+ return snapshot, stop+ }++ first, firstLock := newTask()+ initial, stopFirst := start(first, false)+ if !strings.EqualFold(initial["TARGET"], hostTemp) && !strings.EqualFold(initial["TARGET"], first) {+ t.Skipf("another MSYS process already owns /tmp at %q", initial["TARGET"])+ }+ second, secondLock := newTask()+ overlap, stopOrphan := start(second, true)+ stopFirst()+ execenv.ReleaseTaskTempLock(firstLock)+ if err := execenv.RemoveTaskTempDir(first); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(first); !os.IsNotExist(err) {+ t.Fatalf("completed task temp was not removed: %v", err)+ }+ if removed, _ := execenv.PruneTaskTempDirs(base, 0, time.Now(), nil); removed != 0 {+ t.Fatalf("GC removed %d dirs while the second task held its lock", removed)+ }+ third, thirdLock := newTask()+ afterDelete, stopThird := start(third, false)+ for name, snapshot := range map[string]map[string]string{"overlap": overlap, "after deletion with orphan alive": afterDelete} {+ if snapshot["TMP_OK"] != "yes" {+ t.Errorf("%s: /tmp unusable: %v", name, snapshot)+ }+ if !strings.EqualFold(snapshot["TARGET"], hostTemp) {+ t.Errorf("%s: /tmp target %q, want stable host temp %q", name, snapshot["TARGET"], hostTemp)+ }+ }+ stopThird()+ stopOrphan()+ for dir, lock := range map[string]*os.File{second: secondLock, third: thirdLock} {+ execenv.ReleaseTaskTempLock(lock)+ if err := execenv.RemoveTaskTempDir(dir); err != nil {+ t.Fatal(err)+ }+ }+ fourth, _ := newTask()+ sequential, stopFourth := start(fourth, false)+ if sequential["TMP_OK"] != "yes" || !strings.EqualFold(sequential["TARGET"], hostTemp) {+ t.Fatalf("sequential task after cleanup: %v", sequential)+ }+ stopFourth()+}