Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(git): retry prune/detach in switch_branch when branch held by worktree

yangzequ4ce15d40474f
diff --git a/jiuwenswarm/server/runtime/session/project_git.py b/jiuwenswarm/server/runtime/session/project_git.py
index 0486849be0..ff13974700 100644
--- a/jiuwenswarm/server/runtime/session/project_git.py
+++ b/jiuwenswarm/server/runtime/session/project_git.py
@@ -337,6 +337,53 @@ def _truncate(s: str) -> str:
return (s or "")[:_GIT_OUTPUT_TRUNCATE]
+def _is_branch_held_by_worktree(stderr: str) -> bool:
+ """检测 git stderr 是否表示目标分支被 worktree 占用。
+
+ stale(worktree 目录已删但 ``.git/worktrees`` 管理条目残留)与 live(团队仍在运行)
+ 两种情形 stderr 相同,需配合 ``git worktree prune`` + 重试来区分。
+ """
+ s = (stderr or "").lower()
+ return "already used by worktree" in s or "already checked out" in s
+
+
+def _find_worktrees_holding_branch(
+ repo_root: str,
+ branch: str,
+) -> list[str]:
+ """返回占用目标分支的 worktree 工作目录路径(不含主仓库)。
+
+ 通过 ``git worktree list --porcelain`` 解析 porcelain 输出,
+ branch 字段为 ``refs/heads/<branch>`` 的 worktree 即为占用者。
+ 主仓库本身(worktree 列表第一项)被显式排除,避免误 detach 用户
+ 当前工作区。命令失败或解析异常时返回空列表,调用方回退到错误
+ 分类逻辑提示用户手动处理。
+ """
+ try:
+ cp = _run_git(
+ ["worktree", "list", "--porcelain"],
+ cwd=repo_root,
+ )
+ except FileNotFoundError:
+ return []
+ if cp.returncode != 0:
+ return []
+ target_ref = f"refs/heads/{branch}"
+ real_root = os.path.realpath(repo_root)
+ worktrees: list[str] = []
+ wt_path: str | None = None
+ for line in cp.stdout.splitlines():
+ if line.startswith("worktree "):
+ wt_path = line[len("worktree "):].strip()
+ elif line.startswith("branch ") and wt_path is not None:
+ ref = line[len("branch "):].strip()
+ if ref == target_ref:
+ if os.path.realpath(wt_path) != real_root:
+ worktrees.append(wt_path)
+ wt_path = None
+ return worktrees
+
+
def _make_error(
code: str,
message: str,
@@ -1131,16 +1178,169 @@ class ProjectGitService:
error=err,
)
if cp_co.returncode != 0:
+ # Stale worktree admin entries (e.g. a dissolved team whose
+ # worktree dirs were rmtree'd without `git worktree remove`)
+ # make `git checkout <branch>` fail with "already used by
+ # worktree" even though the worktree no longer exists. Prune
+ # stale admin and retry once; if it still fails the worktree
+ # is live (a team is still running) and the user must dissolve
+ # it first.
+ prune_co = None
+ if _is_branch_held_by_worktree(cp_co.stderr):
+ logger.info(
+ "[ProjectGit] checkout %s blocked by worktree; "
+ "pruning stale admin and retrying (cwd=%s)",
+ branch, project.project_dir,
+ )
+ try:
+ prune_co = _run_git(
+ ["-c", "safe.directory=*", "worktree", "prune"],
+ cwd=project.project_dir,
+ )
+ cp_co = _run_git(["checkout", branch], cwd=project.project_dir)
+ except FileNotFoundError:
+ err = _file_not_found_error(
+ project, project.project_dir,
+ branch=previous_branch,
+ command=f"git checkout {branch}",
+ )
+ return GitOperationResult(
+ success=False,
+ repo_status=pre_status,
+ previous_branch=previous_branch,
+ error=err,
+ )
+ except subprocess.TimeoutExpired:
+ err = _make_repo_error(
+ "GIT_COMMAND_TIMEOUT",
+ "git command timed out",
+ project,
+ command=f"git checkout {branch}",
+ branch=previous_branch,
+ retryable=True,
+ )
+ return GitOperationResult(
+ success=False,
+ repo_status=pre_status,
+ previous_branch=previous_branch,
+ error=err,
+ )
+ if cp_co.returncode == 0:
+ post_status = _git_to_repo_status(project, persist=True)
+ return GitOperationResult(
+ success=True,
+ repo_status=post_status,
+ previous_branch=previous_branch,
+ )
+ # LIVE worktree(团队未解散)占用目标分支:对占用者执行
+ # ``git checkout --detach`` 释放分支 ref 后重试 checkout。
+ # 工作树内容不变,agent 之后可重新 checkout 该分支继续工作。
+ detach_failed: list[str] = []
+ detach_attempted = False
+ if _is_branch_held_by_worktree(cp_co.stderr):
+ holding = _find_worktrees_holding_branch(
+ project.project_dir, branch,
+ )
+ if holding:
+ detach_attempted = True
+ logger.info(
+ "[ProjectGit] checkout %s blocked by live worktree(s) "
+ "%s; detaching HEAD to release branch (cwd=%s)",
+ branch, holding, project.project_dir,
+ )
+ for wt_path in holding:
+ try:
+ wt_co = _run_git(
+ ["checkout", "--detach"], cwd=wt_path,
+ )
+ if wt_co.returncode != 0:
+ detach_failed.append(
+ f"{wt_path}: rc={wt_co.returncode}, "
+ f"stderr={(wt_co.stderr or '')[:200]}"
+ )
+ except FileNotFoundError:
+ detach_failed.append(
+ f"{wt_path}: git executable not found"
+ )
+ except subprocess.TimeoutExpired:
+ detach_failed.append(f"{wt_path}: timeout")
+ if not detach_failed:
+ try:
+ cp_co = _run_git(
+ ["checkout", branch],
+ cwd=project.project_dir,
+ )
+ except FileNotFoundError:
+ err = _file_not_found_error(
+ project, project.project_dir,
+ branch=previous_branch,
+ command=f"git checkout {branch}",
+ )
+ return GitOperationResult(
+ success=False,
+ repo_status=pre_status,
+ previous_branch=previous_branch,
+ error=err,
+ )
+ except subprocess.TimeoutExpired:
+ err = _make_repo_error(
+ "GIT_COMMAND_TIMEOUT",
+ "git command timed out",
+ project,
+ command=f"git checkout {branch}",
+ branch=previous_branch,
+ retryable=True,
+ )
+ return GitOperationResult(
+ success=False,
+ repo_status=pre_status,
+ previous_branch=previous_branch,
+ error=err,
+ )
+ if cp_co.returncode == 0:
+ logger.info(
+ "[ProjectGit] checkout %s succeeded after "
+ "detaching %d worktree(s)",
+ branch, len(holding),
+ )
+ post_status = _git_to_repo_status(project, persist=True)
+ return GitOperationResult(
+ success=True,
+ repo_status=post_status,
+ previous_branch=previous_branch,
+ )
+ held = _is_branch_held_by_worktree(cp_co.stderr)
+ if held and prune_co is not None and prune_co.returncode != 0:
+ msg = "清理 stale worktree 失败,无法切换分支"
+ hint = ("git worktree prune 执行失败(rc={rc}): {stderr}。"
+ "请手动在仓库目录执行: git -c safe.directory=* worktree prune").format(
+ rc=prune_co.returncode, stderr=(prune_co.stderr or "")[:300])
+ elif held and detach_attempted and detach_failed:
+ msg = "自动 detach 占用分支的 worktree 失败,无法切换分支"
+ hint = ("对占用 {branch} 的 worktree 执行 git checkout --detach 失败:\n"
+ "{failures}\n请手动 detach 这些 worktree 或解散团队后重试").format(
+ branch=branch, failures="\n".join(detach_failed[:5]))
+ elif held and detach_attempted:
+ msg = "分支仍被 worktree 占用"
+ hint = ("已尝试 detach 占用 {branch} 的 worktree 并重试,但分支仍被占用。"
+ "请检查 git worktree list,或解散团队后重试").format(branch=branch)
+ elif held:
+ msg = "分支被其他 worktree 占用"
+ hint = "请先解散占用该分支的团队或移除对应 worktree 后重试"
+ elif "would be overwritten" in cp_co.stderr:
+ msg = "切换分支失败:本地改动阻止切换"
+ hint = "请先提交或 stash 改动后重试"
+ else:
+ msg = "git command failed"
+ hint = "请先提交或 stash 改动后重试"
err = _make_repo_error(
- "GIT_COMMAND_FAILED",
- "切换分支失败:本地改动阻止切换" if "would be overwritten" in cp_co.stderr else "git command failed",
- project,
+ "GIT_COMMAND_FAILED", msg, project,
command=f"git checkout {branch}",
exit_code=cp_co.returncode,
stdout=cp_co.stdout,
stderr=cp_co.stderr,
branch=previous_branch,
- hint="请先提交或 stash 改动后重试",
+ hint=hint,
retryable=True,
)
return GitOperationResult(