@michaelxwb/code-flow 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/adapters/claude/commands/cf-init.md +1 -0
  4. package/src/adapters/claude/commands/cf-spec.md +7 -3
  5. package/src/adapters/claude/commands/cf-task/archive.md +5 -5
  6. package/src/adapters/claude/commands/cf-task/block.md +15 -9
  7. package/src/adapters/claude/commands/cf-task/graph.md +8 -1
  8. package/src/adapters/claude/commands/cf-task/note.md +1 -4
  9. package/src/adapters/claude/commands/cf-task/plan.md +2 -2
  10. package/src/adapters/claude/commands/cf-task/start.md +96 -25
  11. package/src/adapters/claude/commands/cf-task/verify-e2e.md +8 -9
  12. package/src/adapters/claude/commands/cf-validate.md +15 -13
  13. package/src/adapters/codex/skills/cf-init/SKILL.md +1 -0
  14. package/src/adapters/codex/skills/cf-spec/SKILL.md +6 -2
  15. package/src/adapters/codex/skills/cf-task-archive/SKILL.md +5 -5
  16. package/src/adapters/codex/skills/cf-task-block/SKILL.md +15 -9
  17. package/src/adapters/codex/skills/cf-task-graph/SKILL.md +8 -1
  18. package/src/adapters/codex/skills/cf-task-note/SKILL.md +1 -4
  19. package/src/adapters/codex/skills/cf-task-plan/SKILL.md +2 -2
  20. package/src/adapters/codex/skills/cf-task-start/SKILL.md +96 -25
  21. package/src/adapters/codex/skills/cf-task-verify-e2e/SKILL.md +106 -0
  22. package/src/adapters/codex/skills/cf-validate/SKILL.md +15 -13
  23. package/src/adapters/costrict/commands/cf-init.md +1 -0
  24. package/src/adapters/costrict/commands/cf-spec.md +7 -3
  25. package/src/adapters/costrict/commands/cf-task/archive.md +5 -5
  26. package/src/adapters/costrict/commands/cf-task/block.md +15 -9
  27. package/src/adapters/costrict/commands/cf-task/graph.md +8 -1
  28. package/src/adapters/costrict/commands/cf-task/note.md +1 -4
  29. package/src/adapters/costrict/commands/cf-task/plan.md +2 -2
  30. package/src/adapters/costrict/commands/cf-task/start.md +96 -25
  31. package/src/adapters/costrict/commands/cf-task/verify-e2e.md +8 -9
  32. package/src/adapters/costrict/commands/cf-validate.md +15 -13
  33. package/src/adapters/opencode/commands/cf-init.md +9 -4
  34. package/src/adapters/opencode/commands/cf-spec.md +6 -2
  35. package/src/adapters/opencode/commands/cf-task/archive.md +5 -5
  36. package/src/adapters/opencode/commands/cf-task/block.md +15 -9
  37. package/src/adapters/opencode/commands/cf-task/graph.md +8 -1
  38. package/src/adapters/opencode/commands/cf-task/note.md +1 -4
  39. package/src/adapters/opencode/commands/cf-task/plan.md +2 -2
  40. package/src/adapters/opencode/commands/cf-task/start.md +96 -25
  41. package/src/adapters/opencode/commands/cf-task/verify-e2e.md +8 -9
  42. package/src/adapters/opencode/commands/cf-validate.md +15 -13
  43. package/src/adapters/opencode/opencode.json +1 -2
  44. package/src/adapters/opencode/plugins/code-flow/index.js +176 -94
  45. package/src/adapters/opencode/plugins/code-flow/package.json +1 -1
  46. package/src/cli.js +228 -64
  47. package/src/core/code-flow/config.yml +2 -1
  48. package/src/core/code-flow/scripts/cf_acceptance_evidence.py +100 -0
  49. package/src/core/code-flow/scripts/cf_acceptance_manifest.py +137 -42
  50. package/src/core/code-flow/scripts/cf_acceptance_runner.py +123 -38
  51. package/src/core/code-flow/scripts/cf_acceptance_schema.py +83 -0
  52. package/src/core/code-flow/scripts/cf_core.py +34 -1
  53. package/src/core/code-flow/scripts/cf_exec_base.py +112 -0
  54. package/src/core/code-flow/scripts/cf_post_hook.py +5 -4
  55. package/src/core/code-flow/scripts/cf_pre_tool_hook.py +22 -7
  56. package/src/core/code-flow/scripts/cf_scan.py +8 -6
  57. package/src/core/code-flow/scripts/cf_spec_context.py +197 -63
  58. package/src/core/code-flow/scripts/cf_spec_gate.py +26 -4
  59. package/src/core/code-flow/scripts/cf_spec_resolver.py +7 -2
  60. package/src/core/code-flow/scripts/cf_spec_router.py +3 -1
  61. package/src/core/code-flow/scripts/cf_spec_session.py +3 -2
  62. package/src/core/code-flow/scripts/cf_spec_verify.py +42 -31
  63. package/src/core/code-flow/scripts/cf_stats.py +41 -9
  64. package/src/core/code-flow/scripts/cf_stop_hook.py +128 -61
  65. package/src/core/code-flow/scripts/cf_task_index.py +148 -0
  66. package/src/core/code-flow/scripts/cf_task_parallel.py +385 -0
  67. package/src/core/code-flow/scripts/cf_task_runtime.py +98 -29
  68. package/src/core/code-flow/scripts/cf_task_state.py +3 -0
  69. package/src/core/code-flow/scripts/cf_task_workflow.py +107 -0
  70. package/src/core/code-flow/scripts/cf_user_prompt_hook.py +9 -5
  71. package/src/core/code-flow/scripts/cf_validation.py +81 -0
  72. package/src/core/code-flow/scripts/cf_workflow_service.py +366 -0
  73. package/src/core/code-flow/scripts/cf_workflow_transaction.py +96 -0
  74. package/src/core/code-flow/validation.yml +5 -0
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env python3
2
+ """Programmatic task-file index: parse TASK statuses/depends, compute DAG batches.
3
+
4
+ Single worktrees allow one active TASK at a time; batches list *independently
5
+ developable* tasks (no dependency path between them). `cf-task:start` may
6
+ dispatch batch tasks in their own worktrees for parallel subagents — the
7
+ single-active constraint stays per worktree.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import re
15
+ import sys
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import IO, Mapping, Optional, Sequence
19
+
20
+
21
+ from cf_task_state import FINISHED_STATUSES as _DONE_STATUSES
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class TaskNode:
26
+ task_id: str
27
+ status: str
28
+ depends: tuple[str, ...]
29
+
30
+
31
+ def parse_task_file(task_file: str) -> tuple[TaskNode, ...]:
32
+ """Parse every `## TASK-xxx` section into status/depends nodes.
33
+
34
+ Unknown statuses are preserved verbatim (e.g. `verified` from the E2E
35
+ flow) — the parser never rejects them, completion checks treat done and
36
+ verified as finished.
37
+ """
38
+ try:
39
+ text = Path(task_file).read_text(encoding="utf-8")
40
+ except (OSError, UnicodeError) as exc:
41
+ raise ValueError(f"task_read_error: {exc}") from exc
42
+ nodes: list[TaskNode] = []
43
+ matches = list(re.finditer(r"(?m)^## (TASK-\d+):[^\n]*$", text))
44
+ for index, match in enumerate(matches):
45
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
46
+ section = text[match.start():end]
47
+ status_match = re.search(r"(?m)^- \*\*Status\*\*:[ \t]*([^\n]+)", section)
48
+ status = status_match.group(1).strip() if status_match else "draft"
49
+ depends_match = re.search(r"(?m)^- \*\*Depends\*\*:[ \t]*([^\n]*)", section)
50
+ depends: tuple[str, ...] = ()
51
+ if depends_match:
52
+ depends = tuple(
53
+ part.strip()
54
+ for part in re.split(r"[,,\s]+", depends_match.group(1).strip())
55
+ if re.fullmatch(r"TASK-\d+", part.strip())
56
+ )
57
+ nodes.append(TaskNode(match.group(1), status, depends))
58
+ if not nodes:
59
+ raise ValueError("no TASK sections found")
60
+ return tuple(nodes)
61
+
62
+
63
+ def task_batches(nodes: Sequence[TaskNode]) -> list[list[str]]:
64
+ """Topological batches over unfinished TASKs; unknown deps and cycles raise."""
65
+ ids = {node.task_id for node in nodes}
66
+ for node in nodes:
67
+ unknown = [dep for dep in node.depends if dep not in ids]
68
+ if unknown:
69
+ raise ValueError(f"unknown depends: {node.task_id} -> {', '.join(unknown)}")
70
+ pending = {node.task_id for node in nodes if node.status not in _DONE_STATUSES}
71
+ finished = {node.task_id for node in nodes if node.status in _DONE_STATUSES}
72
+ deps = {node.task_id: set(node.depends) for node in nodes}
73
+ batches: list[list[str]] = []
74
+ while pending:
75
+ ready = sorted(task for task in pending if deps[task] <= finished)
76
+ if not ready:
77
+ raise ValueError(f"dependency cycle among: {', '.join(sorted(pending))}")
78
+ batches.append(ready)
79
+ finished.update(ready)
80
+ pending.difference_update(ready)
81
+ return batches
82
+
83
+
84
+ def dependency_components(nodes: Sequence[TaskNode]) -> list[list[str]]:
85
+ """Connected dependency components; different components are independent."""
86
+ parent = {node.task_id: node.task_id for node in nodes}
87
+
88
+ def find(task: str) -> str:
89
+ while parent[task] != task:
90
+ parent[task] = parent[parent[task]]
91
+ task = parent[task]
92
+ return task
93
+
94
+ for node in nodes:
95
+ for dep in node.depends:
96
+ left, right = find(node.task_id), find(dep)
97
+ if left != right:
98
+ parent[left] = right
99
+ groups: dict[str, list[str]] = {}
100
+ for node in nodes:
101
+ groups.setdefault(find(node.task_id), []).append(node.task_id)
102
+ return [sorted(members) for members in groups.values()]
103
+
104
+
105
+ def independent_groups(nodes: Sequence[TaskNode]) -> list[list[str]]:
106
+ """Compatibility alias: groups are independent of each other, not within."""
107
+ return dependency_components(nodes)
108
+
109
+
110
+ def index_data(task_file: str) -> dict[str, object]:
111
+ nodes = parse_task_file(task_file)
112
+ return {
113
+ "tasks": [
114
+ {"id": node.task_id, "status": node.status, "depends": list(node.depends)}
115
+ for node in nodes
116
+ ],
117
+ "batches": task_batches(nodes),
118
+ "independent_groups": independent_groups(nodes),
119
+ "dependency_components": dependency_components(nodes),
120
+ "note": "batches 组内无依赖;dependency_components 仅组间独立(independent_groups 为兼容别名);单 worktree 一次仅激活一个 TASK,批次内独立任务可由 cf-task:start 在各 worktree 并行派发",
121
+ }
122
+
123
+
124
+ def main(argv: Optional[Sequence[str]] = None, stdout: IO[str] = sys.stdout) -> int:
125
+ parser = argparse.ArgumentParser(prog="cf_task_index.py")
126
+ parser.add_argument("--task-file", required=True)
127
+ parser.add_argument("--dag", action="store_true", help="输出拓扑批次与独立分组")
128
+ parser.add_argument("--json", action="store_true")
129
+ args = parser.parse_args(argv)
130
+ try:
131
+ data = index_data(args.task_file)
132
+ except (OSError, ValueError) as exc:
133
+ stdout.write(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False))
134
+ return 2
135
+ if args.json or args.dag:
136
+ stdout.write(json.dumps(data, ensure_ascii=False))
137
+ else:
138
+ lines = ["TASK 索引:"]
139
+ for item in data["tasks"]:
140
+ lines.append(f" - {item['id']}: {item['status']} (依赖: {', '.join(item['depends']) or '无'})")
141
+ for index, batch in enumerate(data["batches"], 1):
142
+ lines.append(f"批次 {index}(可独立开发): {', '.join(batch)}")
143
+ stdout.write("\n".join(lines) + "\n")
144
+ return 0
145
+
146
+
147
+ if __name__ == "__main__":
148
+ raise SystemExit(main())
@@ -0,0 +1,385 @@
1
+ #!/usr/bin/env python3
2
+ """Task-level worktree orchestration for parallel batch execution.
3
+
4
+ `cf-task:start` 整文件模式对拓扑批次内的独立 TASK 并行派发子 agent 时,本脚本
5
+ 负责可测试的确定性步骤,子 agent 派发与合并冲突解决仍由命令提示词编排:
6
+
7
+ prepare 预检(git 仓库 / worktree 忽略规则 / 无 active marker / tracked 干净)
8
+ → 自动提交仅位于需求目录内的流程产物 → 校验任务可并行 → 建 worktree+分支
9
+ collect 回并前校验:改动已提交、Status 已 done/verified、marker 已清理
10
+ cleanup 合并完成后移除 worktree;已合入的分支一并删除,未合入的保留可追溯
11
+
12
+ 协议(详见 cf-task:start 命令正文):
13
+ - worktree: .code-flow/worktrees/<run-id>/<TASK-ID>/
14
+ - branch: cf-task/<slug>/<run-id>/<TASK-ID>
15
+ - 元数据: .code-flow/worktrees/<run-id>/run.json(base head / 任务清单)
16
+
17
+ stdout 始终为 JSON:{"ok": true, ...} 或 {"ok": false, "code": ..., "message": ...}。
18
+ 预检失败时命令方回退串行,不得手工绕过本脚本建 worktree/分支。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ from datetime import datetime
29
+ from pathlib import Path
30
+ from typing import IO, Optional, Sequence
31
+
32
+ from cf_task_index import parse_task_file
33
+ from cf_task_index import task_batches
34
+ from cf_task_state import FINISHED_STATUSES
35
+
36
+
37
+ WORKTREES_DIR = ".code-flow/worktrees"
38
+ MARKER = ".code-flow/.active-task.json"
39
+ GITIGNORE = ".code-flow/.gitignore"
40
+ _RUN_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
41
+ _TASK_ID = re.compile(r"^TASK-\d+$")
42
+
43
+
44
+ class ParallelError(ValueError):
45
+ """Precondition or protocol violation with a stable machine code."""
46
+
47
+ def __init__(self, code: str, message: str) -> None:
48
+ super().__init__(message)
49
+ self.code = code
50
+ self.message = message
51
+
52
+
53
+ def _run_git(root: Path, arguments: Sequence[str]) -> str:
54
+ result = subprocess.run(
55
+ ("git", *arguments), cwd=str(root), text=True, encoding="utf-8", capture_output=True, check=False
56
+ )
57
+ if result.returncode != 0:
58
+ message = result.stderr.strip() or "Git command failed"
59
+ raise ParallelError("git_error", message)
60
+ return result.stdout
61
+
62
+
63
+ def _assert_repo(root: Path) -> None:
64
+ try:
65
+ top = _run_git(root, ("rev-parse", "--show-toplevel")).strip()
66
+ except ParallelError as exc:
67
+ raise ParallelError("git_unavailable", "并行执行需要 git 仓库") from exc
68
+ if Path(top).resolve() != root:
69
+ raise ParallelError("not_project_root", f"root 必须是仓库根目录: {top}")
70
+
71
+
72
+ def _status_paths(root: Path) -> list[str]:
73
+ output = _run_git(root, ("status", "--porcelain=v1", "-z", "--untracked-files=all"))
74
+ tokens = output.split("\0")
75
+ paths: list[str] = []
76
+ index = 0
77
+ while index < len(tokens) and tokens[index]:
78
+ record = tokens[index]
79
+ if len(record) < 4:
80
+ raise ParallelError("invalid_git_status", record)
81
+ code, path = record[:2], record[3:]
82
+ paths.append(path)
83
+ if code[:1] in ("R", "C"):
84
+ if index + 1 < len(tokens) and tokens[index + 1]:
85
+ paths.append(tokens[index + 1])
86
+ index += 2
87
+ else:
88
+ index += 1
89
+ return paths
90
+
91
+
92
+ def _require_ignored(root: Path) -> None:
93
+ ignore = root / GITIGNORE
94
+ try:
95
+ text = ignore.read_text(encoding="utf-8")
96
+ except OSError as exc:
97
+ raise ParallelError("worktrees_not_ignored", f"缺少 {GITIGNORE}: {exc}") from exc
98
+ if "worktrees/" not in text.split():
99
+ raise ParallelError(
100
+ "worktrees_not_ignored", f"{GITIGNORE} 缺少 worktrees/ 规则,请先运行 code-flow init 升级"
101
+ )
102
+
103
+
104
+ def _require_no_active(root: Path) -> None:
105
+ if (root / MARKER).exists():
106
+ raise ParallelError("active_exists", "主 worktree 已有 active TASK,先 finish/doctor 后再并行")
107
+
108
+
109
+ def _commit_task_dir(root: Path, task_file: str) -> Optional[str]:
110
+ task_dir = Path(task_file).parent
111
+ entries = _status_paths(root)
112
+ outside = [
113
+ path
114
+ for path in entries
115
+ if not (path == str(task_dir) or path.startswith(f"{task_dir}/"))
116
+ ]
117
+ if outside:
118
+ sample = ", ".join(outside[:8]) + (" ..." if len(outside) > 8 else "")
119
+ raise ParallelError(
120
+ "dirty_tree",
121
+ "并行要求 tracked 工作区干净(需求目录以外仍有改动: "
122
+ f"{sample})。请先提交(git add -A && git commit -m 'wip')"
123
+ "或暂存(git stash push -u)后重试;需求目录内的流程产物会自动提交。",
124
+ )
125
+ if not entries:
126
+ return None
127
+ _run_git(root, ("add", "-A", "--", str(task_dir)))
128
+ _run_git(root, ("commit", "-q", "-m", f"chore(cf-task): plan {Path(task_file).stem}"))
129
+ return _run_git(root, ("rev-parse", "HEAD")).strip()
130
+
131
+
132
+ def _validate_batch(root: Path, task_file: str, tasks: Sequence[str]) -> str:
133
+ path = root / task_file
134
+ if not path.is_file():
135
+ raise ParallelError("task_file_missing", f"任务文件不存在: {task_file}")
136
+ try:
137
+ nodes = parse_task_file(str(path))
138
+ except ValueError as exc:
139
+ raise ParallelError("task_parse_error", str(exc)) from exc
140
+ by_id = {node.task_id: node for node in nodes}
141
+ for task in tasks:
142
+ if task not in by_id:
143
+ raise ParallelError("unknown_task", f"{task} 不在任务文件中")
144
+ if by_id[task].status != "draft":
145
+ raise ParallelError("task_not_draft", f"{task} 当前 Status 为 {by_id[task].status},不可并行激活")
146
+ try:
147
+ ready = task_batches(nodes)[0]
148
+ except ValueError as exc:
149
+ raise ParallelError("task_graph_error", str(exc)) from exc
150
+ not_ready = [task for task in tasks if task not in ready]
151
+ if not_ready:
152
+ raise ParallelError("task_not_ready", f"依赖未完成,本批不可激活: {', '.join(not_ready)}(可激活: {', '.join(ready)})")
153
+ return str(path)
154
+
155
+
156
+ def _branch_slug(task_file: str) -> str:
157
+ stem = Path(task_file).stem
158
+ slug = re.sub(r"[^A-Za-z0-9._-]+", "-", stem).strip("-._")
159
+ return slug[:40] or "batch"
160
+
161
+
162
+ def _worktree_paths(root: Path, run_id: str, task: str, task_file: str) -> tuple[Path, str]:
163
+ branch = f"cf-task/{_branch_slug(task_file)}/{run_id}/{task}"
164
+ return root / WORKTREES_DIR / run_id / task, branch
165
+
166
+
167
+ def _run_id() -> str:
168
+ return datetime.now().strftime("%Y%m%d-%H%M%S")
169
+
170
+
171
+ def _write_run_meta(run_dir: Path, payload: dict[str, object]) -> None:
172
+ run_dir.mkdir(parents=True, exist_ok=True)
173
+ (run_dir / "run.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
174
+
175
+
176
+ def _read_run_meta(root: Path, run_id: str) -> dict[str, object]:
177
+ meta = root / WORKTREES_DIR / run_id / "run.json"
178
+ try:
179
+ return json.loads(meta.read_text(encoding="utf-8"))
180
+ except (OSError, json.JSONDecodeError) as exc:
181
+ raise ParallelError("run_not_found", f"找不到并行记录 {meta}: {exc}") from exc
182
+
183
+
184
+ def _create_worktrees(root: Path, task_file: str, tasks: Sequence[str], run_id: str) -> dict[str, object]:
185
+ created: list[tuple[Path, str]] = []
186
+ base_head = _run_git(root, ("rev-parse", "HEAD")).strip()
187
+ try:
188
+ for task in tasks:
189
+ path, branch = _worktree_paths(root, run_id, task, task_file)
190
+ if path.exists() or _branch_exists(root, branch):
191
+ raise ParallelError("worktree_exists", f"{task} 的 worktree 或分支已存在: {branch}")
192
+ path.parent.mkdir(parents=True, exist_ok=True)
193
+ _run_git(root, ("worktree", "add", "-b", branch, str(path), "HEAD"))
194
+ if not (path / task_file).is_file():
195
+ raise ParallelError("task_file_missing", f"{task}: worktree 内缺少 {task_file}(需先提交任务文件)")
196
+ created.append((path, branch))
197
+ except ParallelError:
198
+ for path, branch in created:
199
+ _remove_worktree(root, path, force=True)
200
+ _run_git(root, ("branch", "-D", branch))
201
+ raise
202
+ return {"base_head": base_head, "created": created}
203
+
204
+
205
+ def _branch_exists(root: Path, branch: str) -> bool:
206
+ result = subprocess.run(
207
+ ("git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"),
208
+ cwd=str(root), capture_output=True, check=False,
209
+ )
210
+ return result.returncode == 0
211
+
212
+
213
+ def _delete_branch(root: Path, branch: str) -> bool:
214
+ result = subprocess.run(
215
+ ("git", "branch", "-d", branch), cwd=str(root), capture_output=True, check=False,
216
+ )
217
+ return result.returncode == 0
218
+
219
+
220
+ def _remove_worktree(root: Path, path: Path, force: bool) -> None:
221
+ arguments = ["worktree", "remove"]
222
+ if force:
223
+ arguments.append("--force")
224
+ arguments.append(str(path))
225
+ _run_git(root, tuple(arguments))
226
+
227
+
228
+ def _relative_task_file(root: Path, task_file: str) -> str:
229
+ candidate = Path(task_file)
230
+ absolute = candidate if candidate.is_absolute() else root / candidate
231
+ try:
232
+ return str(absolute.resolve().relative_to(root))
233
+ except ValueError as exc:
234
+ raise ParallelError("task_file_outside_root", f"任务文件不在仓库内: {task_file}") from exc
235
+
236
+
237
+ def prepare(root: Path, task_file: str, tasks: Sequence[str], run_id: Optional[str]) -> dict[str, object]:
238
+ root = root.resolve()
239
+ _assert_repo(root)
240
+ task_file = _relative_task_file(root, task_file)
241
+ _require_ignored(root)
242
+ _require_no_active(root)
243
+ identifier = run_id or _run_id()
244
+ if not _RUN_ID.match(identifier):
245
+ raise ParallelError("invalid_run_id", f"run-id 非法: {identifier}")
246
+ if not tasks:
247
+ raise ParallelError("no_tasks", "未指定并行 TASK")
248
+ if len(set(tasks)) != len(tasks):
249
+ raise ParallelError("duplicate_task", "并行 TASK 列表存在重复")
250
+ for task in tasks:
251
+ if not _TASK_ID.match(task):
252
+ raise ParallelError("invalid_task_id", f"TASK-ID 非法: {task}")
253
+ _validate_batch(root, task_file, tasks)
254
+ _commit_task_dir(root, task_file)
255
+ outcome = _create_worktrees(root, task_file, tasks, identifier)
256
+ worktrees = [
257
+ {"task": task, "branch": branch, "path": str(path)}
258
+ for task, (path, branch) in zip(tasks, outcome["created"])
259
+ ]
260
+ _write_run_meta(
261
+ root / WORKTREES_DIR / identifier,
262
+ {"version": 1, "run_id": identifier, "task_file": task_file,
263
+ "base_head": outcome["base_head"], "worktrees": worktrees},
264
+ )
265
+ return {"ok": True, "action": "prepare", "run_id": identifier, "task_file": task_file,
266
+ "base_head": outcome["base_head"], "worktrees": worktrees}
267
+
268
+
269
+ def _collect_one(root: Path, entry: dict[str, object], base_head: str, task_file: str) -> dict[str, object]:
270
+ task = str(entry["task"])
271
+ path = Path(str(entry["path"]))
272
+ branch = str(entry["branch"])
273
+ if not path.is_dir():
274
+ raise ParallelError("worktree_missing", f"{task}: worktree 不存在: {path}")
275
+ dirty = _status_paths(path)
276
+ if dirty:
277
+ raise ParallelError("worktree_dirty", f"{task}: 尚有未提交改动: {', '.join(dirty[:8])}")
278
+ if (path / MARKER).exists():
279
+ raise ParallelError("active_marker_present", f"{task}: marker 未清理,finish 未完成")
280
+ head = _run_git(path, ("rev-parse", "HEAD")).strip()
281
+ if head == base_head:
282
+ raise ParallelError("no_commits", f"{task}: worktree 无新提交")
283
+ try:
284
+ nodes = parse_task_file(str(path / task_file))
285
+ except ValueError as exc:
286
+ raise ParallelError("task_parse_error", f"{task}: {exc}") from exc
287
+ status = next((node.status for node in nodes if node.task_id == task), None)
288
+ if status not in FINISHED_STATUSES:
289
+ raise ParallelError("task_not_finished", f"{task}: Status 为 {status},未通过 Done Gate")
290
+ files = _run_git(root, ("diff", "--name-only", f"{base_head}..{branch}")).splitlines()
291
+ return {"task": task, "branch": branch, "path": str(path), "head": head,
292
+ "status": status, "files": sorted(item for item in files if item)}
293
+
294
+
295
+ def collect(root: Path, run_id: str, tasks: Optional[Sequence[str]]) -> dict[str, object]:
296
+ root = root.resolve()
297
+ meta = _read_run_meta(root, run_id)
298
+ entries = [item for item in meta.get("worktrees", []) if isinstance(item, dict)]
299
+ if tasks:
300
+ wanted = set(tasks)
301
+ entries = [item for item in entries if item.get("task") in wanted]
302
+ results: list[dict[str, object]] = []
303
+ for entry in entries:
304
+ try:
305
+ results.append(_collect_one(root, entry, str(meta["base_head"]), str(meta["task_file"])))
306
+ except ParallelError as exc:
307
+ results.append({"task": str(entry.get("task", "")), "ok": False, "code": exc.code, "message": exc.message})
308
+ ok = bool(results) and all(item.get("code") is None for item in results)
309
+ return {"ok": ok, "action": "collect", "run_id": run_id, "results": results}
310
+
311
+
312
+ def cleanup(root: Path, run_id: str, force: bool) -> dict[str, object]:
313
+ root = root.resolve()
314
+ meta = _read_run_meta(root, run_id)
315
+ results: list[dict[str, object]] = []
316
+ for item in meta.get("worktrees", []):
317
+ if not isinstance(item, dict):
318
+ continue
319
+ path = Path(str(item.get("path", "")))
320
+ if not path.exists():
321
+ results.append({"task": item.get("task"), "removed": False, "reason": "already_absent"})
322
+ continue
323
+ try:
324
+ _require_clean_for_removal(path, force)
325
+ _remove_worktree(root, path, force)
326
+ branch = str(item.get("branch", ""))
327
+ merged = _delete_branch(root, branch) if branch else False
328
+ results.append({"task": item.get("task"), "removed": True, "branch_deleted": merged})
329
+ except ParallelError as exc:
330
+ results.append({"task": item.get("task"), "removed": False, "code": exc.code, "message": exc.message})
331
+ _run_git(root, ("worktree", "prune"))
332
+ run_dir = root / WORKTREES_DIR / run_id
333
+ if run_dir.is_dir() and not any(child.is_dir() for child in run_dir.iterdir()):
334
+ (run_dir / "run.json").unlink(missing_ok=True)
335
+ run_dir.rmdir()
336
+ ok = all(item.get("removed") or item.get("reason") == "already_absent" for item in results)
337
+ return {"ok": ok, "action": "cleanup", "run_id": run_id, "results": results}
338
+
339
+
340
+ def _require_clean_for_removal(path: Path, force: bool) -> None:
341
+ if force:
342
+ return
343
+ dirty = _status_paths(path)
344
+ if dirty:
345
+ raise ParallelError("worktree_dirty", f"worktree 有未提交改动: {', '.join(dirty[:8])}")
346
+
347
+
348
+ def _emit(payload: dict[str, object], stdout: IO[str]) -> None:
349
+ stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
350
+
351
+
352
+ def main(argv: Optional[Sequence[str]] = None, stdout: IO[str] = sys.stdout) -> int:
353
+ parser = argparse.ArgumentParser(prog="cf_task_parallel.py")
354
+ sub = parser.add_subparsers(dest="action", required=True)
355
+ for name in ("prepare", "collect", "cleanup"):
356
+ command = sub.add_parser(name)
357
+ command.add_argument("--root", default=".")
358
+ command.add_argument("--json", action="store_true")
359
+ prepare_parser = sub.choices["prepare"]
360
+ prepare_parser.add_argument("--task-file", required=True)
361
+ prepare_parser.add_argument("--tasks", required=True)
362
+ prepare_parser.add_argument("--run-id", default="")
363
+ for name in ("collect", "cleanup"):
364
+ sub.choices[name].add_argument("--run-id", required=True)
365
+ sub.choices["collect"].add_argument("--tasks", default="")
366
+ sub.choices["cleanup"].add_argument("--force", action="store_true")
367
+ args = parser.parse_args(argv)
368
+ root = Path(args.root).resolve()
369
+ try:
370
+ if args.action == "prepare":
371
+ tasks = [item.strip() for item in args.tasks.split(",") if item.strip()]
372
+ payload = prepare(root, args.task_file, tasks, args.run_id or None)
373
+ elif args.action == "collect":
374
+ tasks = [item.strip() for item in args.tasks.split(",") if item.strip()] or None
375
+ payload = collect(root, args.run_id, tasks)
376
+ else:
377
+ payload = cleanup(root, args.run_id, args.force)
378
+ except ParallelError as exc:
379
+ payload = {"ok": False, "action": args.action, "code": exc.code, "message": exc.message}
380
+ _emit(payload, stdout)
381
+ return 0 if payload.get("ok") else 2
382
+
383
+
384
+ if __name__ == "__main__":
385
+ raise SystemExit(main())