Peach: Local-first video metadata scraper and media manager.
chore: isolate concurrent agent changes
Peach local maintenancee853fbcd6c64
diff --git a/AGENTS.md b/AGENTS.mdindex 39572411e..cb5409022 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -25,5 +25,8 @@ Working rules:- Before adding or restoring an implementation, check `docs/REUSE.md`, the current tree and Git history. A missing legacy filename does not prove the capability is missing. Update the reuse register when the decision changes.- When the user says to imitate, reference or align with another product, obtain current reproducible evidence first: live behavior plus DOM/CSS/source/bundle where available, or exact screenshot measurements when source is unavailable. Record the URL/version/hash and intentional Peach deviations in `docs/HANDOFF.md`. If evidence is unavailable, write `未取得`; do not ship a guessed approximation as a faithful reproduction.- Never require the user to relay implementation details between agents. Put current facts in `docs/STATUS.md`, durable rules in `docs/HANDOFF.md`/`docs/REUSE.md`, and architecture decisions in an ADR.+- During concurrent code work, `R:\peach-app` is integration-only. Each agent must create and edit an isolated Git worktree with `scripts/agent_worktree.py create`; a worker commits its branch and reports it ready, but never merges itself merely because it finished last.+- Never use `git add .`, `git add -A`, a directory path, or a glob in an agent checkout. Stage only the exact files owned by the task, then inspect `git diff --cached --name-status`. Tests belong to the implementation they exercise: never stage a test when the corresponding implementation is outside the task or unstaged.+- A clean `git status` is not proof of correct ownership. Before commit, compare the staged path list with the task boundary and run the relevant tests from that same worktree. The coordinator alone integrates ready branches, resolves same-file conflicts and restarts production.- Run the verification commands in `README.md` before committing relevant changes.- Reuse existing usage surfaces and protocols. T3 Code/CodexBar cover historical token and API-equivalent cost views; official provider quota endpoints cover live remaining windows. Do not build another session-log cost scanner or depend on T3 Code's private localhost API.diff --git a/README.md b/README.mdindex 71a96968d..35562c5e9 100644--- a/README.md+++ b/README.md@@ -76,6 +76,14 @@ cd R:\peach-app前提下把自签 HTTPS 变成无警告连接;Let's Encrypt 也不会签发 `.local`。当前运行态与下一任务只看 [`docs/STATUS.md`](docs/STATUS.md);跨 Codex/Claude 的固定接手方式只看 [`docs/HANDOFF.md`](docs/HANDOFF.md)。++并行代码任务不共享编辑目录。由协调者在主目录创建独立 worktree:++```powershell+& .\.venv\Scripts\python.exe scripts\agent_worktree.py create --agent claude --task metadata-batch+```++工作者在返回目录提交后运行 `ready`;协调者审核并运行 `integrate`。脚本会拒绝脏工作树、无提交分支和双方都修改过同一文件的自动合并。禁止 `git add .` / `git add -A`,只暂存任务明确拥有的文件。准备新增、恢复或替换实现前,必须查 [`docs/REUSE.md`](docs/REUSE.md),避免按旧文件名重复造轮子。## 批处理安全边界diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 8d6fbdf01..3dd832929 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -17,6 +17,9 @@ This is durable operating knowledge, not a per-session transcript.- Codex is the coordinator for architecture, code ownership, review, migrations, real-ledger writes, service restarts and final verification. Claude is a parallel worker for bounded mechanical batches such as board reading, metadata candidate scraping and CSV reconciliation; handoff is not the goal.- Parallel workers receive explicit input/output paths, network and cost policy, write boundary and acceptance criteria. They write `candidate` review artifacts only; they do not mark their own output `approved`, run `--apply`, alter migrations/ADR, or restart services.- Use separate Git worktrees for concurrent code changes. Data-only batches may share the main checkout only when their sole writable artifact is outside Git and named in the task. Never let two agents edit the same file.+- The worktree is the edit buffer: run `python scripts/agent_worktree.py create --agent <agent> --task <slug>` from the integration checkout, do all edits/tests/commits in the returned path, then run `ready` there. The coordinating agent runs `integrate` only after review. “Last finisher automatically wins” is forbidden because completion order says nothing about dependency or correctness; Git three-way merge plus coordinator review is the arbitration layer.+- `bba0b77` is the concrete failure case. Codex did not use `git add .`, but still misclassified Claude's newly written `tests/test_scripts.py` as owned and staged it while leaving the required `scripts/probe.py` implementation unstaged. HEAD therefore contained a test for code that did not exist until Claude repaired it. Explicit filenames are necessary but insufficient: isolated worktrees, staged-path ownership review and implementation/test atomicity are mandatory.+- Never use `git add .`, `git add -A`, directory staging or globs. Before every worker commit, read `git diff --cached --name-status`; if any path was not assigned to that worker, unstage it. Workers do not merge, migrate the real ledger or restart production.- Worker results return to the coordinating agent for vocabulary/provenance checks, deduplication, isolated tests and approval. The user does not relay reports between agents.- `scripts/scrape_codes.py` and `scripts/creator_tags.py` are the standard review boundaries. Creator-board work exports `generated/creator-tags-review.csv`; workers may change `pending` to `candidate` or `skip`, while `approved` and the required backup remain coordinator actions.- **Superseded 2026-08-14.** The earlier note that Claude refuses explicit sexual-act classification fromdiff --git a/scripts/agent_worktree.py b/scripts/agent_worktree.pynew file mode 100644index 000000000..ce337e99d--- /dev/null+++ b/scripts/agent_worktree.py@@ -0,0 +1,142 @@+from __future__ import annotations++import argparse+import json+import re+import subprocess+from pathlib import Path+++class WorkspaceError(RuntimeError):+ pass+++def _git(repo: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:+ command = [+ "git", "-c", f"safe.directory={repo.as_posix()}", "-C", str(repo), *args,+ ]+ result = subprocess.run(command, text=True, capture_output=True, check=False)+ if check and result.returncode:+ raise WorkspaceError((result.stderr or result.stdout).strip())+ return result+++def _slug(value: str) -> str:+ slug = re.sub(r"[^a-z0-9]+", "-", value.strip().lower()).strip("-")+ if not slug:+ raise WorkspaceError("agent/task must contain letters or numbers")+ return slug+++def _main_worktree(repo: Path) -> Path:+ common = Path(_git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir").stdout.strip())+ return common.parent if common.name == ".git" else common+++def _lines(result: subprocess.CompletedProcess[str]) -> list[str]:+ return [line for line in result.stdout.splitlines() if line]+++def create(repo: Path, agent: str, task: str, root: Path | None = None) -> dict[str, object]:+ main = _main_worktree(repo)+ agent_slug, task_slug = _slug(agent), _slug(task)+ branch = f"agent/{agent_slug}/{task_slug}"+ target_root = root or (main.parent / "peach-worktrees")+ target = target_root / f"{agent_slug}-{task_slug}"+ if target.exists():+ raise WorkspaceError(f"target exists: {target}")+ if _git(main, "show-ref", "--verify", f"refs/heads/{branch}", check=False).returncode == 0:+ raise WorkspaceError(f"branch exists: {branch}")+ target_root.mkdir(parents=True, exist_ok=True)+ _git(main, "worktree", "add", "-b", branch, str(target), "HEAD")+ return {+ "ok": True,+ "action": "create",+ "path": str(target),+ "branch": branch,+ "base": _git(target, "rev-parse", "HEAD").stdout.strip(),+ "main_dirty": bool(_git(main, "status", "--porcelain").stdout.strip()),+ }+++def ready(repo: Path, target_branch: str = "master") -> dict[str, object]:+ branch = _git(repo, "branch", "--show-current").stdout.strip()+ if not branch.startswith("agent/"):+ raise WorkspaceError("ready must run from an agent/* branch")+ dirty = _lines(_git(repo, "status", "--porcelain"))+ if dirty:+ raise WorkspaceError("worktree is dirty; commit only owned paths first")+ base = _git(repo, "merge-base", target_branch, "HEAD").stdout.strip()+ commits = _lines(_git(repo, "rev-list", "--reverse", f"{base}..HEAD"))+ if not commits:+ raise WorkspaceError("branch has no commits")+ worker_files = set(_lines(_git(repo, "diff", "--name-only", f"{base}..HEAD")))+ target_files = set(_lines(_git(repo, "diff", "--name-only", f"{base}..{target_branch}")))+ return {+ "ok": True,+ "action": "ready",+ "branch": branch,+ "base": base,+ "head": _git(repo, "rev-parse", "HEAD").stdout.strip(),+ "commits": commits,+ "files": sorted(worker_files),+ "same_file_changes": sorted(worker_files & target_files),+ }+++def integrate(repo: Path, worker_branch: str, target_branch: str = "master") -> dict[str, object]:+ main = _main_worktree(repo)+ if repo.resolve() != main.resolve():+ raise WorkspaceError("integrate must run from the main integration worktree")+ if _git(main, "branch", "--show-current").stdout.strip() != target_branch:+ raise WorkspaceError(f"checkout {target_branch} before integrate")+ if _git(main, "status", "--porcelain").stdout.strip():+ raise WorkspaceError("integration worktree is dirty")+ base = _git(main, "merge-base", target_branch, worker_branch).stdout.strip()+ worker_files = set(_lines(_git(main, "diff", "--name-only", f"{base}..{worker_branch}")))+ target_files = set(_lines(_git(main, "diff", "--name-only", f"{base}..{target_branch}")))+ overlap = sorted(worker_files & target_files)+ if overlap:+ raise WorkspaceError("same-file review required: " + ", ".join(overlap))+ before = _git(main, "rev-parse", "HEAD").stdout.strip()+ _git(main, "merge", "--no-ff", "--no-edit", worker_branch)+ return {+ "ok": True,+ "action": "integrate",+ "branch": worker_branch,+ "before": before,+ "after": _git(main, "rev-parse", "HEAD").stdout.strip(),+ "files": sorted(worker_files),+ }+++def main() -> int:+ parser = argparse.ArgumentParser(description="Isolated Peach agent worktree coordinator")+ parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1])+ sub = parser.add_subparsers(dest="command", required=True)+ start = sub.add_parser("create")+ start.add_argument("--agent", required=True)+ start.add_argument("--task", required=True)+ start.add_argument("--root", type=Path)+ inspect = sub.add_parser("ready")+ inspect.add_argument("--target", default="master")+ merge = sub.add_parser("integrate")+ merge.add_argument("--branch", required=True)+ merge.add_argument("--target", default="master")+ 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)+ else:+ result = integrate(args.repo, args.branch, args.target)+ except WorkspaceError as exc:+ print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False))+ return 2+ print(json.dumps(result, ensure_ascii=False, indent=2))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_agent_worktree.py b/tests/test_agent_worktree.pynew file mode 100644index 000000000..e966e5f49--- /dev/null+++ b/tests/test_agent_worktree.py@@ -0,0 +1,61 @@+import subprocess+import tempfile+import unittest+from pathlib import Path++from scripts.agent_worktree import WorkspaceError, _git, create, integrate, ready+++def commit(repo: Path, message: str) -> None:+ _git(repo, "add", "tracked.txt", "worker.txt")+ _git(repo, "commit", "-m", message)+++class AgentWorktreeTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.repo = self.root / "repo"+ self.repo.mkdir()+ subprocess.run(["git", "init", "-b", "master", str(self.repo)], check=True,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ _git(self.repo, "config", "user.email", "[email protected]")+ _git(self.repo, "config", "user.name", "Peach Test")+ (self.repo / "tracked.txt").write_text("base\n", encoding="utf-8")+ (self.repo / "worker.txt").write_text("base\n", encoding="utf-8")+ commit(self.repo, "base")++ def tearDown(self):+ self.tmp.cleanup()++ def test_create_ready_and_integrate_non_overlapping_branch(self):+ result = create(self.repo, "Claude", "metadata batch", self.root / "worktrees")+ worker = Path(result["path"])+ (worker / "worker.txt").write_text("worker\n", encoding="utf-8")+ commit(worker, "worker change")+ report = ready(worker)+ self.assertEqual(report["same_file_changes"], [])+ merged = integrate(self.repo, str(result["branch"]))+ self.assertIn("worker.txt", merged["files"])+ self.assertEqual((self.repo / "worker.txt").read_text(encoding="utf-8"), "worker\n")++ def test_ready_rejects_dirty_worker(self):+ result = create(self.repo, "Codex", "dirty task", self.root / "worktrees")+ worker = Path(result["path"])+ (worker / "worker.txt").write_text("dirty\n", encoding="utf-8")+ with self.assertRaisesRegex(WorkspaceError, "dirty"):+ ready(worker)++ def test_integrate_refuses_same_file_changed_on_both_branches(self):+ result = create(self.repo, "Claude", "overlap", self.root / "worktrees")+ worker = Path(result["path"])+ (worker / "tracked.txt").write_text("worker\n", encoding="utf-8")+ commit(worker, "worker overlap")+ (self.repo / "tracked.txt").write_text("main\n", encoding="utf-8")+ commit(self.repo, "main overlap")+ with self.assertRaisesRegex(WorkspaceError, "same-file"):+ integrate(self.repo, str(result["branch"]))+++if __name__ == "__main__":+ unittest.main()