cowork-flow 2.7.3 → 2.7.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 (29) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/docs/direction.en.md +2 -1
  3. package/docs/direction.md +2 -1
  4. package/docs/team.en.md +3 -0
  5. package/docs/team.md +3 -0
  6. package/package.json +1 -1
  7. package/presets/claude-code/.claude-plugin/plugin.json +1 -1
  8. package/presets/codex/.codex-plugin/plugin.json +1 -1
  9. package/presets/kimi-code/.kimi-plugin/plugin.json +1 -1
  10. package/presets/qoder/.qoder-plugin/plugin.json +1 -1
  11. package/presets/zcode/.zcode-plugin/plugin.json +1 -1
  12. package/template/.cowork-flow/.version +1 -1
  13. package/template/.cowork-flow/scripts/adapters/cli/task_lifecycle_commands.py +1 -0
  14. package/template/.cowork-flow/scripts/adapters/cli/task_parser.py +4 -1
  15. package/template/.cowork-flow/scripts/infra/git_snapshot.py +17 -0
  16. package/template/.cowork-flow/scripts/services/plan_readiness.py +198 -32
  17. package/template/.cowork-flow/scripts/services/task_board.py +13 -0
  18. package/template/.cowork-flow/scripts/services/task_lease.py +63 -0
  19. package/template/.cowork-flow/scripts/services/task_lifecycle.py +113 -22
  20. package/template/.cowork-flow/spec/contracts/error-codes.md +1 -0
  21. package/template/.cowork-flow/spec/contracts/index.md +2 -2
  22. package/template/.cowork-flow/spec/contracts/plan-binding.md +4 -1
  23. package/template/.cowork-flow/spec/contracts/task-adopt.md +1 -0
  24. package/template/.cowork-flow/spec/contracts/task-board.md +1 -0
  25. package/template/.cowork-flow/spec/runtime/contract-registry.json +1 -0
  26. package/template/.cowork-flow/templates/plan-template.md +6 -0
  27. package/template/locales/en-US/.cowork-flow/templates/plan-template.md +6 -0
  28. package/template/skills/runtime-health/scripts/doctor.py +117 -41
  29. package/template/skills/task-planning/SKILL.md +2 -0
package/CHANGELOG.md CHANGED
@@ -6,6 +6,17 @@
6
6
 
7
7
  ### Changed
8
8
 
9
+ ## [2.7.4] - 2026-11-20
10
+
11
+ ### Added
12
+
13
+ - **分支锚定任务租约**:`task.json.meta.lease` 在 start 时记录 `executor`、`branch`、`head`、`at`;start 与 complete 在租约分支与当前分支都已知且不同时以 `LIFECYCLE-LEASE-001` 阻断,`--takeover`(start 迁移、complete 确认在当前分支完成并释放)与 `--adopt` 转移租约;`review` 保持不校验,无 git、detached HEAD 或 `lease.branch` 为 `null` 时不比较。看板(`task next --list --json` 与 MCP `task_list`)每条记录带 `lease` 四键对象或 `null`;`doctor` 对 `in_progress`/`review` 的跨分支租约报 `TASK-HYGIENE-LEASE-BRANCH-MISMATCH`。团队文档补一任务一分支与合并后的操作路径。
14
+ - **计划定稿派发决策**:strict Normal/High-risk 计划模板新增 `派发决策` 必填块(结论、依据、切片、研究问题),`plan finalize` 对缺失或保留占位阻断;`task-planning` 指导默认把可独立取证的研究问题派发给 `cowork-research`。
15
+
16
+ ### Changed
17
+
18
+ - **跨会话冲突模型方向记录**:`docs/direction.md` 与英文对页更新 2026-11-19 调研条目的落地状态——租约第一版(含 complete 校验与看板/doctor 可见性)已实现,`review` 保持不校验;租约信息进入注入模板暂缓,待真实跨分支误操作案例触发;剩余未决为租约过期语义、`task.json` 三方合并规则、显式 claim/release 命令与跨机器 handoff 合并。
19
+
9
20
  ## [2.7.3] - 2026-11-13
10
21
 
11
22
  ### Fixed
@@ -530,7 +541,8 @@
530
541
 
531
542
  此版本未保留本地条目正文,详情见 [GitHub Release](https://github.com/fishlikewater/cowork-flow/releases/tag/v0.0.47)。
532
543
 
533
- [Unreleased]: https://github.com/fishlikewater/cowork-flow/compare/v2.7.3...HEAD
544
+ [Unreleased]: https://github.com/fishlikewater/cowork-flow/compare/v2.7.4...HEAD
545
+ [2.7.4]: https://github.com/fishlikewater/cowork-flow/compare/v2.7.3...v2.7.4
534
546
  [2.7.3]: https://github.com/fishlikewater/cowork-flow/compare/v2.7.2...v2.7.3
535
547
  [2.7.2]: https://github.com/fishlikewater/cowork-flow/compare/v2.7.1...v2.7.2
536
548
  [2.7.1]: https://github.com/fishlikewater/cowork-flow/compare/v2.7.0...v2.7.1
@@ -2,7 +2,7 @@
2
2
 
3
3
  [中文](direction.md) | English
4
4
 
5
- > Status: **approved** · Created: 2026-08-27 · Last updated: 2026-11-10
5
+ > Status: **approved** · Created: 2026-08-27 · Last updated: 2026-11-20
6
6
  > This document is the authoritative input for starting later phases. Any revision to the direction must update this document first, then start the phase.
7
7
  > Implementation details and commit history for completed phases are in the [CHANGELOG](../CHANGELOG.md) (Chinese); this document keeps only the positioning, trade-offs, boundaries, and open items that still hold.
8
8
 
@@ -61,6 +61,7 @@ The test: a project's consumer is an agent, not a person. So injection formats,
61
61
  - 2026-10-21 (step one): the framework spec documentation shipped with the package is unified in English — `spec/index.md`, `spec/runtime/index.md`, `spec/schemas/index.md`, `spec/references/**`. The six parsed headings in `decision-anchor.md`, the injection block in `workflow-state-templates.md`, `backend/frontend/guides`, and `template/AGENTS.md` stay Chinese.
62
62
  - 2026-10-22 (step two): installation can choose `zh-CN` / `en-US`, written to the protected `.cowork-flow/config.yaml` and affecting only `decision-anchor.md` and plan artifacts. The parser permanently accepts both the Chinese and English heading sets; `decision-anchor.md` keeps the Chinese contract and adds an English variant, while `workflow-state-templates.md`, `AGENTS.md`, spec documents, and Skills are not localized by that option. `references/` is still protected by project sync, so an installed project needs a manual refresh to receive the English copies.
63
63
  - **Started (2026-11-10): team collaboration baseline.** 1.9.x addressed single-machine multi-executor facts; git-level fact consistency across multiple developers, branches, and worktrees becomes the next version line, limited to runtime ignore hygiene, dangling-binding degradation semantics, and team collaboration documentation; cross-branch boards and git hosting are out of scope.
64
+ - **Partly implemented (2026-11-19 research, first release 2026-11-20): the conflict model for cross-session and cross-worktree work.** Delivered: a **branch-anchored lightweight task lease** (`meta.lease` records executor, branch, and HEAD; acquired at start, moved by takeover/adopt, released at complete). Start and completion refuse a mismatch with `LIFECYCLE-LEASE-001` (completing from another branch needs `--takeover` to finish there and drop the lease), while `review` stays free of the check. The board and `doctor` expose the lease (`lease` field and `TASK-HYGIENE-LEASE-BRANCH-MISMATCH`) alongside the "one task, one branch" documentation rule; reusing path locks for cross-worktree ownership is deferred because it cannot span worktrees. Putting the lease into the injected workflow-state template is deferred until a real cross-branch mistake (advancing a task on the wrong branch unnoticed) or routine parallel-worktree use appears. Open questions: lease expiry semantics, the three-way `task.json` merge rule, whether explicit claim/release commands are added, and whether cross-machine handoff is folded into `--adopt`. Evidence: `.cowork-flow/plans/2026-11-19-cross-session-conflict-model-research.md` in the local workspace (that directory is ignored and not distributed with the package; it is a research archive only).
64
65
  - **Still deferred**: MCP write tools (the `fact-layer-access` contract must be reopened first), new host integrations, and a home-grown cross-agent protocol.
65
66
  - **Watch item (trigger reached)**: machine-parseable ACs are the first building block for interoperability with Spec Kit / OpenSpec (spec artifacts ↔ decision-anchor mapping), and fit the "state layer beneath SDD tools" positioning. It was originally "to be discussed once the agent-teams schedule is settled"; since the 1.9.0 multi-executor collaboration mainline is already implemented, it can be put on the discussion schedule.
66
67
 
package/docs/direction.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](direction.en.md) | 中文
4
4
 
5
- > 状态:**已批准** · 创建:2026-08-27 · 最近更新:2026-11-10
5
+ > 状态:**已批准** · 创建:2026-08-27 · 最近更新:2026-11-20
6
6
  > 本文档是后续阶段立项的权威输入。任何方向的修订必须先更新本文档,再立项。
7
7
  > 已完成阶段的实施细节与提交记录见 [CHANGELOG](../CHANGELOG.md);本文只保留仍然生效的定位、取舍、边界和待决项。
8
8
 
@@ -61,6 +61,7 @@
61
61
  - 2026-10-21(第一步):随包分发的框架 spec 说明文档统一为英文——`spec/index.md`、`spec/runtime/index.md`、`spec/schemas/index.md`、`spec/references/**`。`decision-anchor.md` 的六个解析标题、`workflow-state-templates.md` 的注入块、`backend/frontend/guides` 与 `template/AGENTS.md` 仍为中文。
62
62
  - 2026-10-22(第二步):安装时可选择 `zh-CN` / `en-US`,写入受保护的 `.cowork-flow/config.yaml`,只影响 `decision-anchor.md` 与计划产物。解析器永久接受中英两套标题;`decision-anchor.md` 保留中文合同并新增英文变体,`workflow-state-templates.md`、`AGENTS.md`、spec 文档与 Skill 不随该选项本地化。`references/` 仍受项目同步保护,已装项目需手动刷新才能拿到英文副本。
63
63
  - **已立项(2026-11-10):团队协作基线。** 1.9.x 解决了单机多执行者事实;多开发者、多分支与 worktree 场景下 git 层的事实一致性作为下一版本线,范围限定为运行时忽略卫生、悬空绑定降级语义与团队协作文档;跨分支看板与 git 托管不做。
64
+ - **部分落地(2026-11-19 调研,2026-11-20 第一版发布):跨会话与跨 worktree 的冲突模型。** 落地内容:**分支锚定的轻量任务租约**(`meta.lease` 记录 executor、分支与 HEAD;start 获取、takeover/adopt 转移、complete 释放),start 与 complete 在租约分支与当前分支冲突时以 `LIFECYCLE-LEASE-001` 阻断(complete 跨分支需加 `--takeover` 确认在当前分支完成并释放),`review` 保持不校验;看板与 `doctor` 暴露租约(`lease` 字段与 `TASK-HYGIENE-LEASE-BRANCH-MISMATCH`),配合「一任务一分支」的文档约定;路径锁复用因无法覆盖跨 worktree 而缓行。租约信息进入注入模板暂缓:待真实跨分支误操作案例(在非租约分支推进任务且未被察觉)或 worktree 并行成为常态时再启动。未决:租约过期语义、`task.json` 三方合并规则、是否新增显式 claim/release 命令、跨机器 handoff 是否与 `--adopt` 合并为一个动作。证据见本地工作区的 `.cowork-flow/plans/2026-11-19-cross-session-conflict-model-research.md`(该目录被忽略、不随包分发,仅作调研存档)。
64
65
  - **维持缓行**:MCP 写工具(须先重开 `fact-layer-access` 契约)、新宿主接入、自创跨 agent 协议。
65
66
  - **观察项(触发条件已到)**:机器可解析 AC 是与 Spec Kit / OpenSpec 互操作的第一块砖(spec 制品 ↔ decision-anchor 映射),符合「SDD 工具之下的状态层」定位。原定「待 agent-teams 排期落定后议」,而 1.9.0 多执行者协作主线已实现,可排入讨论。
66
67
 
package/docs/team.en.md CHANGED
@@ -17,6 +17,9 @@ When several people, branches, or worktrees use cowork-flow together, task state
17
17
  - Rebind: after returning to the branch that contains the task, run `./.cowork-flow/run task next <task-dir>`; or pick an existing task with `task next --list`.
18
18
  - Each worktree has its own `.runtime/`, so session bindings, locks, and state snapshots are not shared; task files follow each worktree's checked-out branch.
19
19
  - Do not advance the same task in parallel worktrees: different checkouts hold different copies of `task.json`, and runtime locks only protect a single working tree.
20
+ - Task lease: `task.json.meta.lease` records where the task was last started (`executor`, `branch`, `head`, `at`). It answers "which branch owns this task" as a queryable fact, not a lock; `complete` releases it, and completing from another branch is refused unless `--takeover` confirms completing there and dropping the lease. The board (`task next --list --json` and MCP `task_list`) carries a `lease` field per task, and `doctor` warns with `TASK-HYGIENE-LEASE-BRANCH-MISMATCH` for in-progress or review (`in_progress`/`review`) tasks when the current branch differs from the lease branch.
21
+ - Starting the same task from another branch is refused with `LIFECYCLE-LEASE-001`; when the move is intended, pass `--takeover` at start or use `--adopt` for an active task, and the lease is rewritten to the current branch and HEAD. Without git or on detached HEAD, branches are not compared (`lease.branch` stays `null`), so CI keeps working.
22
+ - Working rule: **one task, one branch**. Start different tasks for parallel work; after merging a task branch, keep the lease that matches the target branch and `--adopt` on that branch to continue; completing on that branch directly needs `--adopt` first, or `--takeover` on `complete`.
20
23
  - To advance several tasks in parallel, coordinate through the task board (`task next --list --json`) and dependencies (`--depends-on`), then converge after merging.
21
24
 
22
25
  ## executor vs assignee
package/docs/team.md CHANGED
@@ -17,6 +17,9 @@
17
17
  - 重新绑定:回到包含任务的分支后运行 `./.cowork-flow/run task next <task-dir>`;或用 `task next --list` 选一个已存在的任务。
18
18
  - 每个 worktree 有独立的 `.runtime/`,会话绑定、锁与状态快照不共享;任务文件随各 worktree 的检出分支变化。
19
19
  - 同一任务不要在多个 worktree 并行推进:不同检出的 `task.json` 是不同副本,运行时锁只保护单个工作区。
20
+ - 任务租约:`task.json.meta.lease` 记录任务上次在哪个分支启动(`executor`、`branch`、`head`、`at`)。它回答“这个任务属于哪个分支”,是可查询事实,不是锁;`complete` 时释放,在另一分支 `complete` 会被拒绝,除非加 `--takeover`(表示在当前分支完成并释放租约)。看板(`task next --list --json` 与 MCP `task_list`)每条任务带 `lease` 字段;对进行中或评审中(`in_progress`/`review`)的任务,`doctor` 在当前分支与租约分支不一致时给出 `TASK-HYGIENE-LEASE-BRANCH-MISMATCH` 警告。
21
+ - 同一任务在另一分支启动会被 `LIFECYCLE-LEASE-001` 拒绝;确认要迁移时,start 加 `--takeover`、进行中的任务用 `--adopt`,租约会随后按当前分支与 HEAD 重写。无 git 或 detached HEAD 时不比较分支(`lease.branch` 为 `null`),CI 不受影响。
22
+ - 实践约定 **一任务一分支**:需要并行时开不同任务;任务分支合并后,保留与目标分支一致的那份租约,另一方在合并后的分支上 `--adopt` 再继续;若直接在该分支 `complete`,需先 `--adopt` 或加 `--takeover`。
20
23
  - 需要并行推进多个任务时,用任务看板(`task next --list --json`)和依赖(`--depends-on`)协调,合并后再统一推进。
21
24
 
22
25
  ## executor 与 assignee
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cowork-flow",
3
- "version": "2.7.3",
3
+ "version": "2.7.4",
4
4
  "description": "CLI for installing and maintaining cowork-flow collaboration templates.",
5
5
  "keywords": [
6
6
  "ai-agent",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cowork-flow",
3
- "version": "2.7.3",
3
+ "version": "2.7.4",
4
4
  "description": "AI 协作工作流引擎:任务生命周期、子代理调度、门禁与状态注入。将 cowork-flow 的完整工作流带入 Claude Code。",
5
5
  "displayName": "Cowork Flow",
6
6
  "author": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cowork-flow",
3
- "version": "2.7.3",
3
+ "version": "2.7.4",
4
4
  "description": "AI 协作工作流引擎:任务生命周期、子代理调度、门禁与状态注入。将 cowork-flow 的完整工作流带入 Codex。",
5
5
  "author": {
6
6
  "name": "fishlikewater",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cowork-flow",
3
- "version": "2.7.3",
3
+ "version": "2.7.4",
4
4
  "description": "AI 协作工作流引擎:任务生命周期、子代理调度、门禁与状态注入。将 cowork-flow 的完整工作流带入 Kimi Code。",
5
5
  "author": {
6
6
  "name": "fishlikewater",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cowork-flow",
3
- "version": "2.7.3",
3
+ "version": "2.7.4",
4
4
  "description": "AI 协作工作流引擎:任务生命周期、子代理调度、门禁与状态注入。将 cowork-flow 的完整工作流带入 Qoder。",
5
5
  "displayName": "Cowork Flow",
6
6
  "author": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cowork-flow",
3
- "version": "2.7.3",
3
+ "version": "2.7.4",
4
4
  "description": "AI 协作工作流引擎:任务生命周期、子代理调度、门禁与状态注入。将 cowork-flow 的完整工作流带入 ZCode。",
5
5
  "author": {
6
6
  "name": "fishlikewater",
@@ -1 +1 @@
1
- 2.7.3
1
+ 2.7.4
@@ -444,6 +444,7 @@ def cmd_complete(args: argparse.Namespace) -> int:
444
444
  allow_missing_evidence=bool(
445
445
  getattr(args, "allow_missing_evidence", False)
446
446
  ),
447
+ takeover=bool(getattr(args, "takeover", False)),
447
448
  )
448
449
  if not result.ok:
449
450
  if result.code == "LIFECYCLE-TRANSITION-001":
@@ -196,7 +196,10 @@ def _add_next_runtime_inputs(parser: argparse.ArgumentParser) -> None:
196
196
  parser.add_argument(
197
197
  "--takeover",
198
198
  action="store_true",
199
- help="Take the task over from its current executor on start_task",
199
+ help=(
200
+ "Take the task over from its current executor on start_task, or "
201
+ "confirm completing a task leased to another branch"
202
+ ),
200
203
  )
201
204
  parser.add_argument(
202
205
  "--adopt",
@@ -91,6 +91,23 @@ def current_head(repo_root: Path) -> str | None:
91
91
  return value or None
92
92
 
93
93
 
94
+ def current_branch(repo_root: Path) -> str | None:
95
+ """Branch name of this checkout, or None on detached HEAD or no git.
96
+
97
+ A detached HEAD resolves to the literal 'HEAD'; callers that compare
98
+ branches must treat that as unknown rather than as a branch named HEAD.
99
+ """
100
+ rc, stdout, _ = _run_git_command(
101
+ ["rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_root
102
+ )
103
+ if rc != 0:
104
+ return None
105
+ value = stdout.strip()
106
+ if not value or value == "HEAD":
107
+ return None
108
+ return value
109
+
110
+
94
111
  def _run_git_command(args: list[str], cwd: Path | None = None) -> tuple[int, str, str]:
95
112
  try:
96
113
  completed = subprocess.run(
@@ -42,8 +42,38 @@ TASK_HEADING_RE = re.compile(r"^###\s+(?:任务|Task)\s+\d+\s*[::]\s*(.+?)\s*$
42
42
  H2_RE = re.compile(r"^##(?!#)\s+(.+?)\s*$")
43
43
  BOLD_LABEL_RE = re.compile(r"^\*\*(.+?)\*\*\s*$")
44
44
  FENCE_RE = re.compile(r"^(```|~~~)")
45
+ OWNED_PATH_RE = re.compile(r"`([^`]+)`")
46
+ PATH_EXT_RE = re.compile(r"\.\w{1,6}$")
47
+ DECISION_TRAILING = "。..,,;;::"
45
48
  PLAN_TEMPLATE_PATH = f"{DIR_WORKFLOW}/templates/plan-template.md"
46
49
 
50
+ DISPATCH_DECISION_FIELD = {
51
+ "zh-CN": "派发决策",
52
+ "en-US": "Dispatch Decision",
53
+ }
54
+ DISPATCH_DECISION_LABELS = {
55
+ "zh-CN": {
56
+ "decision": "结论",
57
+ "rationale": "依据",
58
+ "slice": "切片",
59
+ "questions": "研究问题",
60
+ "no_dispatch": "不派发",
61
+ "research": "派发研究",
62
+ "implement": "派发实现",
63
+ "both": "派发研究与实现",
64
+ },
65
+ "en-US": {
66
+ "decision": "Decision",
67
+ "rationale": "Rationale",
68
+ "slice": "Slice",
69
+ "questions": "Research questions",
70
+ "no_dispatch": "No dispatch",
71
+ "research": "Research dispatch",
72
+ "implement": "Implement dispatch",
73
+ "both": "Research and implement dispatch",
74
+ },
75
+ }
76
+
47
77
  TASK_FIELDS = {
48
78
  "zh-CN": (
49
79
  "目的",
@@ -51,6 +81,7 @@ TASK_FIELDS = {
51
81
  "文件边界",
52
82
  "关键符号",
53
83
  "热点与改动形状",
84
+ "派发决策",
54
85
  "实现说明",
55
86
  "测试证明",
56
87
  "验证命令",
@@ -64,6 +95,7 @@ TASK_FIELDS = {
64
95
  "File Boundaries",
65
96
  "Key Symbols",
66
97
  "Hotspot and Change Shape",
98
+ "Dispatch Decision",
67
99
  "Implementation Notes",
68
100
  "Test Proof",
69
101
  "Verification Command",
@@ -302,54 +334,184 @@ def _task_block_blockers(
302
334
  language: str,
303
335
  template_fields: dict[str, list[str]],
304
336
  ) -> list[str]:
305
- blockers: list[str] = []
306
337
  tiny = declares_light_profile(task_data)
307
338
  required_fields = TINY_TASK_FIELDS.get(
308
339
  language, TINY_TASK_FIELDS["zh-CN"]
309
340
  ) if tiny else TASK_FIELDS.get(
310
341
  language, TASK_FIELDS["zh-CN"]
311
342
  )
312
- missing_template_fields = [
313
- field for field in required_fields if field not in template_fields
314
- ]
315
- if missing_template_fields:
316
- blockers.append(
317
- "installed plan template is missing task brief field(s): "
318
- + ", ".join(missing_template_fields)
319
- )
320
343
  verification_field = (
321
344
  "Verification Command"
322
345
  if language == "en-US"
323
346
  else "验证命令"
324
347
  )
348
+ blockers = _template_field_blockers(required_fields, template_fields)
325
349
  for block in task_blocks:
326
- fields = _task_fields(block["lines"])
327
- missing = [
328
- field for field in required_fields if field not in fields
350
+ blockers.extend(
351
+ _task_brief_blockers(
352
+ block,
353
+ required_fields,
354
+ verification_field,
355
+ tiny,
356
+ language,
357
+ template_fields,
358
+ )
359
+ )
360
+ return blockers
361
+
362
+
363
+ def _template_field_blockers(
364
+ required_fields: tuple[str, ...],
365
+ template_fields: dict[str, list[str]],
366
+ ) -> list[str]:
367
+ missing = [field for field in required_fields if field not in template_fields]
368
+ if not missing:
369
+ return []
370
+ return [
371
+ "installed plan template is missing task brief field(s): "
372
+ + ", ".join(missing)
373
+ ]
374
+
375
+
376
+ def _task_brief_blockers(
377
+ block: dict,
378
+ required_fields: tuple[str, ...],
379
+ verification_field: str,
380
+ tiny: bool,
381
+ language: str,
382
+ template_fields: dict[str, list[str]],
383
+ ) -> list[str]:
384
+ heading = block["heading"]
385
+ fields = _task_fields(block["lines"])
386
+ missing = [field for field in required_fields if field not in fields]
387
+ if missing:
388
+ return [
389
+ f"plan task `### {heading}` is missing brief "
390
+ f"field(s): {', '.join(missing)}"
329
391
  ]
330
- if missing:
331
- blockers.append(
332
- f"plan task `### {block['heading']}` is missing brief "
333
- f"field(s): {', '.join(missing)}"
392
+ empty = [
393
+ field
394
+ for field in required_fields
395
+ if (
396
+ not _has_verification_command(fields[field])
397
+ if field == verification_field
398
+ else not _has_meaningful_lines(
399
+ fields[field], template_fields.get(field, [])
334
400
  )
401
+ )
402
+ ]
403
+ if empty:
404
+ return [
405
+ f"plan task `### {heading}` has empty brief "
406
+ f"field(s): {', '.join(empty)}"
407
+ ]
408
+ dispatch_field = DISPATCH_DECISION_FIELD.get(
409
+ language, DISPATCH_DECISION_FIELD["zh-CN"]
410
+ )
411
+ if not tiny and dispatch_field in fields:
412
+ return _dispatch_decision_blockers(
413
+ fields[dispatch_field],
414
+ language,
415
+ heading,
416
+ template_fields.get(dispatch_field, []),
417
+ )
418
+ return []
419
+
420
+
421
+ def _labeled_value(
422
+ lines: list[str],
423
+ label: str,
424
+ template_lines: list[str] | tuple[str, ...] = (),
425
+ ) -> str | None:
426
+ """First concrete value after `label:` / `label:`, skipping template lines.
427
+
428
+ A value that only echoes the installed template is not a decision, so the
429
+ template body is excluded before matching."""
430
+ template = {
431
+ normalized
432
+ for raw in template_lines
433
+ if (normalized := _normalize_placeholder_line(raw.strip()))
434
+ }
435
+ for raw in lines:
436
+ body = _normalize_placeholder_line(raw.strip())
437
+ if not body or body in template:
335
438
  continue
336
- empty = [
337
- field
338
- for field in required_fields
339
- if (
340
- not _has_verification_command(fields[field])
341
- if field == verification_field
342
- else not _has_meaningful_lines(
343
- fields[field], template_fields.get(field, [])
344
- )
439
+ for separator in (":", ":"):
440
+ prefix = f"{label}{separator}"
441
+ if body.startswith(prefix):
442
+ return body[len(prefix):].strip()
443
+ return None
444
+
445
+
446
+ def _dispatch_kind(value: str, labels: dict[str, str]) -> str | None:
447
+ """Map a decision value to no_dispatch / research / implement / both.
448
+
449
+ The value must be exactly one decision token (trailing punctuation is
450
+ tolerated). A copied option menu is not a decision, so a prefix match is
451
+ deliberately not enough."""
452
+ normalized = value.strip().rstrip(DECISION_TRAILING).strip()
453
+ for kind in ("both", "implement", "research", "no_dispatch"):
454
+ if normalized == labels[kind]:
455
+ return kind
456
+ return None
457
+
458
+
459
+ def _has_owned_path(value: str) -> bool:
460
+ """Whether a slice line names at least one path-like owned path.
461
+
462
+ A backticked slice name alone is not ownership, so the token must look
463
+ like a repository path: it carries a separator or a file extension."""
464
+ for token in OWNED_PATH_RE.findall(value):
465
+ token = token.strip()
466
+ if "/" in token or "\\" in token or PATH_EXT_RE.search(token):
467
+ return True
468
+ return False
469
+
470
+
471
+ def _dispatch_decision_blockers(
472
+ lines: list[str],
473
+ language: str,
474
+ heading: str,
475
+ template_lines: list[str] | tuple[str, ...] = (),
476
+ ) -> list[str]:
477
+ """Structure check for the dispatch decision brief field.
478
+
479
+ The field records one decision per task: not dispatching, research
480
+ dispatch, implement dispatch, or both. Each branch needs its own evidence
481
+ line so the field cannot pass as a one-word answer."""
482
+ labels = DISPATCH_DECISION_LABELS.get(
483
+ language, DISPATCH_DECISION_LABELS["zh-CN"]
484
+ )
485
+ prefix = f"plan task `### {heading}` dispatch decision"
486
+ decision = _labeled_value(lines, labels["decision"], template_lines)
487
+ if decision is None:
488
+ return [f"{prefix} has no `{labels['decision']}` line"]
489
+ kind = _dispatch_kind(decision, labels)
490
+ if kind is None:
491
+ options = " / ".join(
492
+ labels[key]
493
+ for key in ("no_dispatch", "research", "implement", "both")
494
+ )
495
+ return [f"{prefix} `{labels['decision']}` must be one of: {options}"]
496
+ issues: list[str] = []
497
+ rationale = _labeled_value(lines, labels["rationale"], template_lines)
498
+ if not _has_concrete_text(rationale or ""):
499
+ issues.append(f"{prefix} needs a concrete `{labels['rationale']}` line")
500
+ if kind in ("implement", "both"):
501
+ slice_value = _labeled_value(lines, labels["slice"], template_lines)
502
+ if not _has_owned_path(slice_value or ""):
503
+ issues.append(
504
+ f"{prefix} implement dispatch needs a `{labels['slice']}` "
505
+ "line with a backticked owned path"
345
506
  )
346
- ]
347
- if empty:
348
- blockers.append(
349
- f"plan task `### {block['heading']}` has empty brief "
350
- f"field(s): {', '.join(empty)}"
507
+ if kind in ("research", "both"):
508
+ questions = _labeled_value(lines, labels["questions"], template_lines)
509
+ if not _has_concrete_text(questions or ""):
510
+ issues.append(
511
+ f"{prefix} research dispatch needs a concrete "
512
+ f"`{labels['questions']}` line"
351
513
  )
352
- return blockers
514
+ return issues
353
515
 
354
516
 
355
517
  def _anchor_artifact_blockers(
@@ -516,7 +678,11 @@ def _raw_section_lines(text: str, heading: str) -> list[str]:
516
678
 
517
679
  def _normalize_placeholder_line(line: str) -> str:
518
680
  """Strip list and code-comment markers before template-line comparison."""
519
- body = line[2:].strip() if line.startswith("- ") else line
681
+ body = line
682
+ for marker in ("- ", "* ", "+ "):
683
+ if body.startswith(marker):
684
+ body = body[2:].strip()
685
+ break
520
686
  body = body.lstrip("#> ").strip()
521
687
  return re.sub(r"\s+", " ", body)
522
688
 
@@ -49,6 +49,18 @@ def bound_task_paths(repo_root: Path) -> set[str]:
49
49
  return bound
50
50
 
51
51
 
52
+ def _lease_facts(task_data: dict) -> dict[str, object] | None:
53
+ """The recorded task lease, narrowed to the four board keys."""
54
+ meta = task_data.get("meta")
55
+ lease = meta.get("lease") if isinstance(meta, dict) else None
56
+ if not isinstance(lease, dict):
57
+ return None
58
+ return {
59
+ key: lease.get(key)
60
+ for key in ("executor", "branch", "head", "at")
61
+ }
62
+
63
+
52
64
  def board_facts(
53
65
  repo_root: Path,
54
66
  task_dir: Path,
@@ -78,6 +90,7 @@ def board_facts(
78
90
  "executor": executor,
79
91
  "ownerSessionActive": bool(executor) and relative_path in bound_paths,
80
92
  "evidenceCoverage": coverage_summary(task_dir),
93
+ "lease": _lease_facts(task_data),
81
94
  "blocked": bool(unresolved),
82
95
  "blockedBy": unresolved,
83
96
  }
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env python3
2
+ """Branch-anchored task lease facts for the task lifecycle.
3
+
4
+ The lease answers one question the rest of the state model cannot: on which
5
+ branch this task was last started. It is a fact, not a lock: the start
6
+ activation point and completion refuse a mismatch, and an explicit takeover
7
+ overrides that gate.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+
15
+ from infra import git_snapshot
16
+
17
+
18
+ LEASE_KEY = "lease"
19
+
20
+
21
+ def _now() -> str:
22
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
23
+
24
+
25
+ def record(meta: dict, *, repo_root: Path, executor: str) -> None:
26
+ """Write the lease for the branch this checkout is currently on.
27
+
28
+ branch stays None without git or on detached HEAD; head stays None only
29
+ when git is unavailable, because a detached HEAD still names a commit.
30
+ branch_conflict treats an unknown branch as no conflict so headless and
31
+ CI starts keep working.
32
+ """
33
+ meta[LEASE_KEY] = {
34
+ "executor": executor,
35
+ "branch": git_snapshot.current_branch(repo_root),
36
+ "head": git_snapshot.current_head(repo_root),
37
+ "at": _now(),
38
+ }
39
+
40
+
41
+ def release(meta: dict) -> bool:
42
+ """Drop the lease; returns True when one was present."""
43
+ return meta.pop(LEASE_KEY, None) is not None
44
+
45
+
46
+ def branch_conflict(task_data: dict, repo_root: Path) -> str | None:
47
+ """Blocker text when the recorded lease branch differs from this checkout.
48
+
49
+ Returns None when the task holds no lease, the lease records no branch
50
+ (start ran without git), or the current branch is unknown (detached HEAD).
51
+ """
52
+ meta = task_data.get("meta")
53
+ lease = meta.get(LEASE_KEY) if isinstance(meta, dict) else None
54
+ recorded = lease.get("branch") if isinstance(lease, dict) else None
55
+ if not isinstance(recorded, str) or not recorded:
56
+ return None
57
+ current = git_snapshot.current_branch(repo_root)
58
+ if not current or recorded == current:
59
+ return None
60
+ return (
61
+ f"task lease is held on branch '{recorded}', "
62
+ f"current branch is '{current}'"
63
+ )
@@ -24,6 +24,7 @@ from runtime.session_state import (
24
24
  is_delegated_session,
25
25
  )
26
26
  from infra.git_snapshot import current_head
27
+ from services import task_lease
27
28
  from services.lifecycle_checks import (
28
29
  LifecycleCheckResult,
29
30
  LifecycleCheckRunner,
@@ -64,6 +65,9 @@ COMPLETE_STAGE = LifecycleStage(
64
65
  records_completion_date=True,
65
66
  )
66
67
 
68
+ # Stages whose mutation is refused when the recorded lease names another branch.
69
+ LEASE_GUARDED_STAGES = (START_STAGE.name, COMPLETE_STAGE.name)
70
+
67
71
  # Adoption repairs ownership on an unfinished task; finished or unstarted
68
72
  # tasks have nothing to hand over.
69
73
  ADOPTABLE_STATUSES = ("in_progress", "review")
@@ -236,6 +240,7 @@ class TaskLifecycleService:
236
240
  allow_spec_file_modifications: bool | None = None,
237
241
  allow_missing_evidence: bool = False,
238
242
  execution_context: object | None = None,
243
+ takeover: bool = False,
239
244
  ) -> LifecycleResult:
240
245
  return self.execute(
241
246
  COMPLETE_STAGE,
@@ -244,6 +249,7 @@ class TaskLifecycleService:
244
249
  allow_spec_file_modifications=allow_spec_file_modifications,
245
250
  allow_missing_evidence=allow_missing_evidence,
246
251
  execution_context=execution_context,
252
+ takeover=takeover,
247
253
  )
248
254
 
249
255
  def execute(
@@ -342,13 +348,65 @@ class TaskLifecycleService:
342
348
  ),
343
349
  check_result=check_result,
344
350
  )
345
- return self._check_executor(
351
+ executor_failure = self._check_executor(
346
352
  stage,
347
353
  task_dir,
348
354
  task_data,
349
355
  executor,
350
356
  takeover,
351
357
  )
358
+ if executor_failure is not None:
359
+ return executor_failure
360
+ return self._check_lease(stage, task_dir, task_data, takeover)
361
+
362
+ def _check_lease(
363
+ self,
364
+ stage: LifecycleStage,
365
+ task_dir: Path,
366
+ task_data: dict,
367
+ takeover: bool,
368
+ ) -> LifecycleResult | None:
369
+ """Refuse a start or completion from a branch other than the lease's.
370
+
371
+ Review keeps its session-free semantics; an explicit takeover
372
+ overrides the gate on both guarded stages."""
373
+ if takeover or stage.name not in LEASE_GUARDED_STAGES:
374
+ return None
375
+ conflict = task_lease.branch_conflict(task_data, self.repo_root)
376
+ if conflict is None:
377
+ return None
378
+ return self._lease_failure(stage, task_dir, conflict)
379
+
380
+ def _lease_failure(
381
+ self,
382
+ stage: LifecycleStage,
383
+ task_dir: Path,
384
+ conflict: str,
385
+ ) -> LifecycleResult:
386
+ """Stage-specific lease blocker text: complete releases, start moves."""
387
+ if stage.name == COMPLETE_STAGE.name:
388
+ return self._failure(
389
+ stage,
390
+ task_dir,
391
+ "LIFECYCLE-LEASE-001",
392
+ title="task lease belongs to another branch",
393
+ blockers=(
394
+ conflict,
395
+ "complete the task from its lease branch, or re-run with "
396
+ "--takeover to complete here and release the lease",
397
+ ),
398
+ )
399
+ return self._failure(
400
+ stage,
401
+ task_dir,
402
+ "LIFECYCLE-LEASE-001",
403
+ title="task lease belongs to another branch",
404
+ blockers=(
405
+ conflict,
406
+ "re-run with --takeover only if you intend to move the "
407
+ "lease to this branch",
408
+ ),
409
+ )
352
410
 
353
411
  def _already_at_target_result(
354
412
  self,
@@ -551,9 +609,39 @@ class TaskLifecycleService:
551
609
  ) -> LifecycleResult | None:
552
610
  if not already_at_target or stage.name != START_STAGE.name:
553
611
  return None
554
- # The executor gate runs before the idempotent shortcut: a
555
- # foreign session re-running start on an active task must
556
- # not ride through as a no-op success.
612
+ guard = self._idempotent_guard(
613
+ stage, task_dir, task_data, executor, takeover
614
+ )
615
+ if guard is not None:
616
+ return guard
617
+ return LifecycleResult(
618
+ ok=True,
619
+ code="LIFECYCLE-IDEMPOTENT",
620
+ stage=stage,
621
+ task_dir=task_dir,
622
+ active_task_path=(
623
+ self._display_task_path(task_dir)
624
+ if stage.activates_session
625
+ else None
626
+ ),
627
+ transition=transition,
628
+ emitted_events=self._success_events(stage),
629
+ )
630
+
631
+ def _idempotent_guard(
632
+ self,
633
+ stage: LifecycleStage,
634
+ task_dir: Path,
635
+ task_data: dict | None,
636
+ executor: str | None,
637
+ takeover: bool,
638
+ ) -> LifecycleResult | None:
639
+ """Owner and lease gates for a start already at its target.
640
+
641
+ The executor gate runs before the idempotent shortcut: a foreign
642
+ session re-running start on an active task must not ride through as
643
+ a no-op success. The lease gate then refuses a start from another
644
+ branch, including this idempotent one."""
557
645
  current = task_data.get("executor") if isinstance(task_data, dict) else None
558
646
  current = (
559
647
  current.strip()
@@ -579,19 +667,13 @@ class TaskLifecycleService:
579
667
  "identify yourself",
580
668
  ),
581
669
  )
582
- return LifecycleResult(
583
- ok=True,
584
- code="LIFECYCLE-IDEMPOTENT",
585
- stage=stage,
586
- task_dir=task_dir,
587
- active_task_path=(
588
- self._display_task_path(task_dir)
589
- if stage.activates_session
590
- else None
591
- ),
592
- transition=transition,
593
- emitted_events=self._success_events(stage),
594
- )
670
+ if takeover:
671
+ taken_over = self._apply_takeover_on_idempotent(
672
+ stage, task_dir, task_data, executor, takeover
673
+ )
674
+ if taken_over is not None:
675
+ return taken_over
676
+ return self._check_lease(stage, task_dir, task_data or {}, takeover)
595
677
 
596
678
  def _run_preflight(
597
679
  self,
@@ -741,7 +823,12 @@ class TaskLifecycleService:
741
823
  head = current_head(self.repo_root)
742
824
  if head:
743
825
  meta["baselineCommit"] = head
744
- persisted["meta"] = meta
826
+ if executor:
827
+ task_lease.record(
828
+ meta, repo_root=self.repo_root, executor=executor
829
+ )
830
+ if meta:
831
+ persisted["meta"] = meta
745
832
  if stage.name == COMPLETE_STAGE.name:
746
833
  meta = dict(persisted.get("meta") or {})
747
834
  # Resolved here rather than reusing resolved_executor: the
@@ -759,6 +846,8 @@ class TaskLifecycleService:
759
846
  **payloads["evidenceExempt"],
760
847
  }
761
848
  persisted["meta"] = meta
849
+ if task_lease.release(meta):
850
+ persisted["meta"] = meta
762
851
  return persisted
763
852
 
764
853
  def _resolve_executor(self, executor: str | None) -> str | None:
@@ -880,14 +969,15 @@ class TaskLifecycleService:
880
969
  takeover: bool,
881
970
  ) -> LifecycleResult | None:
882
971
  """Reassign ownership when an already-active task is taken over; a
883
- plain idempotent start performs no write."""
972
+ plain idempotent start performs no write. A takeover by the same
973
+ identity still rewrites the lease to this branch."""
884
974
  if not stage.activates_session or not takeover:
885
975
  return None
886
976
  current = task_data.get("executor")
887
977
  if not isinstance(current, str) or not current.strip():
888
978
  return None
889
979
  resolved = self._resolve_executor(executor)
890
- if resolved is None or resolved == current.strip():
980
+ if resolved is None:
891
981
  return None
892
982
  current_task, failure = self._takeover_snapshot(stage, task_dir, task_data)
893
983
  if failure is not None:
@@ -963,10 +1053,11 @@ class TaskLifecycleService:
963
1053
  )
964
1054
  persisted = dict(task_data)
965
1055
  persisted["executor"] = resolved
1056
+ meta = dict(persisted.get("meta") or {})
966
1057
  if adoption is not None:
967
- meta = dict(persisted.get("meta") or {})
968
1058
  meta.update(adoption)
969
- persisted["meta"] = meta
1059
+ task_lease.record(meta, repo_root=self.repo_root, executor=resolved)
1060
+ persisted["meta"] = meta
970
1061
  unit.replace(
971
1062
  self.repository.task_json_path(task_dir),
972
1063
  persisted,
@@ -20,6 +20,7 @@ results, and the closeout blockers.
20
20
  | `LIFECYCLE-CONTEXT-001` | A session-activating stage (start/activate) cannot build the active-task session state, so the activation has no session to bind. | `services/task_lifecycle.py:716` |
21
21
  | `LIFECYCLE-DEPENDENCY-001` | The start preflight finds a `dependsOn` target that is not `completed`; the blocker text is `task depends on unfinished work: <names>`. | `services/lifecycle_policy.py:93` |
22
22
  | `LIFECYCLE-EXECUTOR-001` | The start activation point finds the task already owned by a different executor and no `--takeover` was passed, including the foreign-session idempotent re-run. | `services/task_lifecycle.py:577` (also `:1028`) |
23
+ | `LIFECYCLE-LEASE-001` | The start activation point or completion finds `task.json.meta.lease.branch` different from the current branch, both branches are known, and `--takeover` was not passed. Completion uses the same code and blocks instead of releasing, with blocker text pointing at the release path. The lease is written only by start/takeover/adopt and released at complete. | `services/task_lifecycle.py:391` |
23
24
  | `LIFECYCLE-RECOVERY-001` | An interrupted transaction from an earlier run cannot be replayed by `UnitOfWork.recover_all`, so the task is never loaded. | `services/task_lifecycle.py:538` |
24
25
  | `LIFECYCLE-REVIEW-001` | A `strict`, non-light task reaches completion with no independent review receipt at all. | `services/lifecycle_checks.py:658` |
25
26
  | `LIFECYCLE-REVIEW-002` | The latest review receipt does not have `result: "pass"`, so the newest review stands as a failure. | `services/lifecycle_checks.py:670` |
@@ -19,5 +19,5 @@ Current contracts:
19
19
  - `host-install-inspection.md`: the read-only `cwf host inspect` model for machine-level host install state, the doctor's consumption and unavailable path, and the installer/read-model/runtime ownership boundary (`HOST_INSTALL_INSPECTION_V1`).
20
20
  - `evidence-completion.md`: evidence-based completion — the `evidence.jsonl` schema, the `LIFECYCLE-AC-001/002/003/004` completion gate, `--allow-missing-evidence` exemption traces, and the injected coverage row.
21
21
  - `task-adopt.md`: task adoption — the entry boundary of `task next --run --adopt`, its preconditions (`LIFECYCLE-ADOPT-001`), the rebind + baseline reset + audit write, and how it differs from `--takeover`.
22
- - `task-board.md`: the shared board and dependency edges — the list/MCP board fields (executor / ownerSessionActive / evidenceCoverage / blocked), `--depends-on` declaration and validation, the start dependency gate (`LIFECYCLE-DEPENDENCY-001`), and the adopt handover receipt.
23
- - `error-codes.md`: the registry of every runtime error code with the condition that produces it: `LIFECYCLE-AC-001/002/003/004`, `LIFECYCLE-ADOPT-001`, `LIFECYCLE-CHECK-001`, `LIFECYCLE-CONTEXT-001`, `LIFECYCLE-DEPENDENCY-001`, `LIFECYCLE-EXECUTOR-001`, `LIFECYCLE-RECOVERY-001`, `LIFECYCLE-REVIEW-001/002/003/004`, `LIFECYCLE-TASK-001`, `LIFECYCLE-TRANSITION-001`, `LIFECYCLE-UOW-001`, `SUBAGENT-SLICE-001`.
22
+ - `task-board.md`: the shared board and dependency edges — the list/MCP board fields (executor / lease / ownerSessionActive / evidenceCoverage / blocked), `--depends-on` declaration and validation, the start dependency gate (`LIFECYCLE-DEPENDENCY-001`), and the adopt handover receipt.
23
+ - `error-codes.md`: the registry of every runtime error code with the condition that produces it: `LIFECYCLE-AC-001/002/003/004`, `LIFECYCLE-ADOPT-001`, `LIFECYCLE-CHECK-001`, `LIFECYCLE-CONTEXT-001`, `LIFECYCLE-DEPENDENCY-001`, `LIFECYCLE-EXECUTOR-001`, `LIFECYCLE-LEASE-001`, `LIFECYCLE-RECOVERY-001`, `LIFECYCLE-REVIEW-001/002/003/004`, `LIFECYCLE-TASK-001`, `LIFECYCLE-TRANSITION-001`, `LIFECYCLE-UOW-001`, `SUBAGENT-SLICE-001`.
@@ -53,7 +53,10 @@ the plan into a second workflow kernel.
53
53
  machine-readable concrete goal line, at least one concrete `AC-NNN` row,
54
54
  content in `## 目标` / `## 全局约束` / `## 文件边界` beyond the installed
55
55
  template body, complete task briefs (full fields for Normal/High-risk; file
56
- boundaries, verification command, and completion conditions for Tiny), a
56
+ boundaries, verification command, and completion conditions for Tiny),
57
+ including a dispatch decision with an explicit branch and branch evidence
58
+ (every branch states a concrete rationale; an implement branch names at
59
+ least one backticked owned path; a research branch names its questions), a
57
60
  concrete command inside the task's fenced verification block, a non-empty
58
61
  `implement.jsonl`, anchor acceptance rows matching the plan IDs/text, an
59
62
  anchor goal matching the plan goal, and the filled anchor spec-check result.
@@ -51,6 +51,7 @@ binding is not touched; the blockers state the concrete reason.
51
51
  | `meta.previousBaseline` | the former `meta.baselineCommit` (`null` when there was none) |
52
52
  | `meta.adoptedAt` | UTC timestamp `YYYY-MM-DDTHH:MM:SSZ` |
53
53
  | `meta.baselineCommit` | **reset** to the HEAD at adoption time; `null` when there is no git/no HEAD (degraded to status-only) |
54
+ | `meta.lease` | rewritten to `{executor: adopter, branch, head, at}` for the checkout doing the adoption; `branch` is `null` without git or on detached HEAD, `head` is `null` only without git (a detached HEAD records its commit sha). An idempotent `--takeover` shares this write path; a planning-phase `--takeover` moves the lease through the start write. |
54
55
  | `status` | unchanged |
55
56
  | `_state.revision` / `_state.operation_id` | the revision increments, and the operation_id carries the `adopt` tag (audit-traceable) |
56
57
 
@@ -14,6 +14,7 @@ reused by both surfaces, so field values must stay consistent from one source.
14
14
  | Field | Meaning | Boundary |
15
15
  |---|---|---|
16
16
  | `executor` | the currently owning executor (`task.json.executor`, `null` when unset) | written by start / `--takeover` / `--adopt` |
17
+ | `lease` | the branch-anchored lease as `{executor, branch, head, at}`, or `null` when the task holds none; only these four keys are exposed | same source as `task.json.meta.lease`; `branch` is `null` without git or on detached HEAD; `complete` releases the lease and refuses a lease held on another branch unless `--takeover` is passed |
17
18
  | `ownerSessionActive` | whether any session is bound to this task (`active_task_path` in `sessions/` points at it) | **a hint, not a verdict**: a session working with an explicit directory is never bound, so `false` only means "no binding points here" and never that the task is orphaned |
18
19
  | `evidenceCoverage` | `{total, withEvidence, missing[]}`; `null` for a task with no declared AC | same source as `run state` / the injected coverage row (`ac_evidence`) |
19
20
  | `blocked` | whether an unfinished dependency exists | see "dependency semantics" below |
@@ -125,6 +125,7 @@
125
125
  "Task start blocks clear missing plan facts for non-Tiny tasks.",
126
126
  "Strict non-Tiny start requires the configured-language plan template shape and a filled spec-check line.",
127
127
  "New strict non-Tiny tasks require a plan-ready snapshot from `plan finalize`; edits after finalize invalidate it.",
128
+ "Plan finalize requires a dispatch decision per task brief: no dispatch, research, implement, or both, with rationale and branch evidence.",
128
129
  "V1 does not parse plan step status or verification evidence; AC text is only compared between plan and anchor."
129
130
  ],
130
131
  "readWhen": [
@@ -60,6 +60,12 @@ Tiny 任务可保留简化 brief,但仍须写明精确文件边界、完成条
60
60
  - 本次改动形状:替换 / 抽取 / 删除 / 追加(可多选;“追加”必须说明旧路径为何不能替换或抽取)
61
61
  - 目标结构:<改动后由哪个函数/模块承担什么职责;职责不变时写“不变”并说明为什么>
62
62
 
63
+ **派发决策**
64
+ - 结论:不派发 / 派发研究 / 派发实现 / 派发研究与实现
65
+ - 依据:<不派发写具体理由;派发写并行收益或独立验证面>
66
+ - 切片:`<slice 名称>`:`<owned paths>`(派发实现时必填)
67
+ - 研究问题:<派发研究时必填;列出交给 cowork-research 的独立问题>
68
+
63
69
  **实现说明**
64
70
  ```python
65
71
  # 核心控制流草图;按现有代码调整名称。
@@ -60,6 +60,12 @@ Tiny plans may keep a shorter brief, but must still name exact file boundaries,
60
60
  - Change shape: replace / extract / delete / append (multiple allowed; "append" requires why the old path cannot be replaced or extracted)
61
61
  - Target structure: <which function/module owns what responsibility after this change; if unchanged, say "unchanged" and why>
62
62
 
63
+ **Dispatch Decision**
64
+ - Decision: No dispatch / Research dispatch / Implement dispatch / Research and implement dispatch
65
+ - Rationale: <concrete reason when not dispatching; parallel value or independent verification surface when dispatching>
66
+ - Slice: `<slice name>`: `<owned paths>` (required for implement dispatch)
67
+ - Research questions: <required for research dispatch; list the independent questions handed to cowork-research>
68
+
63
69
  **Implementation Notes**
64
70
  ```python
65
71
  # Core control-flow sketch; adjust names to match existing code.
@@ -400,6 +400,106 @@ def _missing_context_files(task_dir: Path) -> tuple[str, ...]:
400
400
  return tuple(name for name in required if not (task_dir / name).is_file())
401
401
 
402
402
 
403
+ def _completion_issues(
404
+ *,
405
+ task: str,
406
+ status: str,
407
+ open_ids: list[str] | None,
408
+ ) -> list[dict[str, str]]:
409
+ """Warnings that only an unarchived completed task can carry."""
410
+ issues = [
411
+ _task_hygiene_issue(
412
+ kind="completed_unarchived",
413
+ task=task,
414
+ status=status,
415
+ message="completed task remains in the active task tree",
416
+ hint=f"./.cowork-flow/run task next {task} --run --intent archive",
417
+ )
418
+ ]
419
+ if open_ids:
420
+ issues.append(
421
+ _task_hygiene_issue(
422
+ kind="completed_with_open_subagents",
423
+ task=task,
424
+ status=status,
425
+ message=(
426
+ "completed task still has open subagent context(s): "
427
+ + ", ".join(open_ids)
428
+ ),
429
+ hint=f"./.cowork-flow/run subagent list --task {task}",
430
+ )
431
+ )
432
+ return issues
433
+
434
+
435
+ def _context_issues(
436
+ *,
437
+ task: str,
438
+ status: str,
439
+ task_dir: Path,
440
+ bound_tasks: set[str],
441
+ ) -> list[dict[str, str]]:
442
+ """Warnings about the task's session binding and context files."""
443
+ issues: list[dict[str, str]] = []
444
+ if status in {"in_progress", "review"} and task not in bound_tasks:
445
+ issues.append(
446
+ _task_hygiene_issue(
447
+ kind="in_progress_unbound",
448
+ task=task,
449
+ status=status,
450
+ message="active task state is not bound to any runtime session",
451
+ hint=f"./.cowork-flow/run task next {task} --run",
452
+ )
453
+ )
454
+ missing = _missing_context_files(task_dir)
455
+ if missing:
456
+ issues.append(
457
+ _task_hygiene_issue(
458
+ kind="missing_task_context",
459
+ task=task,
460
+ status=status,
461
+ message=f"missing task context file(s): {', '.join(missing)}",
462
+ hint=f"./.cowork-flow/run task next {task} --validate",
463
+ )
464
+ )
465
+ return issues
466
+
467
+
468
+ def _lease_branch_issue(
469
+ repo_root: Path,
470
+ *,
471
+ task: str,
472
+ status: str,
473
+ data: dict[str, object],
474
+ ) -> dict[str, str] | None:
475
+ """Warn when an active task's lease names a different branch.
476
+
477
+ This mirrors the start gate without enforcing anything: an unknown
478
+ branch (no git, detached HEAD) or a missing lease never warns."""
479
+ if status not in {"in_progress", "review"}:
480
+ return None
481
+ meta = data.get("meta")
482
+ lease = meta.get("lease") if isinstance(meta, dict) else None
483
+ branch = lease.get("branch") if isinstance(lease, dict) else None
484
+ if not isinstance(branch, str) or not branch:
485
+ return None
486
+ from infra.git_snapshot import current_branch
487
+
488
+ current = current_branch(repo_root)
489
+ if not current or current == branch:
490
+ return None
491
+ return _task_hygiene_issue(
492
+ kind="lease_branch_mismatch",
493
+ task=task,
494
+ status=status,
495
+ message=(
496
+ f"task lease is held on branch '{branch}', "
497
+ f"current branch is '{current}'"
498
+ ),
499
+ hint=f"./.cowork-flow/run task next {task} --run --takeover",
500
+ )
501
+
502
+
403
503
  def check_task_hygiene(repo_root: Path) -> list[dict[str, str]]:
404
504
  from services.task_gate_profiles import is_light_task
405
505
 
@@ -432,52 +532,28 @@ def check_task_hygiene(repo_root: Path) -> list[dict[str, str]]:
432
532
  )
433
533
  )
434
534
  if status == "completed":
435
- issues.append(
436
- _task_hygiene_issue(
437
- kind="completed_unarchived",
438
- task=task,
439
- status=status,
440
- message="completed task remains in the active task tree",
441
- hint=f"./.cowork-flow/run task next {task} --run --intent archive",
442
- )
443
- )
444
- open_ids = open_subagents.get(
445
- _normalized_task_path(task, repo_root)
446
- )
447
- if open_ids:
448
- issues.append(
449
- _task_hygiene_issue(
450
- kind="completed_with_open_subagents",
451
- task=task,
452
- status=status,
453
- message=(
454
- "completed task still has open subagent context(s): "
455
- + ", ".join(open_ids)
456
- ),
457
- hint=f"./.cowork-flow/run subagent list --task {task}",
458
- )
459
- )
460
- if status in {"in_progress", "review"} and task not in bound_tasks:
461
- issues.append(
462
- _task_hygiene_issue(
463
- kind="in_progress_unbound",
535
+ issues.extend(
536
+ _completion_issues(
464
537
  task=task,
465
538
  status=status,
466
- message="active task state is not bound to any runtime session",
467
- hint=f"./.cowork-flow/run task next {task} --run",
539
+ open_ids=open_subagents.get(
540
+ _normalized_task_path(task, repo_root)
541
+ ),
468
542
  )
469
543
  )
470
- missing = _missing_context_files(task_dir)
471
- if missing:
472
- issues.append(
473
- _task_hygiene_issue(
474
- kind="missing_task_context",
475
- task=task,
476
- status=status,
477
- message=f"missing task context file(s): {', '.join(missing)}",
478
- hint=f"./.cowork-flow/run task next {task} --validate",
479
- )
544
+ issues.extend(
545
+ _context_issues(
546
+ task=task,
547
+ status=status,
548
+ task_dir=task_dir,
549
+ bound_tasks=bound_tasks,
480
550
  )
551
+ )
552
+ lease_issue = _lease_branch_issue(
553
+ repo_root, task=task, status=status, data=data
554
+ )
555
+ if lease_issue is not None:
556
+ issues.append(lease_issue)
481
557
  return issues
482
558
 
483
559
 
@@ -71,6 +71,8 @@ Fill the template in order: header table and goal first, then acceptance criteri
71
71
  - Each task is small enough to execute and verify independently.
72
72
  - Every Normal or High-risk task fills every required field in the template's task brief: Purpose, Code Fact Sources, File Boundaries, Key Symbols, Implementation Notes, Test Proof, Verification Command, Completion Conditions, Prohibited Drift, and Deviation Conditions.
73
73
  - Every Normal or High-risk task fills the hotspot and change-shape brief field (immediately after Key Symbols in the installed template). Treat the target as a hotspot when any of these is true: the target function already exceeds the 60-line soft budget; it has 6+ control-flow branches or 3+ nesting levels; the target file is an executable source file touched by 5+ commits in the last 180 days (query the tracked `template/` source path for gitignored live copies); or this change adds a parameter, boolean flag, or mode branch to an existing function. The churn criterion does not apply to docs, skills, or templates. A hotspot defaults to replace/extract/delete; append requires a concrete reason why the old path cannot be changed.
74
+ - Every Normal or High-risk task fills the dispatch decision brief field (immediately after the hotspot field in the installed template): record one decision — no dispatch, research dispatch, implement dispatch, or both — with a concrete rationale. Implement dispatch names the slice and its backticked owned paths; research dispatch names the independent questions. A one-word decision without its rationale or branch evidence does not pass `plan finalize`.
75
+ - When the plan's code facts cannot be established from the repository alone — external API, format, or protocol behavior, or facts spanning unrelated areas — the default is to dispatch one to three `cowork-research` children instead of widening the main context, and to record that decision and those questions in the dispatch decision field.
74
76
  - For Tiny tasks, keep the brief short but still name exact file boundaries, completion conditions, and verification commands.
75
77
  - For behavior changes, include a failing test before implementation when behavior can be tested.
76
78
  - For implementation tasks whose changed files are covered by `.cowork-flow/spec/` requirements, name the covered spec files in the plan and add the clause check to the task's `Verification Command` and the plan's `Final Verification`: run the deciding command when one exists, otherwise check clause by clause and record `pass` / `not_applicable` with reason. For strict non-Tiny tasks this is a hard start gate: the bound plan and the task anchor must use the configured-language verification heading and carry a filled spec-check result. The template placeholder `<pass / not_applicable + reason>` blocks start; replace it before starting. The content remains self-declared and is reviewed by the check agent.