Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

prune --apply 逐个回收工作树,失败不再中止整轮

longmeidao334b78e38b23
diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.md
index 43a3c09c8..d651bff6a 100644
--- a/.claude/skills/peach-worktree/SKILL.md
+++ b/.claude/skills/peach-worktree/SKILL.md
@@ -79,6 +79,11 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成
手工清到 3 个,两天后长回 74 个、占 868 MB。脏的一律拒收并单独列出:分支已合入不等于工作区
里没东西,实测就有工作树的分支早已并入 master、里面却躺着一份成形的未提交改动。
+一个工作树失败不影响其它工作树。Windows 上目录句柄常被别的进程占着,`git worktree remove`
+报 Permission denied,而 git 已经把文件删光、注册也摘掉了:这种只按 `residue` 列出来等人清,
+分支照样删;注册还在才进 `failed`,分支保留。2026-09-01 之前是一失败就中止整轮,结果连跑
+5 次才摘完 5 个工作树、分支一条没删。看完 JSON 里的 `residue` 再手工 `rmdir` 那几个空目录。
+
`Desktop\peach` 顶层只放 ADR-0017 定义的四个运行时目录加一个 `attic/`:
peach-app peach-data peach-sync peach-worktrees attic
diff --git a/scripts/agent_worktree.py b/scripts/agent_worktree.py
index cc9dfa1a3..5d159f6c8 100644
--- a/scripts/agent_worktree.py
+++ b/scripts/agent_worktree.py
@@ -111,6 +111,40 @@ def integrate(repo: Path, worker_branch: str, target_branch: str = "master") ->
}
+def _worktree_entries(main: Path) -> list[dict[str, str]]:
+ entries: list[dict[str, str]] = []
+ entry: dict[str, str] = {}
+ for line in _lines(_git(main, "worktree", "list", "--porcelain")):
+ if line.startswith("worktree "):
+ entry = {"path": line[len("worktree "):]}
+ entries.append(entry)
+ elif line.startswith("branch "):
+ entry["branch"] = line[len("branch "):].replace("refs/heads/", "")
+ return entries
+
+
+def _reclaim(main: Path, path: Path, branch: str) -> tuple[str, dict[str, str]]:
+ """回收单个工作树,把结果归到 reclaimed / residue / failed 之一。
+
+ 2026-09-01 实测:Windows 上 `.claude/worktrees/*` 的目录句柄被别的进程占着,
+ `git worktree remove` 报 Permission denied,而 git 已经把文件删光、注册也摘掉了,
+ 只剩一个空目录。这一步以前直接抛错中止整轮,于是分支一条没删、后面的工作树一个没碰,
+ 要靠人反复重跑 prune,跑一次才推进一个。所以失败只波及它自己:注册已经摘掉的照常删
+ 分支,残留目录单独列出来交给人清;注册还在才算真没回收成。
+ """
+ removal = _git(main, "worktree", "remove", str(path), check=False)
+ why = (removal.stderr or removal.stdout).strip()
+ registered = {Path(item["path"]).resolve() for item in _worktree_entries(main)}
+ if removal.returncode and path.resolve() in registered:
+ return "failed", {"path": str(path), "branch": branch, "why": why}
+ if branch:
+ _git(main, "branch", "-d", branch, check=False)
+ if removal.returncode:
+ return "residue", {"path": str(path), "branch": branch,
+ "why": "目录残留,待人工清理:" + why}
+ return "reclaimed", {"path": str(path), "branch": branch}
+
+
def prune(repo: Path, target_branch: str = "master", *,
apply: bool = False) -> dict[str, object]:
"""回收分支已并入 target、且工作区干净的隔离工作树。
@@ -121,6 +155,9 @@ def prune(repo: Path, target_branch: str = "master", *,
默认只报告不动手。回收不可逆,而「分支已合入」并不等于「工作区里没有东西」:
实测就有工作树的分支早已并入 master,里面却躺着一份成形的未提交改动。所以脏的
一律拒收并单独列出,交给人看,不给 `--force` 这个口子。
+
+ 单个工作树回收失败不影响其它工作树:结果分成 reclaimed / residue / failed /
+ dirty / kept 五组,整轮照样 ok。理由见 `_reclaim`。
"""
main = _main_worktree(repo)
merged = {line.strip().lstrip("+* ") for line in
@@ -130,18 +167,12 @@ def prune(repo: Path, target_branch: str = "master", *,
here = repo.resolve()
reclaimed: list[str] = []
+ residue: list[dict[str, str]] = []
+ failed: list[dict[str, str]] = []
dirty: list[dict[str, str]] = []
kept: list[dict[str, str]] = []
- entry: dict[str, str] = {}
- entries: list[dict[str, str]] = []
- for line in _lines(_git(main, "worktree", "list", "--porcelain")):
- if line.startswith("worktree "):
- entry = {"path": line[len("worktree "):]}
- entries.append(entry)
- elif line.startswith("branch "):
- entry["branch"] = line[len("branch "):].replace("refs/heads/", "")
- for item in entries:
+ for item in _worktree_entries(main):
path = Path(item["path"])
branch = item.get("branch", "")
if path.resolve() == main.resolve() or path.resolve() == here:
@@ -153,16 +184,24 @@ def prune(repo: Path, target_branch: str = "master", *,
check=False).stdout.strip():
dirty.append({"path": str(path), "branch": branch, "why": "工作区有未提交改动"})
continue
- if apply:
- _git(main, "worktree", "remove", str(path))
- _git(main, "branch", "-d", branch, check=False)
- reclaimed.append(str(path))
+ if not apply:
+ reclaimed.append(str(path))
+ continue
+ group, record = _reclaim(main, path, branch)
+ if group == "reclaimed":
+ reclaimed.append(str(path))
+ elif group == "residue":
+ residue.append(record)
+ else:
+ failed.append(record)
return {
"ok": True,
"action": "prune",
"applied": apply,
"reclaimed": sorted(reclaimed),
+ "residue": residue,
+ "failed": failed,
"dirty": dirty,
"kept": kept,
}
diff --git a/tests/test_agent_worktree.py b/tests/test_agent_worktree.py
index 5a6614739..f0efd8567 100644
--- a/tests/test_agent_worktree.py
+++ b/tests/test_agent_worktree.py
@@ -2,10 +2,38 @@ import subprocess
import tempfile
import unittest
from pathlib import Path
+from unittest import mock
+from scripts import agent_worktree
from scripts.agent_worktree import WorkspaceError, _git, create, integrate, prune, ready
+class StuckRemoval:
+ """复刻 2026-09-01 Windows 上的实测:目录句柄被别的进程占着,
+ `git worktree remove` 报 Permission denied。
+
+ `residue`:git 已经把文件删光、注册也摘掉了,只剩一个空目录删不掉。
+ `stuck`:注册还在,工作树整个没摘掉。
+ """
+
+ def __init__(self, real, modes: dict[Path, str]):
+ self.real = real
+ self.modes = {path.resolve(): mode for path, mode in modes.items()}
+
+ def __call__(self, repo, *args, **kwargs):
+ mode = None
+ if args[:2] == ("worktree", "remove"):
+ mode = self.modes.get(Path(args[-1]).resolve())
+ if mode is None:
+ return self.real(repo, *args, **kwargs)
+ path = Path(args[-1])
+ if mode == "residue":
+ self.real(repo, *args, check=False)
+ path.mkdir(parents=True, exist_ok=True)
+ return subprocess.CompletedProcess(
+ list(args), 1, "", f"fatal: failed to delete '{path}': Permission denied")
+
+
def commit(repo: Path, message: str) -> None:
_git(repo, "add", "tracked.txt", "worker.txt")
_git(repo, "commit", "-m", message)
@@ -122,3 +150,38 @@ class PruneTests(AgentWorktreeTests):
report = prune(self.repo)
listed = report["reclaimed"] + [row["path"] for row in report["dirty"] + report["kept"]]
self.assertNotIn(str(self.repo), listed, "主检出不能出现在回收清单里")
+
+ def test_a_directory_that_will_not_delete_still_loses_its_branch(self):
+ """注册已经摘掉、只剩目录删不掉时,分支照删,目录列进 residue 交给人清。
+
+ 2026-09-01 实测:连跑 5 次 prune --apply 才把 5 个工作树摘完,5 条分支一条没删,
+ 最后是手工 `git branch -d` 收的尾——因为 remove 一失败就抛错中止了整轮。
+ """
+ worker = self._integrated("stuck-handle")
+ with mock.patch.object(agent_worktree, "_git",
+ StuckRemoval(agent_worktree._git, {worker: "residue"})):
+ report = prune(self.repo, apply=True)
+ self.assertTrue(report["ok"], "一个目录删不掉不该把整轮判成失败")
+ self.assertTrue(worker.is_dir(), "空目录还在原地")
+ self.assertEqual([row["path"] for row in report["residue"]], [str(worker)])
+ self.assertEqual(report["reclaimed"], [])
+ self.assertNotIn("stuck-handle",
+ _git(self.repo, "branch", "--list", "agent/codex/stuck-handle").stdout,
+ "注册已经摘掉了,分支就该跟着删")
+
+ def test_one_stuck_worktree_does_not_block_the_others(self):
+ """回收失败只波及它自己,剩下的工作树照常处理,不用人反复重跑。"""
+ stuck = self._integrated("stuck-first")
+ other = self._integrated("second-in-line")
+ with mock.patch.object(agent_worktree, "_git",
+ StuckRemoval(agent_worktree._git, {stuck: "stuck"})):
+ report = prune(self.repo, apply=True)
+ self.assertEqual(report["reclaimed"], [str(other)])
+ self.assertFalse(other.exists())
+ self.assertNotIn("second-in-line",
+ _git(self.repo, "branch", "--list", "agent/codex/second-in-line").stdout)
+ self.assertEqual([row["branch"] for row in report["failed"]], ["agent/codex/stuck-first"])
+ self.assertTrue(stuck.is_dir())
+ self.assertIn("stuck-first",
+ _git(self.repo, "branch", "--list", "agent/codex/stuck-first").stdout,
+ "注册还在就是没回收成,分支不能删")