Peach: Local-first video metadata scraper and media manager.
feat(hygiene): 工作树回收做成命令,顶层与文档失真做成门槛
longmeidaoff64890a8c5e
diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.mdindex 690d6abc8..965c5fca4 100644--- a/.claude/skills/peach-worktree/SKILL.md+++ b/.claude/skills/peach-worktree/SKILL.md@@ -70,3 +70,24 @@ description: 在用户说并行、开工作树、worktree、暂存、提交、re- 工作者报 `ready` 前必须 rebase 到当前 `master`。落后十天的分支不要指望协调者去 merge:共享文件上你那一侧是旧的,冲突解错就会把已上线的修复回退掉。2026-08-25 清理时有 7 条这样的分支,最后是把各自独有的那几个文件移植到当前 master,而不是 merge 分支本体。++## 回收与顶层归置++工作树用完要回收:`python scripts/agent_worktree.py prune` 列出分支已并入 master 且工作区+干净的工作树,加 `--apply` 才真的删。以前只有 `create` 有入口,回收全靠人想起来——2026-08-29+手工清到 3 个,两天后长回 74 个、占 868 MB。脏的一律拒收并单独列出:分支已合入不等于工作区+里没东西,实测就有工作树的分支早已并入 master、里面却躺着一份成形的未提交改动。++`Desktop\peach` 顶层只放 ADR-0017 定义的四个运行时目录加一个 `attic/`:++ peach-app peach-data peach-sync peach-worktrees attic++`peach-` 前缀专属那四个,不再新增;别的东西按性质进 `attic/` 的 `builds`/`evidence`/+`instances`/`tools`/`reviews`,目录名写成 `YYYYMMDD-主题`,顶层不放散落文件。这条规则原本+只写在 `../attic/README.md`——仓库外、不进 Git、AGENTS.md 也没提,于是在 peach-app 里干活的+人根本看不到它,清完两天又堆回三个违规目录。现在由 `test_repo_hygiene` 守住。++`attic/` 不等于可以随便删:`instances/` 常带 100 MB 量级的 ledger 副本,`tools/` 的+`runtime.json` 会留 token。账本副本、复核产物和取证归档按 AGENTS.md 的保留清单对待,+删除要单独确认。+diff --git a/AGENTS.md b/AGENTS.mdindex fdb71a023..ba814b10d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -44,7 +44,7 @@| 触发条件 | 文件 || --- | --- |-| 并行任务、创建工作树、暂存与提交、集成分支 | `.claude/skills/peach-worktree/SKILL.md` |+| 并行任务、创建工作树、暂存与提交、集成分支、回收工作树、顶层目录归置 | `.claude/skills/peach-worktree/SKILL.md` || 迁移、`--apply`、实体合并、批量删除等真实 ledger 写入 | `.claude/skills/peach-ledger-write/SKILL.md` || 改完界面、API、契约或文案后声明影响面 | `.claude/skills/peach-surfaces/SKILL.md` || 长跑批处理、刮削、限流、磁盘与流量预算 | `.claude/skills/peach-batch-jobs/SKILL.md` |diff --git a/scripts/agent_worktree.py b/scripts/agent_worktree.pyindex 0f2aa15ad..cc9dfa1a3 100644--- a/scripts/agent_worktree.py+++ b/scripts/agent_worktree.py@@ -111,6 +111,63 @@ def integrate(repo: Path, worker_branch: str, target_branch: str = "master") ->}+def prune(repo: Path, target_branch: str = "master", *,+ apply: bool = False) -> dict[str, object]:+ """回收分支已并入 target、且工作区干净的隔离工作树。++ 这个命令存在的理由:`create` 一直有人用,回收却从来没有入口。2026-08-29 清过一次+ 到 3 个,两天后又长回 74 个、占 868 MB——因为那次是一次性动作,不是常设机制。++ 默认只报告不动手。回收不可逆,而「分支已合入」并不等于「工作区里没有东西」:+ 实测就有工作树的分支早已并入 master,里面却躺着一份成形的未提交改动。所以脏的+ 一律拒收并单独列出,交给人看,不给 `--force` 这个口子。+ """+ main = _main_worktree(repo)+ merged = {line.strip().lstrip("+* ") for line in+ _lines(_git(main, "branch", "--merged", target_branch,+ "--format=%(refname:short)"))}+ merged.discard(target_branch)+ here = repo.resolve()++ reclaimed: list[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:+ path = Path(item["path"])+ branch = item.get("branch", "")+ if path.resolve() == main.resolve() or path.resolve() == here:+ continue+ if branch not in merged:+ kept.append({"path": str(path), "branch": branch, "why": "分支未并入 " + target_branch})+ continue+ if _git(main, "-C", str(path), "status", "--porcelain",+ 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))++ return {+ "ok": True,+ "action": "prune",+ "applied": apply,+ "reclaimed": sorted(reclaimed),+ "dirty": dirty,+ "kept": kept,+ }++def main() -> int:parser = argparse.ArgumentParser(description="Isolated Peach agent worktree coordinator")parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1])@@ -124,12 +181,18 @@ def main() -> int:merge = sub.add_parser("integrate")merge.add_argument("--branch", required=True)merge.add_argument("--target", default="master")+ sweep = sub.add_parser("prune")+ sweep.add_argument("--target", default="master")+ sweep.add_argument("--apply", action="store_true",+ help="真的回收;不给这个参数就只报告")args = parser.parse_args()try:if args.command == "create":result = create(args.repo, args.agent, args.task, args.root)elif args.command == "ready":result = ready(args.repo, args.target)+ elif args.command == "prune":+ result = prune(args.repo, args.target, apply=args.apply)else:result = integrate(args.repo, args.branch, args.target)except WorkspaceError as exc:diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex a7fe7af63..edf4cdfde 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -37,6 +37,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_versioning.py","test_windows_update.py", "test_certs.py", "test_config.py","test_job_status.py", "test_jobs.py", "test_reference_updates.py",+ "test_repo_hygiene.py","test_review_csv.py","test_subprocess_encoding.py", "test_module_layering.py"),}diff --git a/tests/test_agent_worktree.py b/tests/test_agent_worktree.pyindex e966e5f49..5a6614739 100644--- a/tests/test_agent_worktree.py+++ b/tests/test_agent_worktree.py@@ -3,7 +3,7 @@ import tempfileimport unittestfrom pathlib import Path-from scripts.agent_worktree import WorkspaceError, _git, create, integrate, ready+from scripts.agent_worktree import WorkspaceError, _git, create, integrate, prune, readydef commit(repo: Path, message: str) -> None:@@ -59,3 +59,66 @@ class AgentWorktreeTests(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class PruneTests(AgentWorktreeTests):+ """回收已经并入 master 的隔离工作树。++ `create` 一直有人用,回收却从来没有入口——2026-08-29 清到 3 个,两天后长回 74 个、+ 占 868 MB。一次性清理解决不了这个问题,所以把回收做成命令,并在这里锁住它的边界。+ """++ def _integrated(self, name: str) -> Path:+ result = create(self.repo, "Codex", name, self.root / "worktrees")+ worker = Path(result["path"])+ (worker / "worker.txt").write_text(name + " done\n", encoding="utf-8")+ commit(worker, f"{name} change")+ integrate(self.repo, str(result["branch"]))+ return worker++ def test_reporting_does_not_remove_anything(self):+ """默认只报告。回收不可逆,不该是运行一下就顺手做了的事。"""+ worker = self._integrated("reportable")+ report = prune(self.repo)+ self.assertIn(str(worker), report["reclaimed"])+ self.assertFalse(report["applied"])+ self.assertTrue(worker.is_dir(), "没给 --apply 就不该动手")++ def test_apply_reclaims_the_worktree_and_its_branch(self):+ worker = self._integrated("reclaimable")+ branch = _git(self.repo, "branch", "--list", "agent/codex/reclaimable").stdout+ self.assertIn("reclaimable", branch)+ prune(self.repo, apply=True)+ self.assertFalse(worker.exists(), "工作树应当被回收")+ self.assertNotIn("reclaimable",+ _git(self.repo, "branch", "--list", "agent/codex/reclaimable").stdout,+ "已并入的分支也应一并删掉")++ def test_a_dirty_worktree_is_refused_even_when_its_branch_is_merged(self):+ """分支已合入不等于工作区里没东西。++ 实测就有这样的工作树:分支早已并入 master,里面却躺着一份成形的未提交改动+ (按钮等待态改用 aria-busy,还配了对应的测试)。所以脏的一律拒收并单独列出,+ 交给人看,不给 --force 这个口子。+ """+ worker = self._integrated("has-wip")+ (worker / "worker.txt").write_text("未提交的后续改动\n", encoding="utf-8")+ report = prune(self.repo, apply=True)+ self.assertTrue(worker.is_dir(), "脏工作树不能被回收")+ self.assertEqual([row["path"] for row in report["dirty"]], [str(worker)])+ self.assertEqual(report["reclaimed"], [])++ def test_an_unmerged_branch_is_kept_with_a_reason(self):+ result = create(self.repo, "Codex", "still-open", self.root / "worktrees")+ worker = Path(result["path"])+ (worker / "worker.txt").write_text("still open wip\n", encoding="utf-8")+ commit(worker, "still open")+ report = prune(self.repo, apply=True)+ self.assertTrue(worker.is_dir())+ self.assertEqual([row["branch"] for row in report["kept"]], ["agent/codex/still-open"])++ def test_the_main_worktree_is_never_a_candidate(self):+ self._integrated("bystander")+ report = prune(self.repo)+ listed = report["reclaimed"] + [row["path"] for row in report["dirty"] + report["kept"]]+ self.assertNotIn(str(self.repo), listed, "主检出不能出现在回收清单里")diff --git a/tests/test_repo_hygiene.py b/tests/test_repo_hygiene.pynew file mode 100644index 000000000..6e48d26d0--- /dev/null+++ b/tests/test_repo_hygiene.py@@ -0,0 +1,109 @@+"""仓库与顶层目录的卫生门槛。++这里守的都是「清理过一次、过几天又长回来」的东西。一次性清理解决不了它们:+2026-08-29 把顶层收敛到 4 个运行时目录、工作树清到 3 个,两天后顶层多出三个违规目录、+工作树长回 74 个。原因是规则只写在 `../attic/README.md`——仓库外、不进 Git、AGENTS.md+也没提,在 peach-app 里干活的人根本看不到。约定不是门槛。+"""+import pathlib+import re+import unittest++import peach++REPO = pathlib.Path(peach.__file__).resolve().parents[2]+DOCS = REPO / "docs"++#: ADR-0017 定义的四个运行时目录,加一个归置处。顶层只允许这五项。+TOP_LEVEL_ALLOWED = {"peach-app", "peach-data", "peach-sync", "peach-worktrees", "attic"}+++class TopLevelLayoutTests(unittest.TestCase):+ """顶层只放四个运行时目录加 attic/,且不放散落文件。++ 在别的机器或 CI 上这个布局不成立(只 clone 了 peach-app),那里跳过——门槛要能在+ 真实布局上拦住人,不能因为环境不同就把整套测试拖红。+ """++ def setUp(self):+ # 往上找真正的顶层,而不是 `REPO.parent`:测试几乎总是在隔离工作树里跑,那时+ # 上一级是 `peach-worktrees/`,判据不成立就会永远跳过——一个永远跳过的门槛+ # 等于没有,和它要防的失效是同一种。+ self.top = None+ for candidate in [REPO, *REPO.parents]:+ if all((candidate / name).is_dir()+ for name in ("peach-app", "peach-data", "peach-worktrees")):+ self.top = candidate+ break+ if self.top is None:+ self.skipTest("不是双盘运行时布局(只 clone 了 peach-app),跳过")++ def test_only_the_runtime_directories_and_attic_live_at_the_top(self):+ extra = sorted(p.name for p in self.top.iterdir()+ if p.is_dir() and p.name not in TOP_LEVEL_ALLOWED)+ self.assertEqual(+ extra, [],+ "顶层多了目录:`peach-` 前缀专属那四个运行时目录,别的东西进 attic/ 的"+ " builds/evidence/instances/tools/reviews,目录名写成 YYYYMMDD-主题",+ )++ def test_no_loose_files_at_the_top(self):+ loose = sorted(p.name for p in self.top.iterdir() if p.is_file())+ self.assertEqual(loose, [],+ "顶层不放散落文件:文档进 attic/reviews/,产物进 attic/evidence/")+++class BacklogSelfConsistencyTests(unittest.TestCase):+ """产品待办自己报的数必须和它列的条目对得上。++ 测试逼不出「有人去更新 prose」,但能逼出「改了条目却忘了改总数」——那是这份文档+ 最常见的失真,而且一旦失真,后面每次读它的人都会被那个总数误导。+ """++ def setUp(self):+ self.text = (DOCS / "PRODUCT_BACKLOG.md").read_text(encoding="utf-8")++ def _numbered(self, heading: str) -> int:+ body = self.text.split(heading, 1)[1].split("\n## ", 1)[0]+ return len(re.findall(r"^\d+\. ", body, re.M))++ def test_the_stated_totals_match_the_items_listed(self):+ skeleton = self._numbered("## 已有骨架、尚未完成")+ unbuilt = self._numbered("## 尚未实现")+ claimed = re.search(r"合计:\*\*(\d+) 项开放需求\*\*,其中 (\d+) 项已有骨架,(\d+) 项尚未实现",+ self.text)+ self.assertIsNotNone(claimed, "结尾那句合计被改写了,请保持可核对的写法")+ total, said_skeleton, said_unbuilt = (int(g) for g in claimed.groups())+ self.assertEqual((said_skeleton, said_unbuilt), (skeleton, unbuilt),+ "分项数和实际列出的条目对不上")+ self.assertEqual(total, skeleton + unbuilt, "合计和分项加起来对不上")++ def test_the_section_headings_declare_their_own_counts(self):+ for heading, actual in (("已有骨架、尚未完成", self._numbered("## 已有骨架、尚未完成")),+ ("尚未实现", self._numbered("## 尚未实现"))):+ declared = re.search(rf"## {heading}((\d+) 项)", self.text)+ self.assertIsNotNone(declared, f"「{heading}」的标题应当带上条数,便于一眼核对")+ self.assertEqual(int(declared.group(1)), actual,+ f"「{heading}」标题写的条数和实际列出的对不上")+++class ArchitectureDriftTests(unittest.TestCase):+ """架构文档点名的模块必须真的存在。++ 它逼不出「架构变了要重写描述」,但能逼出「模块改名或删掉之后文档还在指它」——+ 那种失真最难发现,因为文档读起来一切正常。+ """++ def test_every_module_the_document_names_still_exists(self):+ text = (DOCS / "ARCHITECTURE.md").read_text(encoding="utf-8")+ source = pathlib.Path(peach.__file__).parent+ missing = sorted({+ name for name in re.findall(r"`src/peach/(\w+)\.py`", text)+ if not (source / f"{name}.py").is_file()+ })+ self.assertEqual(missing, [],+ "架构文档还在指已经不存在的模块,改名或删除时请一起改")+++if __name__ == "__main__":+ unittest.main()