Skip to content

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

Go

fix(daemon): unblock local worktree removal behind pinned Windows handles (#11620)

Zeng, Bolingaeff017c8d0f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index aba4adba27..5af1870acb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -759,10 +759,10 @@ jobs:
- name: Test Windows execution-environment isolation
working-directory: server
- # Keep this job scoped to the runtime regression it exists to prove.
+ # Run the process-isolation and worktree cleanup regressions on Windows.
# The package's legacy OpenClaw HOME tests are not Windows-safe and are
# outside this PR; the normal backend job still runs the full package.
- run: go test ./internal/daemon/execenv -run '^TestPrepareIsolated_WindowsKillsDescendantBeforeRetry$' -count=1 -timeout=5m
+ run: go test ./internal/daemon/execenv -v -run '^(TestPrepareIsolated_WindowsKillsDescendantBeforeRetry$|TestRemoveLocalWorktreeDir)' -count=1 -timeout=5m
- name: Test Windows daemon local-skill discovery
working-directory: server
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdx
index a54a258628..c4ec2c9e9a 100644
--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx
@@ -281,7 +281,7 @@ Le tableau liste les variables que les runtimes personnalisés peuvent utiliser
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).
<Callout type="info">
-Les runtimes intégrés **Codex** et **Claude Code** réutilisent par défaut des processus chauds entre les tours suivants d'une même conversation. Lors des exécutions en pool chaud, les variables propres à chaque tâche (`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`) sont transmises au CLI `multica` du daemon via un fichier de surcharge privé par tour plutôt que figées dans l'environnement statique du processus persistant ; elles ne sont donc pas garanties dans l'environnement du processus fournisseur ni dans les scripts enfants arbitraires. Les commandes de profil de runtime personnalisé n'utilisent pas le pool chaud et continuent de recevoir toutes les variables directement dans l'environnement du processus. Définissez `MULTICA_WARM_POOL=0` sur le daemon si un workflow Codex ou Claude Code intégré nécessite l'ancien comportement direct par variables d'environnement.
+Les runtimes intégrés **Codex** et **Claude Code** réutilisent par défaut des processus chauds entre les tours suivants d'une même conversation. Lors des exécutions en pool chaud, les variables propres à chaque tâche (`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`) sont transmises au CLI `multica` du daemon via un fichier de surcharge privé par tour plutôt que figées dans l'environnement statique du processus persistant ; elles ne sont donc pas garanties dans l'environnement du processus fournisseur ni dans les scripts enfants arbitraires. Les exécutions dans un répertoire local en mode worktree et les commandes de profil de runtime personnalisé démarrent un nouveau processus qui reçoit toutes les variables de la tâche directement dans son environnement. Définissez `MULTICA_WARM_POOL=0` sur le daemon si un workflow Codex ou Claude Code intégré nécessite l'ancien comportement direct par variables d'environnement.
</Callout>
<Callout type="warning">
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index 3d83983304..5d6f8f4885 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -281,7 +281,7 @@ Codex のネイティブサブエージェントも既定でオフです。Multi
`MULTICA_TOKEN` を使ったリクエストの作成者はサーバーが決定し、タスクへのコメントなどの書き込みは、割り当てられたエージェントと実行中の作業に帰属します。認証情報の完全な紐付け、権限、帰属、最長 24 時間の有効期間、クリーンアップについては、[エージェント実行用の一時トークン](/auth-tokens#エージェント実行用の一時トークン)を参照してください。
<Callout type="info">
-組み込みの **Codex** および **Claude Code** ランタイムは、後続ターンのためにウォームプロセスプールを既定で有効化します。ウォームプール実行時は、ターンごとに変化する作業変数(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)が常駐プロセスの静的環境ではなく専用のターン単位オーバーレイファイル経由で `multica` CLI に渡されるため、プロバイダーのプロセス環境や任意の子スクリプトに現れることは保証されません。カスタムランタイムプロファイルのコマンドではウォームプールを使用しないため、引き続きすべての変数をプロセス環境から直接受け取ります。組み込みの Codex または Claude Code で従来の直接環境変数が必要な場合は、デーモンに `MULTICA_WARM_POOL=0` を設定してください。
+組み込みの **Codex** および **Claude Code** ランタイムは、後続ターンのためにウォームプロセスプールを既定で有効化します。ウォームプール実行時は、ターンごとに変化する作業変数(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)が常駐プロセスの静的環境ではなく専用のターン単位オーバーレイファイル経由で `multica` CLI に渡されるため、プロバイダーのプロセス環境や任意の子スクリプトに現れることは保証されません。ローカルディレクトリのワークツリーモードとカスタムランタイムプロファイルのコマンドでは、新しいプロセスを起動し、すべての作業変数をそのプロセス環境に直接渡します。組み込みの Codex または Claude Code で従来の直接環境変数が必要な場合は、デーモンに `MULTICA_WARM_POOL=0` を設定してください。
</Callout>
<Callout type="warning">
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index df30f060a1..01e6406d0f 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -281,7 +281,7 @@ Codex 기본 하위 에이전트도 기본적으로 꺼져 있습니다. Multica
`MULTICA_TOKEN`을 사용하는 요청의 작성자는 서버가 결정하며, 태스크 댓글 같은 쓰기는 할당된 에이전트와 실행 중인 작업에 귀속됩니다. 자격 증명의 전체 바인딩, 권한, 귀속, 최대 24시간의 유효 기간 및 정리 동작은 [에이전트 실행용 임시 토큰](/auth-tokens#에이전트-실행용-임시-토큰)을 참고하세요.
<Callout type="info">
-기본 제공 **Codex** 및 **Claude Code** 런타임은 후속 턴을 위해 기본적으로 웜 프로세스 풀을 재사용합니다. 웜 풀 실행 중에는 턴마다 바뀌는 작업 변수(`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`)가 상주 프로세스의 정적 환경이 아니라 비공개 턴별 오버레이 파일을 통해 `multica` CLI에 전달되므로, 프로바이더 프로세스 환경이나 임의의 자식 스크립트에 노출되는 것은 보장되지 않습니다. 사용자 지정 런타임 프로필 명령은 웜 풀을 사용하지 않으며 계속해서 프로세스 환경에서 모든 변수를 직접 받습니다. 기본 제공 Codex 또는 Claude Code에서 기존 직접 환경 변수가 필요하면 데몬에 `MULTICA_WARM_POOL=0`을 설정하세요.
+기본 제공 **Codex** 및 **Claude Code** 런타임은 후속 턴을 위해 기본적으로 웜 프로세스 풀을 재사용합니다. 웜 풀 실행 중에는 턴마다 바뀌는 작업 변수(`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`)가 상주 프로세스의 정적 환경이 아니라 비공개 턴별 오버레이 파일을 통해 `multica` CLI에 전달되므로, 프로바이더 프로세스 환경이나 임의의 자식 스크립트에 노출되는 것은 보장되지 않습니다. 로컬 디렉터리의 워크트리 모드 실행과 사용자 지정 런타임 프로필 명령은 새 프로세스를 시작하고 모든 작업 변수를 해당 프로세스 환경에서 직접 받습니다. 기본 제공 Codex 또는 Claude Code에서 기존 직접 환경 변수가 필요하면 데몬에 `MULTICA_WARM_POOL=0`을 설정하세요.
</Callout>
<Callout type="warning">
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index c18bef22ad..6a3daceb2d 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -281,7 +281,7 @@ The table lists the variables that custom runtimes can use today. It is intentio
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).
<Callout type="info">
-Built-in **Codex** and **Claude Code** runtimes reuse warm provider processes across follow-up turns by default. During warm-pooled runs, per-task variables that change every turn (`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`) are provided to the daemon's `multica` CLI through a private per-turn overlay file rather than set in the long-lived provider process's static environment, so they are not guaranteed to appear in the provider process environment or arbitrary child scripts. Custom runtime profile commands do not use the warm pool and continue receiving all variables directly in the process environment. Set `MULTICA_WARM_POOL=0` on the daemon if a built-in Codex or Claude Code workflow needs the legacy direct environment variables.
+Built-in **Codex** and **Claude Code** runtimes reuse warm provider processes across follow-up turns by default. During warm-pooled runs, per-task variables that change every turn (`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`) are provided to the daemon's `multica` CLI through a private per-turn overlay file rather than set in the long-lived provider process's static environment, so they are not guaranteed to appear in the provider process environment or arbitrary child scripts. Local directory runs in worktree mode and custom runtime profile commands start a fresh process and receive all task variables directly in its environment. Set `MULTICA_WARM_POOL=0` on the daemon if a built-in Codex or Claude Code workflow needs the legacy direct environment variables.
</Callout>
<Callout type="warning">
diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
index d818b15bd1..eb3b99b5e0 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
@@ -282,7 +282,7 @@ Codex 原生子 AI 代理同樣預設關閉:父執行緒結束時,Multica
使用 `MULTICA_TOKEN` 發起請求時,作者身份由服務端決定;任務評論等寫入操作會歸屬到被指派的 AI 代理和當前 task。令牌的完整繫結關係、權限、歸屬方式、最長 24 小時的有效期和清理規則見[AI 代理執行的臨時令牌](/auth-tokens#ai-代理執行的臨時令牌)。
<Callout type="info">
-內建的 **Codex** 與 **Claude Code** 執行時預設啟用工作階段程序池以複用後續輪次程序。在程序池模式下,每輪都會變動的任務變數(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)改由守護程序透過私有的單輪覆蓋檔案提供給 `multica` CLI,不再寫入常駐程序的靜態環境變數,因此不保證出現在 provider 程序環境或任意子指令碼中。自定義執行時配置命令不啟用程序池,仍直接在程序環境中接收全部變數。如果內建 Codex 或 Claude Code 的工作流需要舊的直接環境變數行為,可在守護程序環境中設定 `MULTICA_WARM_POOL=0`。
+內建的 **Codex** 與 **Claude Code** 執行時預設啟用工作階段程序池以複用後續輪次程序。在程序池模式下,每輪都會變動的任務變數(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)改由守護程序透過私有的單輪覆蓋檔案提供給 `multica` CLI,不再寫入常駐程序的靜態環境變數,因此不保證出現在 provider 程序環境或任意子指令碼中。以 worktree 模式執行的本地目錄任務和自定義執行時配置命令會啟動新程序,並直接在程序環境中接收全部任務變數。如果內建 Codex 或 Claude Code 的工作流需要舊的直接環境變數行為,可在守護程序環境中設定 `MULTICA_WARM_POOL=0`。
</Callout>
<Callout type="warning">
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index 6f10ee0399..2b13470e70 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -282,7 +282,7 @@ Codex 原生子智能体同样默认关闭:父线程结束时,Multica 就把
使用 `MULTICA_TOKEN` 发起请求时,作者身份由服务端决定;任务评论等写入操作会归属到被指派的智能体和当前 task。令牌的完整绑定关系、权限、归属方式、最长 24 小时的有效期和清理规则见[智能体执行的临时令牌](/auth-tokens#智能体执行的临时令牌)。
<Callout type="info">
-内置的 **Codex** 和 **Claude Code** 运行时默认开启会话进程池以复用跟进轮进程。在进程池模式下,每轮都会变化的任务变量(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)改由守护进程通过私有的单轮覆盖文件提供给 `multica` CLI,不再写入常驻进程的静态环境变量,因此不保证出现在 provider 进程环境或任意子脚本中。自定义运行时配置命令不启用进程池,仍直接在进程环境中接收全部变量。如果内置 Codex 或 Claude Code 的工作流需要旧的直接环境变量行为,可在守护进程环境中设置 `MULTICA_WARM_POOL=0`。
+内置的 **Codex** 和 **Claude Code** 运行时默认开启会话进程池以复用跟进轮进程。在进程池模式下,每轮都会变化的任务变量(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)改由守护进程通过私有的单轮覆盖文件提供给 `multica` CLI,不再写入常驻进程的静态环境变量,因此不保证出现在 provider 进程环境或任意子脚本中。以 worktree 模式运行的本地目录任务和自定义运行时配置命令会启动新进程,并直接在进程环境中接收全部任务变量。如果内置 Codex 或 Claude Code 的工作流需要旧的直接环境变量行为,可在守护进程环境中设置 `MULTICA_WARM_POOL=0`。
</Callout>
<Callout type="warning">
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index c0fb8bf9a7..e9e317b5a0 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9309,7 +9309,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
agentEnv["MULTICA_DSH_SESSION_ROOT"] = dshSessionRoot
agentEnv["DSH_TELEMETRY_DISABLED"] = "1"
}
- taskWarmPool := selectTaskWarmPool(d.warmPool, usesCustomProfileCommand)
+ taskWarmPool := selectTaskWarmPool(d.warmPool, usesCustomProfileCommand, env.LocalWorktree != nil)
codexShellEnv := agentEnv
if provider == "codex" && taskWarmPool != nil {
// Ensure Codex's managed shell_environment_policy allowlist permits
@@ -11766,12 +11766,23 @@ func codexShellAuthorizedCustomEnvNames(customEnv map[string]string) []string {
}
// selectTaskWarmPool returns the daemon's warm session pool only for built-in
-// runtimes. Custom runtime profile commands (wrappers, version-pinned shims,
-// sandbox launchers) always launch cold so startup wrappers can read per-task
-// variables such as MULTICA_TOKEN and MULTICA_TASK_ID directly from the process
-// environment.
-func selectTaskWarmPool(pool *agent.WarmSessionPool, usesCustomProfileCommand bool) *agent.WarmSessionPool {
- if usesCustomProfileCommand {
+// runtimes on durable workdirs. Custom runtime profile commands (wrappers,
+// version-pinned shims, sandbox launchers) always launch cold so startup
+// wrappers can read per-task variables such as MULTICA_TOKEN and
+// MULTICA_TASK_ID directly from the process environment.
+//
+// Worktree-mode local_directory tasks never pool either, and not only because
+// the reuse is impossible: every turn prepares a fresh env root, so the
+// worktree path in the warm fingerprint never matches a continuation turn and
+// the parked process would never be re-acquired anyway. What the parking does
+// do is keep the provider process alive — app-server and MCP subprocesses
+// included — with its working directory inside the worktree that Finalize is
+// about to remove. Unix tolerates removing a tree underneath a process;
+// Windows does not: the unlink of the process's cwd fails with a sharing
+// violation, `git worktree remove --force` errors out, the removal fallback
+// fails too, and the task is failed after its delivery already succeeded.
+func selectTaskWarmPool(pool *agent.WarmSessionPool, usesCustomProfileCommand, worktreeMode bool) *agent.WarmSessionPool {
+ if usesCustomProfileCommand || worktreeMode {
return nil
}
return pool
diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.go
index 0d65cf8dad..b6de56a407 100644
--- a/server/internal/daemon/execenv/local_worktree.go
+++ b/server/internal/daemon/execenv/local_worktree.go
@@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strconv"
"strings"
"time"
@@ -1071,23 +1072,60 @@ func worktreeIsDirty(worktreePath string) (bool, error) {
// removeLocalWorktreeDir unregisters the worktree from the user's repo and
// deletes its directory. The branch is deliberately left alone — it is the
// task's deliverable.
+//
+// The removal is retried on a short backoff because on Windows a directory
+// that is any process's working directory cannot be deleted, and the handles
+// that pin it — the provider's own shell children finishing late, an antivirus
+// or indexer scan of the tree — close asynchronously after the processes are
+// already gone. Failing the whole task the moment the first unlink hits a
+// sharing violation misreports a delivery that is already committed (the
+// caller fails the task precisely because removal could not be confirmed), so
+// the retry buys the platform's lag, not unlimited patience: the budget stays
+// small enough that a genuinely leaked process still fails the task.
func removeLocalWorktreeDir(gitRoot, worktreePath string, logger *slog.Logger) error {
- var removeErr error
- if out, err := runGit(gitRoot, "worktree", "remove", "--force", worktreePath); err != nil {
- removeErr = err
+ for attempt := 0; ; attempt++ {
+ removeErr := removeLocalWorktreeDirOnce(gitRoot, worktreePath, logger)
+ if removeErr == nil || runtime.GOOS != "windows" || attempt >= worktreeRemoveMaxAttempts-1 {
+ return removeErr
+ }
+ backoff := time.Duration(250*(1<<attempt)) * time.Millisecond
if logger != nil {
- logger.Warn("execenv: git worktree remove failed; pruning registration",
- "path", worktreePath, "output", out, "error", err)
- }
- // Fall back to deleting the directory ourselves and dropping the now
- // dangling registration, so the user's repo isn't left listing a
- // worktree that no longer exists.
- if rmErr := os.RemoveAll(worktreePath); rmErr != nil {
- removeErr = errors.Join(removeErr, rmErr)
- if logger != nil {
- logger.Warn("execenv: remove worktree directory failed", "path", worktreePath, "error", rmErr)
- }
+ logger.Info("execenv: worktree removal blocked (transient lock?); retrying",
+ "path", worktreePath, "attempt", attempt+1, "backoff", backoff.String(), "error", removeErr)
}
+ time.Sleep(backoff)
+ }
+}
+
+// worktreeRemoveMaxAttempts caps the backoff at 3.75 seconds. Git commands
+// also have their own timeout.
+const worktreeRemoveMaxAttempts = 5
+
+func removeLocalWorktreeDirOnce(gitRoot, worktreePath string, logger *slog.Logger) error {
+ out, gitErr := runGit(gitRoot, "worktree", "remove", "--force", worktreePath)
+ if gitErr == nil {
+ // Git for Windows can unregister a worktree and exit successfully
+ // while leaving directory junctions behind (#7548).
+ if _, statErr := os.Lstat(worktreePath); errors.Is(statErr, os.ErrNotExist) {
+ return nil
+ } else if statErr != nil {
+ return fmt.Errorf("confirm worktree removal: %w", statErr)
+ } else if runtime.GOOS != "windows" {
+ return errors.New("worktree directory still exists after git removal reported success")
+ }
+ } else if logger != nil {
+ logger.Warn("execenv: git worktree remove failed; pruning registration",
+ "path", worktreePath, "output", out, "error", gitErr)
+ }
+
+ removeErr := gitErr
+ if rmErr := os.RemoveAll(worktreePath); rmErr != nil {
+ removeErr = errors.Join(removeErr, rmErr)
+ if logger != nil {
+ logger.Warn("execenv: remove worktree directory failed", "path", worktreePath, "error", rmErr)
+ }
+ }
+ if gitErr != nil {
if out, pruneErr := runGit(gitRoot, "worktree", "prune"); pruneErr != nil && logger != nil {
logger.Warn("execenv: git worktree prune failed", "output", out, "error", pruneErr)
}
@@ -1102,7 +1140,7 @@ func removeLocalWorktreeDir(gitRoot, worktreePath string, logger *slog.Logger) e
if removeErr != nil {
return fmt.Errorf("worktree directory still exists after removal fallback: %w", removeErr)
}
- return errors.New("worktree directory still exists after git removal reported success")
+ return errors.New("worktree directory still exists after removal fallback")
}
// deleteBranch drops a task branch that carries nothing worth keeping — an
diff --git a/server/internal/daemon/execenv/local_worktree_remove_windows_test.go b/server/internal/daemon/execenv/local_worktree_remove_windows_test.go
new file mode 100644
index 0000000000..918ce06668
--- /dev/null
+++ b/server/internal/daemon/execenv/local_worktree_remove_windows_test.go
@@ -0,0 +1,138 @@
+//go:build windows
+
+package execenv
+
+import (
+ "bufio"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// startWorktreeHolder waits for a live process to take the worktree as its
+// working directory, the same pin a parked provider leaves on Windows.
+func startWorktreeHolder(t *testing.T, worktreePath string) func() {
+ t.Helper()
+ cmd := exec.CommandContext(t.Context(), "ping.exe", "-n", "120", "127.0.0.1")
+ cmd.Dir = worktreePath
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ t.Fatalf("open holder stdout: %v", err)
+ }
+ if err := cmd.Start(); err != nil {
+ t.Fatalf("start pinned-cwd holder: %v", err)
+ }
+ release := sync.OnceFunc(func() {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ })
+ t.Cleanup(release)
+ if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
+ t.Fatalf("wait for pinned-cwd holder: %v", err)
+ }
+ return release
+}
+
+func TestRemoveLocalWorktreeDirRetriesUntilThePinningProcessExits(t *testing.T) {
+ repo := newTestRepo(t)
+ worktreePath := filepath.Join(t.TempDir(), "worktree")
+ gitRun(t, repo, "worktree", "add", "-b", "pin-test", worktreePath)
+ release := startWorktreeHolder(t, worktreePath)
+
+ // Release the pin between attempts, after the first removal fails.
+ retried := false
+ logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
+ ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
+ if attr.Key == "backoff" {
+ retried = true
+ release()
+ }
+ return attr
+ },
+ }))
+ if err := removeLocalWorktreeDir(repo, worktreePath, logger); err != nil {
+ t.Fatalf("removeLocalWorktreeDir with a released pin: %v", err)
+ }
+ if !retried {
+ t.Fatal("the pinned first removal should have required a retry")
+ }
+ assertRemovedWorktree(t, repo, worktreePath, "pin-test")
+}
+
+func TestRemoveLocalWorktreeDirFailsWhenThePinNeverLifts(t *testing.T) {
+ repo := newTestRepo(t)
+ worktreePath := filepath.Join(t.TempDir(), "worktree")
+ gitRun(t, repo, "worktree", "add", "-b", "pin-stuck-test", worktreePath)
+ startWorktreeHolder(t, worktreePath)
+
+ started := time.Now()
+ err := removeLocalWorktreeDir(repo, worktreePath, worktreeTestLogger())
+ if err == nil {
+ t.Fatal("removeLocalWorktreeDir succeeded under a permanent pin; want a bounded failure")
+ }
+ if elapsed := time.Since(started); elapsed > 30*time.Second {
+ t.Fatalf("removal took %s; want a small bounded budget", elapsed)
+ }
+ if _, statErr := os.Lstat(worktreePath); statErr != nil {
+ t.Fatalf("worktree path should survive the failed removal: %v", statErr)
+ }
+ if got := err.Error(); !strings.Contains(got, "still exists") {
+ t.Fatalf("error does not describe the surviving worktree: %q", got)
+ }
+ gitRun(t, repo, "show-ref", "--verify", "refs/heads/pin-stuck-test")
+}
+
+func TestRemoveLocalWorktreeDirCleansUpJunctionOnFirstAttempt(t *testing.T) {
+ repo := newTestRepo(t)
+ worktreePath := filepath.Join(t.TempDir(), "worktree")
+ gitRun(t, repo, "worktree", "add", "-b", "junction-test", worktreePath)
+
+ scopeDir := filepath.Join(worktreePath, "node_modules", "@scope")
+ if err := os.MkdirAll(scopeDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ packageDir := filepath.Join(worktreePath, "packages", "pkg")
+ if err := os.MkdirAll(packageDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // npm workspace links point inside the worktree. An external target
+ // also checks that cleanup does not follow directory junctions.
+ externalPackage := t.TempDir()
+ marker := filepath.Join(externalPackage, "package.json")
+ if err := os.WriteFile(marker, []byte("{}"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ for name, target := range map[string]string{"pkg": packageDir, "external": externalPackage} {
+ junction := filepath.Join(scopeDir, name)
+ if out, err := exec.Command("cmd", "/d", "/c", "mklink", "/J", junction, target).CombinedOutput(); err != nil {
+ t.Fatalf("mklink /J %s: %s: %v", name, out, err)
+ }
+ }
+ if err := removeLocalWorktreeDirOnce(repo, worktreePath, worktreeTestLogger()); err != nil {
+ t.Fatalf("remove worktree with a junction on the first attempt: %v", err)
+ }
+ assertRemovedWorktree(t, repo, worktreePath, "junction-test")
+ if body, err := os.ReadFile(marker); err != nil || string(body) != "{}" {
+ t.Fatalf("junction target was changed: contents %q, error %v", body, err)
+ }
+}
+
+func assertRemovedWorktree(t *testing.T, repo, worktreePath, branch string) {
+ t.Helper()
+ if _, err := os.Lstat(worktreePath); !os.IsNotExist(err) {
+ t.Fatalf("worktree path still present after successful removal: %v", err)
+ }
+ ref := "refs/heads/" + branch
+ for line := range strings.Lines(gitRun(t, repo, "worktree", "list", "--porcelain")) {
+ if strings.TrimSpace(line) == "branch "+ref {
+ t.Fatalf("worktree for %s is still registered", branch)
+ }
+ }
+ gitRun(t, repo, "show-ref", "--verify", ref)
+}
diff --git a/server/internal/daemon/warm_pool_test.go b/server/internal/daemon/warm_pool_test.go
index 2591155de2..ae1340d418 100644
--- a/server/internal/daemon/warm_pool_test.go
+++ b/server/internal/daemon/warm_pool_test.go
@@ -16,13 +16,16 @@ func TestSelectTaskWarmPoolDisablesCustomProfileCommands(t *testing.T) {
})
defer pool.Close()
- if got := selectTaskWarmPool(pool, false); got != pool {
- t.Fatalf("selectTaskWarmPool(pool, false) = %v, want %v", got, pool)
+ if got := selectTaskWarmPool(pool, false, false); got != pool {
+ t.Fatalf("selectTaskWarmPool(pool, false, false) = %v, want %v", got, pool)
}
- if got := selectTaskWarmPool(pool, true); got != nil {
- t.Fatalf("selectTaskWarmPool(pool, true) = %v, want nil for custom profile command", got)
+ if got := selectTaskWarmPool(pool, true, false); got != nil {
+ t.Fatalf("selectTaskWarmPool(pool, true, false) = %v, want nil for custom profile command", got)
}
- if got := selectTaskWarmPool(nil, false); got != nil {
- t.Fatalf("selectTaskWarmPool(nil, false) = %v, want nil", got)
+ if got := selectTaskWarmPool(pool, false, true); got != nil {
+ t.Fatalf("selectTaskWarmPool(pool, false, true) = %v, want nil for worktree mode", got)
+ }
+ if got := selectTaskWarmPool(nil, false, false); got != nil {
+ t.Fatalf("selectTaskWarmPool(nil, false, false) = %v, want nil", got)
}
}