@aibyzero/cm-workflow 0.15.4 → 0.16.0

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-workflow",
3
- "version": "0.15.4",
3
+ "version": "0.16.0",
4
4
  "description": "Spec-driven product development workflow for Codex: external research, PRD, implementation, read-only feature testing, review, QA, fixes, refactors, and documentation.",
5
5
  "author": {
6
6
  "name": "cm-workflow maintainers",
package/CHANGELOG.md CHANGED
@@ -7,6 +7,37 @@
7
7
 
8
8
  (暂无)
9
9
 
10
+ ## 0.16.0 — 2026-09-20
11
+
12
+ 一次真实实跑把 cm-ai 从「跑不完」推到「跑得完」,本版是那趟跑出来的修复与新增。
13
+
14
+ **不修就跑不下去的三处**
15
+
16
+ - **交接文件撞名不再让任务永久卡死**。交接文件 `{feature}-{任务}-a{轮次}-handoff.json` 以不覆盖方式发布,于是一个在审查前就死掉的运行留下的文件,会让同一任务此后**每一次**重跑都崩在 `linkSync` 上,且异常被塌缩成 `execution_error`,既不知道原因也没有恢复路径。实跑中同一任务连续 5 个批次全挂于此,换批次号无效。现按「这份旧交接有没有被审查用过」分流:字节相同视为已发布;无回执指名则归档到 `.reviews/.superseded/` 让路;有回执指名则绝不覆盖,返回 `handoff_exists`。判据只认回执 front matter 内的 `handoff:` 行,按 front matter 边界解析而非固定行数,读取侧不依赖写入侧字段顺序;读不懂一律按「已消费」失败关闭,绝不因解析不了就去动审查证据。
17
+ - **独立审查超时可单独配置**。审查进程超时此前写死 60 秒,唯一能调大它的入口是受保护模式,而那个模式又禁止开发者跑命令——两者互斥,等于没有出路。实测三次真实审查耗时 69 / 104 / 174 秒,在此前的实现下全都会被掐断、重试一次仍超时、任务直接判死。`--review-config` 新增可选 `timeoutMs`(1–3600000 毫秒,默认仍 60000),与受保护模式解耦,且不进入已授权配置的摘要,所以 `review_transport_timeout` 之后可以在恢复时调大再续跑。
18
+ - **QA 单用例应答窗口可调,批次也能只重跑被阻断的 QA**。`qa.timeoutMs` 上限此前写死 60000,而一轮真实浏览器走查按分钟计,必然超时判 BLOCKED 拖垮整轮;上限提到 3600000,默认不变。批次宿主补上 `--rerun-unknown-qa` / `--rerun-blocked-qa`,此前批次里一条用例超时之后唯一补救是重做整个任务、连已 approved 的审查也要重跑,而任务已被勾完成又过不了准入,等于没有补救路径。
19
+
20
+ **新增:交付前验证闸门(可选 `--verification-precheck`)**
21
+
22
+ - 实测一个 feature 的耗时里末任务占 79%、返工率 80%(其他任务 4%),而打回理由**全部**是「证据没满足任务书里早就写明的验证要求」,没有一条是代码缺陷。启用后,宿主在收齐任务自身检查之后、**构建审查包与派发独立审查之前**,把该任务的验证要求原文与检查结果交给对端逐条核对;任一条不满足即停在 `blocked / verification_precheck_failed`,`pendingAction` 为 `resume`,走与 `developer_result_invalid` 相同的重做通道,**不消耗审查轮次**。
23
+ - **只能拦,不能放**:通过闸门不产生审查回执、不授予批准、不替代后续的完整独立审查,定位与 `prd_self_check` 一致。任务没写验证要求时自动让路。不启用该开关时流程逐字节不变。
24
+ - 一条如实说明的限制:验证要求在 `tasks.md` 里是自由文本,**JS 无法机械证明对端把每一条都枚举到了**。机械强制的只有回答形状、每条必须给出非空证据落点、全部满足才放行。形状合规不等于语义覆盖。
25
+
26
+ **故障可诊断**
27
+
28
+ - 失败码不在白名单内时会塌缩成 `execution_error`,此前原始错误既不进日志也不进 stderr 也不进状态。上面那个 EEXIST 当初是临时加打印才看到的,普通使用者做不到。现在塌缩的同时往宿主 stderr 输出一行结构化诊断,只含 `code`/`syscall`/`path`/`dest` 具名字段,**绝不输出 `error.message`**。宿主请求被遮蔽成 `host_request_failed` 时同样如此,并带上是哪个 `operation`。现有脱敏边界一行未动:协议回复逐字节不变,诊断只走 stderr,不进日志镜像、不进运行状态、不进任何摘要或 digest。
29
+
30
+ **规则与文档**
31
+
32
+ - cm-ai N3 要求交付前把任务的 `verification` 当清单逐条核对,写清每一项的证据落点,对不上就报阻塞而不是交付。
33
+ - 文档补齐:批次启动与推进的四项前置条件;cm-prd 宿主的调用契约与 split 章节标题要求(五处坑连同「字段集严格、多给字段同样被拒」这一共同根源);`pendingAction: reconcile` 出现时该做什么(含两个来源、各自的恢复路径,以及三种不管用的做法)。
34
+
35
+ ## 0.15.5 — 2026-09-20
36
+
37
+ - **安装时按实际状态询问是否开启更新播报**。安装器结尾此前无条件打印「自动更新器未自动启用」:对已启用的人这句是错的(实测 hook 已配、后台更新器也在跑,仍这么说),对未启用的人它读着像普通说明而不像少配了一步——两边都没起作用,这才是装了包的人收不到新版提示的真实原因,不是缺功能。现改为检测后再说话:已配好则确认一句;未配好且交互安装则询问一次,答 y 才写入;`--yes` 与非交互安装不写任何东西,改为打印确切的 hook 条目;此前拒绝过则不再打扰(记在 `~/.cm-workflow/announce-hook-declined`,删掉该文件并重装即可重新被问)。
38
+ - 只添加播报 hook,**绝不添加后台升级器**——告知有新版与让工具自我替换是两个决定。`settings.json` 属于用户:无法解析时原文件逐字节不动、写入走临时文件加原子改名、已存在则不重复添加。安装器此前从不碰该文件,本次开的口子范围写死,只加这一条 hook 且只在明确同意时。
39
+ - 注意:只开播报而不开后台升级器时没有东西会产生播报内容(`cm-announce.sh` 只消费 `cm-update.sh` 留下的文件),两者需一起开启才有效果,详见 `docs/installation.md`。
40
+
10
41
  ## 0.15.4 — 2026-09-20
11
42
 
12
43
  - **`cm-check --quick`:约 12 秒收口的快速检查**。完整检查耗时拆分为查更新 0.7 秒、机械检查 12.4 秒,其余几乎全在八组语义检查上——那不是程序在跑,而是执行者逐个文件读取并取证行号,且控制器强制八组齐全、passed 必须附真实行号,慢是设计换来的。日常「装没装对、版本对不对」这类问题机械检查已能回答,`--quick` 让更新与机械检查照常跑、机械通过后直接收口,不进语义检查。结论为 `MECHANICAL_ONLY` 而**不是 PASSED**:八组一组没读,不得据此宣称安装完整无断链;结果带 `semanticChecked:false` 与 `reason:quick_mode_semantic_not_run`。机械失败仍照常报 FAILED/BLOCKED,快速模式不跳过任何失败。默认不带该参数时行为不变。
package/README.md CHANGED
@@ -17,6 +17,11 @@
17
17
 
18
18
  ## 最近更新
19
19
 
20
+ **0.16.0**
21
+
22
+ - **安装时会问你要不要开启新版提示**。此前安装完只有一句含糊的「自动更新器未自动启用」,已经开启的人也会看到这句(是错的),没开启的人又不会当回事,结果几乎没人用上这个功能。现在安装器会先看你实际配没配,再决定说什么;没配且是手动安装时,问一句、你答 y 才写入。用 `--yes` 静默安装的不会被改动任何配置,只会打印该加什么。
23
+ - 它**只加一条「有新版就告诉你」的提示**,不会顺手打开后台自动升级——那是另一回事,仍需你自己决定。你的 `settings.json` 里原有的内容(比如自定义状态栏)不会被动。
24
+
20
25
  **0.15.4**
21
26
 
22
27
  - **`/cm-check` 新增快速模式**:日常只想确认「装没装对、版本对不对」时,跑快速检查约 12 秒出结果,不再等十几分钟。完整检查的时间几乎全花在逐个文件核对引用关系上,快速模式跳过这一段。结论会明确标为「仅机械检查」而不是「通过」——跳过的部分不会被说成检查过了。机械检查本身发现的问题照常报错,不会被跳过。
@@ -143,7 +148,7 @@ $cm-check
143
148
 
144
149
  仓库直接分发 Skills 和脚本,无需在仓库根目录运行 `npm install` 或构建。完整安装行为、覆盖范围和卸载说明见[安装指南](docs/installation.md)。
145
150
 
146
- 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.15.4 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
151
+ 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.16.0 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
147
152
 
148
153
  ## 升级旧版本
149
154
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.15.4
1
+ 0.16.0
@@ -73,7 +73,7 @@ Install or upgrade with the same command:
73
73
  npx @aibyzero/cm-workflow@latest install
74
74
  ```
75
75
 
76
- To pin a version, use `npx @aibyzero/cm-workflow@0.15.4 install` from outside
76
+ To pin a version, use `npx @aibyzero/cm-workflow@0.16.0 install` from outside
77
77
  the CM Workflow source checkout (for example, your home directory). Inside a
78
78
  checkout with the same package name and version, npm can select the local
79
79
  uninstalled package and report `cm-workflow: command not found`.
@@ -181,7 +181,14 @@ platforms; any admitted task still uses the shared Review/N5 gates.
181
181
  ## Optional Claude auto-update (macOS/Linux)
182
182
 
183
183
  The Bash installer copies the updater on a best-effort basis but does not activate
184
- it. A copy failure is reported as a warning and does not invalidate a core runtime
184
+ it. An interactive install now asks once whether to enable the **announcement** hook
185
+ and, on yes, adds that single `hooks.SessionStart` entry for you; it never adds the
186
+ background updater, and it never edits `settings.json` without that yes. A refusal is
187
+ remembered in `~/.cm-workflow/announce-hook-declined`; delete that file and reinstall
188
+ to be asked again. `--yes` and non-interactive installs write nothing and print the
189
+ exact entry to add. Announcing a new version and letting the tool replace itself are
190
+ separate decisions, so enabling the announcement alone leaves the updater off: with no
191
+ updater scheduled there is nothing to announce, so enable it below if you want both. A copy failure is reported as a warning and does not invalidate a core runtime
185
192
  that already passed its installed self-check. The PowerShell
186
193
  installer intentionally does not copy this Bash-based updater; Windows users who
187
194
  want it must run the Bash installer from WSL or Git Bash. To enable it on a
@@ -340,8 +340,75 @@ host-context 必须是真实当前会话身份;宿主将其排除出独立审
340
340
  原结果合同,不谎报无新增。检查的 `result` 是数组,不是上述开发结果。错绑定回复被拒绝,
341
341
  不会解除当前等待。正常 `status/cancel` 仍可随时发送,JS 一次只发一项工具工作。
342
342
  开发返回后,原 runner 完成检查、Learning 写回与 handoff 定稿;随后返回
343
- `awaiting_review / decision_required`。不能通过回复 `approved` 打开 V3 授权或完成任务;
344
- 需要审查时使用下方可信启动选项,不能据此宣称 N1–N8 已跑完。
343
+ `awaiting_review / decision_required`。
344
+
345
+ ### 交付前验证闸门(可选,`--verification-precheck`)
346
+
347
+ 实测数据:末任务占一个 feature 总耗时约 79%,返工率 80%(其他任务 4%),
348
+ 而打回理由**全部**是「证据没满足任务书里早就写明的验证要求」,没有一条是代码缺陷。
349
+ 一轮独立审查要花一到三分钟,返工则要再赔上一整轮开发加审查。
350
+
351
+ 启用后,宿主在收齐任务自身的检查之后、**构建审查包与派发独立审查之前**,
352
+ 发一个 `verification_precheck` 请求,把该任务 `tasks.md` 里的验证要求原文与本次检查结果
353
+ 一起交给对端,由对端逐条核对本次交付并回答:
354
+
355
+ ```json
356
+ {"items":[{"requirement":"记录实现前基线","satisfied":true,"evidence":"npm test tests 42 / pass 42 / fail 0"}]}
357
+ ```
358
+
359
+ 只要有一条 `satisfied` 为 false,任务停在 `blocked / verification_precheck_failed`,
360
+ `pendingAction` 为 `resume`——与 `developer_result_invalid` 同一条重做通道,**不消耗审查轮次**。
361
+
362
+ **它只能拦,不能放。** 通过闸门不产生审查回执、不授予任何批准、不减少后续的完整独立审查。
363
+ 这与 `prd_self_check` 的定位一致:机械通过不等于语义通过,不能用自检冒充独立审查。
364
+
365
+ **一条要如实说明的限制**:任务的验证要求在 `tasks.md` 里是自由文本,
366
+ **JS 无法机械证明对端把其中每一条都枚举到了**。JS 强制的是:回答的形状、
367
+ 每条都必须给出非空的证据落点、以及只有全部满足才放行。形状合规不等于语义覆盖。
368
+
369
+ 对端如何核对不受限制:可以一个上下文读完全部要求,也可以一条要求派一个子 agent。
370
+ 后者的价值不在快,而在每个核对者只看到一条要求与交付物、看不到开发者的推理过程。
371
+
372
+ 任务没写验证要求时闸门自动让路,不自造要求。不启用该开关时,流程与之前逐字节一致。
373
+
374
+ 交接文件 `{SPECS_DIR}/.reviews/{feature}-{任务}-a{轮次}-handoff.json` 以不覆盖方式发布。
375
+ 撞名时按「这份旧交接有没有被审查用过」分流,判据是同轮次回执 `{feature}-{任务}-r{轮次}.md`
376
+ 里的 `handoff:` 行是否指名它:
377
+
378
+ - **字节完全相同**:视为已发布(链接后崩溃的情形),直接成功,不重写文件。
379
+ - **内容不同且没有回执指名它**:这份交接属于一个在审查前就死掉的运行,会被归档到
380
+ `.reviews/.superseded/{原文件名}.{内容摘要前16位}`(先硬链接再删除,中途崩溃不丢字节),
381
+ 然后发布新交接。归档目录是子目录,不进入 `{feature}-{任务}-r{N}.md` 的证据文件名匹配。
382
+ - **内容不同且回执指名它**:这是审查已经消费过的证据,绝不覆盖,返回 `handoff_exists`。
383
+
384
+ 判据只认回执 **front matter 内**(首个 `---` 到下一个 `---` 之间)的 `handoff:` 行,不按固定行数截取——`handoff:` 之后的 `scope` 列表长度等于该任务的改动文件数,按行数截取会让判定依赖字段顺序。正文里出现的 `handoff:` 不算数。回执缺失视为未被消费;front matter 未闭合、起始不是 `---`、文件非普通文件或为符号链接、超过 256 KiB,一律按「已消费」处理(失败关闭),绝不因为读不懂就去覆盖审查证据。
385
+
386
+ 因此同一任务失败一次后不再需要人工去 `.reviews/` 删文件才能重跑;已批准的交接仍然不可覆盖。
387
+
388
+ 宿主请求在协议层被遮蔽成 `host_request_failed` 时同样如此。哪些契约码可以透给对端
389
+ 是刻意划定的边界——宿主选择暴露的走 blocked 结果带 `reason`,其余统一遮蔽——这条边界
390
+ 不变;缺的只是被遮蔽的那些错误连运维也看不到。现在会在宿主进程的 stderr 输出:
391
+
392
+ ```json
393
+ {"diagnostic":"host_request_failed","operation":"save_draft","code":"prd_review_sections_missing"}
394
+ ```
395
+
396
+ `operation` 是对端自己发的操作名。字段取舍、脱敏规则与下述 `execution_error` 诊断一致。
397
+ 协议回复一个字节未变,写 stderr 抛错也不影响回复。
398
+
399
+ 失败码不在白名单内时会塌缩成 `execution_error`。塌缩的同时,宿主进程的 stderr 会输出
400
+ 一行结构化诊断,便于定位真实原因:
401
+
402
+ ```json
403
+ {"diagnostic":"execution_error","code":"EEXIST","syscall":"link","path":"…","dest":"…"}
404
+ ```
405
+
406
+ 只输出 `code`、`syscall`、`path`、`dest` 四个具名字段,且每个字段须为 1–1024 字节、
407
+ 不含控制字符,否则丢弃;一个都没有时输出 `{"diagnostic":"execution_error","detail":"unavailable"}`。
408
+ **不输出 `error.message`**——它可能夹带 provider 输出或源码片段。诊断只走 stderr,
409
+ 不进日志镜像、不进运行状态、不进任何摘要或 digest,也不改变失败路径本身;
410
+ 写 stderr 失败时静默忽略。白名单内的失败码按原样返回,不输出诊断。
411
+ 不能通过回复 `approved` 打开 V3 授权或完成任务;需要审查时使用下方可信启动选项,不能据此宣称 N1–N8 已跑完。
345
412
 
346
413
  结束发送 `{"type":"host_close","sessionId":"from-host-ready"}`,进程确认后退出;
347
414
  PTY 会关闭本进程输入回显并恢复原终端模式,须用上述消息结束,而非依赖 Ctrl-D。
@@ -432,11 +499,17 @@ node scripts/cm-ai-host.mjs serve --config /absolute/run.json --mode resume \
432
499
  --allow-review-attempt 1
433
500
  ```
434
501
 
435
- review.json 仅含 `{model, disabledSkills, preflight}`;disabledSkills 是本机探测实际发现并
502
+ review.json 含 `{model, disabledSkills, preflight}`,另有可选 `timeoutMs`;disabledSkills 是本机探测实际发现并
436
503
  禁用的 Skill 路径,preflight 沿原配置指纹/模型/stdin 合同。探测输出不包含原始诊断、
437
504
  凭证或请求正文;旧实验路径仅兼容转发到共享 runtime。通过探测不等于获准调用或模型可用。
438
505
  更换 CLI/安装配置后应重新本机探测;模型和 disabledSkills 必须与运行绑定的配置一致。
439
506
 
507
+ `timeoutMs` 是 reviewer 进程的传输预算,单位毫秒,必须是 1 到 3600000 之间的整数,
508
+ 不填时沿用 worker 默认的 60000。它与 `--protected-conversation-config`/`--protected-config`
509
+ 互不依赖:两者都给出时 reviewer 取 review.json 里的值,因此**调大审查超时不需要切换开发模式**。
510
+ 它不进入已授权配置的摘要,所以 `review_transport_timeout` 之后可以在恢复时调大再续跑;
511
+ 它只管 reviewer,不改变开发、检查或 QA 的任何超时。
512
+
440
513
  `--allow-review-attempt` 只能为1或2,只传递可信启动会话已经取得的那一轮授权,
441
514
  不能为了让流程继续而擅自添加。不会自动批准后续轮次、换模型或重试失败;若第一轮要求
442
515
  修改,原 runner 执行修复后停在第二轮待审,需第二轮单独授权。没有该选项时不调用 reviewer,
@@ -652,6 +725,17 @@ unassessedTasks;只返回语义评估:`scores`含scope/risk/accumulation/bou
652
725
  `{result: "PASS"|"FAIL"|"BLOCKED", passed, failed, blocked, report}`,报告必须实际位于
653
726
  specs `.reviews/` 内。宿主只能写获准报告,不能修产品代码或独立写 start/complete。
654
727
 
728
+ 工作流配置的 `qa.timeoutMs` 是单条 QA 用例给宿主的应答窗口,整数 1–3600000 毫秒,
729
+ 不填仍为 60000。一轮真实浏览器走查(造数据、逐步点击、每步读 DOM 与存储)按分钟计,
730
+ 60 秒内做不完;超时的用例会被标记 `hostRequestTimeout` 并判 `BLOCKED`,拖垮整轮 QA。
731
+ 需要真实走查时按实际耗时调大它。
732
+
733
+ 被阻断的 QA 可以单独重跑,不必重做任务:批次宿主接受 `--rerun-unknown-qa` 与
734
+ `--rerun-blocked-qa`,语义、限制与 qaRound 上限沿用单任务宿主,两者互斥且都要求
735
+ `--allow-qa`。批次没有 `--mode`,所以是否生效逐任务判定——只有「已有运行记录可恢复
736
+ 且该任务配了 QA 执行器」的任务才会收到这个开关,新建的运行或没有 QA 的任务直接忽略,
737
+ 不会因此让整个批次启动失败。
738
+
655
739
  JS 在 dispatch 前用原 writer 写 `test_run/start`(首轮),返回后重新检查任务包、
656
740
  报告路径和计数,再写 `complete`,最后由原 `inspectCmAiQaResult` 裁决。
657
741
  PASS 且提供 `execution.applicableAgentFiles` 时继续原上下文刷新;FAIL/BLOCKED 停止。
@@ -986,6 +1070,60 @@ review.json 与单任务入口相同;有 QA 配置仍必须获得对应命令/
986
1070
  重开不自动恢复;整个 workflows map 绑定原 child 配置指纹,未来任务配置漂移也不能悄悄采纳。
987
1071
  本地双任务 CLI/真实命令与文档/合成 reviewer 的恢复组合已通过,不是实际模型或双宿主验收。
988
1072
 
1073
+ #### 启动与推进的前置条件
1074
+
1075
+ 下列四项不满足时,现象都不易从返回值直接看出,逐条核对可省掉一次排查:
1076
+
1077
+ - **每个任务都要有 `qa` 配置,不只是末任务。** `workflows[key].qa` 为 `null` 时
1078
+ `createHostWorkflowCapabilities` 不装 `qaDecisionProvider`,该任务开发与检查完成后
1079
+ QA 决策恒为空,状态停在 `fixture_completed / qa_decision_required`,**批次不会自行推进,
1080
+ 再发 advance 也没有反应**。需要某个任务不跑 QA 时,仍给它 `qa` 配置,由评估结果决定跳过。
1081
+ - **QA 环境声明 `carrier: "browser"` 时必须显式传 `--browser-qa available|unavailable`**,
1082
+ 否则启动即 `browser_capability_required`。这是声明不是探测,创建与恢复都要重新给。
1083
+ - **首次推进前主工作区必须干净,含未跟踪文件**,否则 `batch_main_dirty` 并列出文件。
1084
+ 上一批次的产出未提交即会触发。
1085
+ - **`batch.tasks` 的首项必须等于准入的 `nextTask`**,否则 `task_selection_mismatch`。
1086
+ 上一轮已把某任务标完成时,新批次要从下一个未完成任务起,不能沿用旧任务清单。
1087
+ `--allow-review` 列出的条目也必须落在本批次任务集合内,否则启动即 `review_task_mismatch`。
1088
+
1089
+ `review_transport_timeout` 且无结果返回时,状态会带 `pendingAction: "resume"`。
1090
+ 此时应按该提示走恢复并重新给出审查授权;继续发 `advance` 会消耗掉这次机会,
1091
+ 随后状态转为 `blocked / pendingAction: none`,只能换新 `batchId` 重来。
1092
+
1093
+ ### `pendingAction: "reconcile"` 时该做什么
1094
+
1095
+ `reconcile` 的意思是**这一步的结果未知**——不是失败,也不是成功,JS 拒绝替你猜。
1096
+ 它只有两个来源:
1097
+
1098
+ | 状态 | 含义 | 恢复路径 |
1099
+ | --- | --- | --- |
1100
+ | `state: "unknown"` | 某个有副作用的步骤抛了异常或返回了无法判定的终态,做没做成不确定 | 无协议级恢复,见下 |
1101
+ | `state: "fixture_completed"` + `code: "qa_execution_unknown"` | 一次 QA 调用没拿到终态,工具可能还在跑或已被中断 | `--rerun-unknown-qa` |
1102
+
1103
+ **`reconcile` 不是一个可以发送的操作。** 三件事都不管用,而且会让情况更糟:
1104
+
1105
+ - 带 `identity` 发 `advance` → `invalid_input`;
1106
+ - 不带 `identity` 发 `advance` → 原样重放同一个 `reconcile` 状态。这两者交替出现,
1107
+ 按「同一个响应码连续出现才算卡住」做的空转检测会被交替清零,驱动可能空转到上限。
1108
+ **判定卡住应当只看 `pendingAction`,不要看错误码。**
1109
+ - 换 `batchId` 也不一定管用:批次任务的 `runId` 是 `task-{digest({batchId, task})}`,
1110
+ 换批次号确实会换 runId、拿到全新日志,但如果真正的阻塞物在批次外(例如
1111
+ `.reviews/` 下上一次运行留下的文件),换号无济于事。
1112
+
1113
+ **`state: "unknown"` 的处理顺序**:
1114
+
1115
+ 1. 先看宿主进程的 stderr。被塌缩成 `execution_error` 的失败会在那里留下一行
1116
+ `{"diagnostic":"execution_error","code":…}`,多数情况足以定位(例如 `EEXIST` 会
1117
+ 带上冲突的 `path` 与 `dest`)。
1118
+ 2. 按诊断处理掉真实原因,**再**用新的 `batchId` 重跑该任务。旧的未知状态已经写进该
1119
+ runId 的执行日志,同一个 runId 重开只会原样重放它。
1120
+ 3. 不要手工改写执行日志或伪造一个终态。已完成的提交、已登记的审查记录都不因此作废,
1121
+ 重跑是从该任务重新开始,不是从整个 feature 重新开始。
1122
+
1123
+ **`qa_execution_unknown` 的处理**:按上文 `--rerun-unknown-qa` 的条件恢复。
1124
+ 它只接受「已记录的用例结果全部 PASS 且没有定稿执行报告」的未完成调用,
1125
+ FAIL/BLOCKED 或资源未关闭的仍然拒绝,不会伪造通过。
1126
+
989
1127
  `node --test scripts/cm-ai-run.test.mjs` 验证真实 store 创建/取消/恢复和零 provider 调用;
990
1128
  另用真实 host/runner + 隔离假 developer 验证长任务期间的控制可达性。
991
1129
  这不是实际 provider 运行、跨平台完整支持或 P1/P2 总验收。
@@ -1107,6 +1245,33 @@ PDF/HTML现通过同一CLI的`prd_materials`宿主请求处理,先于prd_analy
1107
1245
  收到host_ready后发`{"requestId":"prd-1","operation":"start","text":"当前真实用户请求"}`;宿主按prd_analyze的原Skill参考执行分析,通过原host_result信封回question/analyzed/blocked。有澄清时传`advance`及真实用户回答;status/cancel沿原通信协议。首次start写一次run_start,每轮分析先写带analysis_turn的route decision;正文不写日志。关闭/EOF记录run_done的incomplete、blocked或cancelled,不记录成功、不改审批位。分析就绪不是工作流完成。终态日志异常不自动重试。
1108
1246
  这是真实CLI及原日志接线;目前无跨会话分析恢复、规格落盘或普通Skill激活,关闭会话后不能续接内存中的澄清/草稿。下文模块层描述的回调由本CLI接入,模块本身仍不拥有日志文件。
1109
1247
 
1248
+ #### 调用契约中容易踩空的几处
1249
+
1250
+ 控制请求的字段集是**严格**的:`cm-prd-host.mjs` 对每个 operation 逐一 `shape` 校验,
1251
+ **少给必填字段和多给不属于该 operation 的字段一样会被拒**。被拒时错误通道统一返回
1252
+ `host_request_failed`(只有宿主主动暴露的失败才带 reason 走 blocked 结果),
1253
+ 因此无法从返回值分辨是哪种问题,照下列逐条核对可省掉一次排查:
1254
+
1255
+ - `advance` / `start` / `plan_design` **必须带 `text`**,且非空。
1256
+ - `save_draft` / `prepare_summary` 等**不接受 `draftDigest`**;只有
1257
+ `promote_design` 与 `select_design_reviews` 带 `draftDigest`,`publish_summary` 带
1258
+ `summaryDigest`。多给一个字段即被拒。
1259
+ - 用 `--session prd-ID` 恢复既有会话时**不要再发 `start`**,否则 `prd_turn_not_ready`;
1260
+ 先 `status` 读回当前 stage 再继续。
1261
+ - `prd_analyze` 回复的 `analyzed.sourcePaths` 必须**覆盖 `sources` 的全部条目**,
1262
+ 用与之相同的相对路径;只列本轮相关的那几份会以
1263
+ `prd_source_coverage_invalid` 拒绝。提供 `--cases` 时另含其绝对路径。
1264
+ - 每条验收标准都要被至少一条测试用例的 `acIds` 覆盖,否则机械自检
1265
+ `acceptance_test_coverage_missing`。
1266
+
1267
+ split 审查对文档章节标题有硬要求,不满足时 `final_review_package` 只返回
1268
+ `host_request_failed`(真实原因是 `prd_review_sections_missing`):
1269
+
1270
+ - `requirements.md` 必须有匹配 `^##\s+(功能需求|Functional requirements)\s*$` 的章节——
1271
+ 写成「## 功能要求」不匹配。
1272
+ - `design.md` 必须有方案摘要/概述/架构/功能模块/技术/接口/数据/波及/安全一类的
1273
+ `##` 章节,`split` 阶段另单独校验一次摘要类标题。
1274
+
1110
1275
  `runtime/js/cm-prd/analysis.mjs` 提供 `createCmPrdAnalysis({input,runtime,analyze,record})` 会话分析控制层;input沿用来源入口参数。先准入、解析analyst/planner配置,再读取正文。`advance(text)` 接真实当前用户输入,回调 `analyze(payload,signal)` 执行当前宿主分析;`status()`/`cancel()` 提供状态与取消。
1111
1276
  `record(event)` 必须由宿主接原规格日志写入器,失败阻止派发;此模块不自行创建run_start/run_done或日志文件。非current-runtime analyst明确blocked/degrade,不自动换provider。question进入awaiting_user,analyzed含summary/sourcePaths/openQuestions;来源路径必须完整,开放问题非空仍awaiting_user。PDF/HTML(含用例文件)必须先经上方材料宿主处理;未提供processMaterials的旧模块调用方仍阻断非文本材料。未知格式继续阻断。
1112
1277
 
package/install.sh CHANGED
@@ -246,4 +246,15 @@ echo
246
246
  echo "完成(已安装版本: v${VERSION})。"
247
247
  echo "建议在 Claude Code 中运行 /cm-check 校验;macOS/Linux 也保留 /cm:check 别名。"
248
248
  echo "使用手册: $DEST/cm-workflow/docs/user-guide.md"
249
- echo "自动更新器未自动启用;按 docs/installation.md 手工配置 SessionStart hook。"
249
+ # 播报 hook 的实际状态由脚本判断后再说话:此前这行无条件打印,对已启用的人是错的,
250
+ # 对未启用的人又读着像普通说明,两边都没起作用。仅在交互安装时询问,且只加播报 hook。
251
+ if [ -x "$DEST/scripts/cm-announce-hook.mjs" ] || [ -f "$DEST/scripts/cm-announce-hook.mjs" ]; then
252
+ if [ "$ASSUME_YES" -ne 1 ] && [ -t 0 ] && [ -t 1 ]; then
253
+ node "$DEST/scripts/cm-announce-hook.mjs" || true
254
+ else
255
+ CM_NONINTERACTIVE=1 node "$DEST/scripts/cm-announce-hook.mjs" </dev/null || true
256
+ fi
257
+ else
258
+ echo "自动更新器未自动启用;按 docs/installation.md 手工配置 SessionStart hook。"
259
+ fi
260
+ echo "后台自动升级仍需另行开启,见 docs/installation.md。"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.15.4",
3
+ "version": "0.16.0",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -12,7 +12,13 @@ const sameTask=(left,right)=>['repositoryId','runId','taskId'].every(key=>left[k
12
12
  const boundStatus=(status,identity)=>{validIdentity(status?.identity);
13
13
  need(sameIdentity(status.identity,identity),'identity_mismatch');return status;};
14
14
  const retryReview=status=>status.state==='pending_review'&&status.code==='review_transport_timeout';
15
- const retryDeveloper=status=>status.state==='blocked'&&status.code==='developer_result_invalid';
15
+ // Both mean the delivery itself must be redone: an invalid developer result, or
16
+ // one that does not satisfy the task's own written verification. Exported so the
17
+ // batch driver decides retryability from the same predicate instead of keeping a
18
+ // second copy of the code list that silently drifts.
19
+ export const developmentRetryable=status=>status.state==='blocked'
20
+ &&['developer_result_invalid','verification_precheck_failed'].includes(status.code);
21
+ const retryDeveloper=developmentRetryable;
16
22
  const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approval':
17
23
  status.state==='changes_requested'||retryDeveloper(status)||retryReview(status)?'resume':
18
24
  status.state==='awaiting_review'?'decision':status.state==='unknown'?'reconcile':
@@ -140,6 +146,7 @@ export function createCmAiConversationEntry(options) {
140
146
  const ownerIdentity=json(options.identity);validIdentity(ownerIdentity);
141
147
  const runner=options.runner;
142
148
  const runnerKeys=['executeEffect','status','cancel','run'];
149
+ if(runner&&Object.hasOwn(runner,'verificationBlocks'))runnerKeys.push('verificationBlocks');
143
150
  if(runner&&Object.hasOwn(runner,'attachLearningEvidence'))runnerKeys.push('attachLearningEvidence');
144
151
  if(runner&&Object.hasOwn(runner,'inspectFixAssociation'))runnerKeys.push('inspectFixAssociation');
145
152
  if(runner&&Object.hasOwn(runner,'acceptCompletedFix'))runnerKeys.push('acceptCompletedFix');
@@ -579,7 +586,10 @@ export function createCmAiConversationEntry(options) {
579
586
  // corrected result a new effect id without changing the provider attempt.
580
587
  const rejectedValues=status.calls.filter(call=>call.terminal==='failed'
581
588
  &&call.failureResult?.code==='invalid_result'&&call.failureResult.retryable===true).length;
582
- const effectId=`develop-${identity.attempt}${rejectedValues?`-retry-${rejectedValues}`:''}`;
589
+ // Both kinds of local rejection need a fresh effect id: an invalid developer
590
+ // result, and one the host gate blocked before the review package existed.
591
+ const retries=rejectedValues+(runner.verificationBlocks?.()??0);
592
+ const effectId=`develop-${identity.attempt}${retries?`-retry-${retries}`:''}`;
583
593
  const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'develop',learningInput});
584
594
  return effectSummary(operation,result,runner,identity);
585
595
  }
@@ -19,7 +19,7 @@ const prefix=(a,b)=>{need(b.length>=a.length,'runner_history_mismatch');same(a,b
19
19
  const uuid=s=>need(typeof s==='string' && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(s),'runner_session');
20
20
  const states=['ready','awaiting_review','approved','changes_requested','fixture_completed','blocked','unknown','cancelled','pending_review'];
21
21
  export const stageAllowed=(kind,state,code=null)=>
22
- kind==='develop'&&state==='blocked'&&code==='developer_result_invalid'
22
+ kind==='develop'&&state==='blocked'&&['developer_result_invalid','verification_precheck_failed'].includes(code)
23
23
  ||kind==='review'&&state==='pending_review'&&code==='review_transport_timeout'
24
24
  ||({develop:['ready','changes_requested'],review:['awaiting_review'],complete:['approved']})[kind]?.includes(state)===true;
25
25
  // Local rejected values keep audit records but do not consume provider rounds.
@@ -295,6 +295,9 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
295
295
  }
296
296
  }else need(s.state==='unknown'||s.state==='cancelled'
297
297
  ||Object.hasOwn(original,'specification')&&s.state==='blocked'&&s.code==='spec_drift'
298
+ // The host gate rejected the delivery after Learning was already written
299
+ // back: the writeback stands, only the review package was not built.
300
+ ||s.state==='blocked'&&s.code==='verification_precheck_failed'
298
301
  ||added[0]&&['failed','unavailable','auth_required','permission_denied'].includes(added[0].terminal),'runner_learning');
299
302
  }
300
303
  if(digest(s.reviewPackage)!==digest(before.reviewPackage)) {
@@ -310,6 +313,14 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
310
313
  s.learningResult.writeback,effect.learningInput,s.learningResult.bootstrap??null,config.bootstrap??null);
311
314
  expectedState='awaiting_review';
312
315
  }
316
+ // The developer call succeeded and is never retried, but the host gate blocked
317
+ // between the checks and the review package. No package exists, so no review
318
+ // round was spent; the attempt counter does not move either.
319
+ if(added[0]?.terminal==='succeeded'&&s.code==='verification_precheck_failed') {
320
+ need(digest(s.reviewPackage)===digest(before.reviewPackage),'runner_develop');
321
+ same(s.receipt,before.receipt);same(s.receipts,before.receipts);
322
+ expectedState='blocked';expectedCode='verification_precheck_failed';
323
+ }
313
324
  if(added[0] && ['failed','unavailable','auth_required','permission_denied'].includes(added[0].terminal)) {
314
325
  expectedState='blocked';expectedCode=invalidDeveloperCall(added[0])
315
326
  ?'developer_result_invalid':added[0].failureResult?.code==='protected_edit_stale'?'protected_edit_stale':added[0].terminal;
@@ -9,12 +9,37 @@ const failureCodes=new Set(['invalid_input','limit_exceeded','call_timeout','can
9
9
  'review_package_mismatch','missing_material','contradictory_verdict','execution_mismatch','receipt_version',
10
10
  'unregistered_receipt','invalid_receipt','receipt_identity','receipt_package_mismatch','review_not_approved',
11
11
  'checks_not_passed','async_commit','commit_unknown','unsupported_path','unsupported_file','read_failed',
12
- 'snapshot_changed','spec_drift','invalid_baseline','out_of_scope','empty_changes','invalid_package','package_mismatch']);
12
+ 'snapshot_changed','spec_drift','invalid_baseline','out_of_scope','empty_changes','invalid_package','package_mismatch',
13
+ 'handoff_exists','verification_precheck_failed']);
14
+ // An unlisted code becomes execution_error, which on its own is not actionable.
15
+ // The EEXIST that blocked every retry of a task in #81 stayed invisible in the
16
+ // log, the state and stderr until a temporary print was added by hand. Emit one
17
+ // structured line at the point of collapse, with named fields only: never
18
+ // error.message, which can carry arbitrary provider output or source text.
19
+ const diagnosticText=value=>typeof value==='string'&&value.length>0&&value.length<=1024
20
+ &&!/[\x00-\x08\x0b-\x1f]/.test(value);
21
+ export function executionDiagnostic(error) {
22
+ const detail={};
23
+ for(const name of ['code','syscall','path','dest']) {
24
+ const d=Object.getOwnPropertyDescriptor(error,name);
25
+ if(d && Object.hasOwn(d,'value') && diagnosticText(d.value))detail[name]=d.value;
26
+ }
27
+ return Object.keys(detail).length>0?detail:null;
28
+ }
29
+ export function reportExecutionCollapse(error,write=value=>process.stderr.write(value)) {
30
+ // Diagnostics never change the failure path: a broken stream stays silent.
31
+ try{
32
+ const detail=executionDiagnostic(error);
33
+ write(JSON.stringify({diagnostic:'execution_error',...(detail??{detail:'unavailable'})})+'\n');
34
+ }catch{/* ignore */}
35
+ }
13
36
  export function failureCode(error) {
14
37
  try {
15
38
  const d=Object.getOwnPropertyDescriptor(error,'code');
16
- return d && Object.hasOwn(d,'value') && failureCodes.has(d.value)?d.value:'execution_error';
17
- } catch {return 'execution_error';}
39
+ if(d && Object.hasOwn(d,'value') && failureCodes.has(d.value))return d.value;
40
+ } catch {/* an error that cannot be inspected collapses like any other */}
41
+ reportExecutionCollapse(error);
42
+ return 'execution_error';
18
43
  }
19
44
  export function shape(value,names) {
20
45
  need(value!==null && typeof value==='object' && !Array.isArray(value)
@@ -25,16 +25,52 @@ import {validateDocumentationPaths} from './host-documentation.mjs';
25
25
  import {verifySpecificationMaterial} from './specification-material.mjs';
26
26
  import {isFinalCmAiTask} from './cm-ai-admission.mjs';
27
27
  import {createHostBootstrap} from './host-bootstrap.mjs';
28
- import {digest,id,hex,json,need,shape,freeze} from './effect-contract.mjs';
28
+ import {digest,id,hex,json,need,shape,freeze,arrayItems} from './effect-contract.mjs';
29
29
  export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
30
30
  +'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content}], complete UTF-8 text or null for deletion. '
31
31
  +'Only the supplied scope and expected hashes are allowed. The fixed sandbox applies these edits. On failure return {status,code} without edits. '
32
32
  +'status must be exactly "succeeded" on success (with value and edits) or "failed" (with code). Return the object through the structured output schema; never wrap it in markdown fences.';
33
33
  const protectedConversations=new WeakMap();
34
34
  export const conversationProtection=execution=>protectedConversations.get(execution)??null;
35
+ // An explicit reviewer budget wins over the protected-mode budget: it is the
36
+ // narrower knob, and raising it must not require switching development mode.
37
+ // Absent both, the worker default applies. Returns a spread-ready fragment so
38
+ // an unset budget never plants an undefined timeoutMs on the worker options.
39
+ // Between the task's own checks and the independent review. It may only block:
40
+ // passing it is not an approval, produces no receipt and consumes no review
41
+ // round. A satisfied gate still leaves the full independent review ahead.
42
+ //
43
+ // One deliberate limit, stated rather than papered over: a task's verification
44
+ // is free text, so JS cannot prove every requirement in it was enumerated. What
45
+ // is enforced mechanically is the shape, that each returned requirement cites a
46
+ // nonempty evidence location, and that the gate passes only when every returned
47
+ // requirement is satisfied. Mechanical shape is not semantic coverage.
48
+ export function readVerificationPrecheck(raw){
49
+ const value=json(raw,256*1024);shape(value,['items']);
50
+ const items=arrayItems(value.items);
51
+ need(items.length>0&&items.length<=64,'verification_precheck_invalid');
52
+ for(const item of items){
53
+ shape(item,['requirement','satisfied','evidence']);
54
+ need(typeof item.satisfied==='boolean','verification_precheck_invalid');
55
+ for(const field of ['requirement','evidence']){
56
+ const text=item[field];
57
+ need(typeof text==='string'&&text.trim().length>0&&Buffer.byteLength(text,'utf8')<=2000
58
+ &&!/[\x00-\x08\x0b-\x1f]/.test(text),'verification_precheck_invalid');
59
+ }
60
+ }
61
+ return freeze({satisfied:items.every(item=>item.satisfied===true),
62
+ unsatisfied:items.filter(item=>item.satisfied!==true).map(item=>item.requirement)});
63
+ }
64
+
65
+ export function resolveReviewTimeout(review,protection){
66
+ if(review?.timeoutMs!=null)return {timeoutMs:review.timeoutMs};
67
+ if(protection)return {timeoutMs:protection.timeoutMs};
68
+ return {};
69
+ }
35
70
  export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
36
71
  definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
37
- shape(options,[...['protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember'].filter(key=>Object.hasOwn(options,key))]);
72
+ shape(options,[...['protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
73
+ need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
38
74
  const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
39
75
  const provider=options.providerDevelopment??null;
40
76
  if(provider){
@@ -77,7 +113,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
77
113
  ...(workflow?{workflow}: {})};
78
114
  const reviewOptions={cwd:definition.codeProject,model:review?.model??'unconfigured',preflight:review?.preflight??null,
79
115
  disabledSkills:review?.disabledSkills??[],
80
- ...(protection?{timeoutMs:protection.timeoutMs}:{}),
116
+ ...resolveReviewTimeout(review,protection),
81
117
  promptTransport:'stdin',schemaPath:fileURLToPath(new URL('./review-result.schema.json',import.meta.url))};
82
118
  need(!allowedAttempts.length||review!==null,'review_configuration_required');
83
119
  if(allowedAttempts.length||provider)need((reviewerRuntime==='codex'?preflightMatches:claudePreflightMatches)(reviewOptions.preflight,reviewOptions),'tool_preflight_missing');
@@ -102,7 +138,23 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
102
138
  };
103
139
  };
104
140
  const used=new Set();
141
+ // The gate is opt-in: without it the flow is byte-for-byte what it was.
142
+ // The runner contract is exactly {satisfied}. Which requirements failed is
143
+ // what the operator needs to act on, so it goes to this process's stderr the
144
+ // same way other host diagnostics do, not into the runner state.
145
+ const verificationGate=options.verificationPrecheck===true?async(request,control)=>{
146
+ const verdict=readVerificationPrecheck(await bridge.call('verification_precheck',
147
+ {...request,codeProject:definition.codeProject,feature:definition.feature,
148
+ scope:definition.scope},control.signal));
149
+ if(!verdict.satisfied)try{
150
+ process.stderr.write(JSON.stringify({diagnostic:'verification_precheck_failed',
151
+ task:request.identity.taskId,attempt:request.identity.attempt,
152
+ unsatisfied:verdict.unsatisfied})+'\n');
153
+ }catch{/* diagnostics never change the verdict */}
154
+ return {satisfied:verdict.satisfied};
155
+ }:null;
105
156
  const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[hostContextId],hostDecision:null,applicableAgentFiles:[],
157
+ ...(verificationGate?{verificationGate}:{}),
106
158
  ...(bootstrap?{bootstrap}:{}),
107
159
  ...(provider?{developmentAttempt:provider.attempt}:{}),
108
160
  ...(workflow?createHostWorkflowCapabilities({definition,configuration:workflow,bridge,allowQa,runtime,protectedExecution:protection!==null,bootstrap,parallelMember}):{}),
@@ -47,6 +47,64 @@ export function verifyHostHandoff(raw){
47
47
  return {outcome:'matched',handoffSha256:bound.handoff.sha256,packageDigest:reviewPackage.packageDigest};
48
48
  }
49
49
 
50
+ // A handoff a review already consumed is approval evidence and is never replaced.
51
+ // One left by a run that died before review is not: it must not block every retry
52
+ // of the same task forever. The receipt names the handoff it reviewed, so the two
53
+ // cases are distinguishable without guessing from timestamps or run identity.
54
+ function reviewConsumedHandoff(parent,name,attempt){
55
+ const suffix=`-a${attempt}-handoff.json`;
56
+ if(!name.endsWith(suffix))return true;
57
+ const receipt=path.join(parent,`${name.slice(0,-suffix.length)}-r${attempt}.md`);
58
+ let body;
59
+ try{
60
+ const info=fs.lstatSync(receipt);
61
+ // Receipts are written under a 256 KiB cap. Anything larger is not one, and
62
+ // guessing about it must not license replacing approval evidence.
63
+ if(!info.isFile()||info.isSymbolicLink()||info.size>256*1024)return true;
64
+ body=fs.readFileSync(receipt,'utf8');
65
+ }catch(error){
66
+ if(error.code==='ENOENT')return false;
67
+ throw error;
68
+ }
69
+ // Search the real front matter rather than a fixed line count: the scope list
70
+ // after handoff: is as long as the task's changed file list, so any reordering
71
+ // of these fields would silently push handoff: out of a fixed window and turn
72
+ // reviewed evidence into a supersedable leftover. Unterminated or unrecognised
73
+ // front matter fails closed.
74
+ const lines=body.split('\n');
75
+ if(lines[0]?.trim()!=='---')return true;
76
+ const end=lines.findIndex((line,index)=>index>0&&line.trim()==='---');
77
+ if(end===-1)return true;
78
+ return lines.slice(1,end).some(line=>line.trim()===`handoff: ${name}`);
79
+ }
80
+
81
+ // Archive by link-then-unlink so the bytes survive a crash between the two steps.
82
+ function supersedeHandoff(parent,handoffPath,existing){
83
+ const archive=path.join(parent,'.superseded');
84
+ fs.mkdirSync(archive,{recursive:true,mode:0o700});
85
+ const stamp=createHash('sha256').update(existing).digest('hex').slice(0,16);
86
+ const target=path.join(archive,`${path.basename(handoffPath)}.${stamp}`);
87
+ try{fs.linkSync(handoffPath,target);}catch(error){if(error.code!=='EEXIST')throw error;}
88
+ fs.unlinkSync(handoffPath);
89
+ const dir=fs.openSync(archive,fs.constants.O_RDONLY);
90
+ try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
91
+ }
92
+
93
+ // Publish with no-replace semantics, resolving only the collisions that are
94
+ // provably safe to resolve. Returns nothing; throws on a conflict it may not touch.
95
+ function publishHandoff(parent,handoffPath,temp,bytes,attempt){
96
+ try{fs.linkSync(temp,handoffPath);return;}
97
+ catch(error){if(error.code!=='EEXIST')throw error;}
98
+ const info=fs.lstatSync(handoffPath);
99
+ need(info.isFile()&&!info.isSymbolicLink(),'handoff_exists');
100
+ const existing=fs.readFileSync(handoffPath);
101
+ // Republishing identical bytes is the crash-after-link case, already published.
102
+ if(existing.equals(bytes))return;
103
+ need(!reviewConsumedHandoff(parent,path.basename(handoffPath),attempt),'handoff_exists');
104
+ supersedeHandoff(parent,handoffPath,existing);
105
+ fs.linkSync(temp,handoffPath);
106
+ }
107
+
50
108
  export function createHostHandoff(raw){
51
109
  const {root,baseline,checks,handoffPath,parent,reviewPackage,changedFiles,payload,bytes}=prepareHostHandoff(raw);
52
110
  const temp=path.join(parent,`.cm-initial-handoff-${randomUUID()}`);
@@ -58,7 +116,7 @@ export function createHostHandoff(raw){
58
116
  verifyReviewPackage({root,baseline,checks,reviewPackage,expectedDigest:reviewPackage.packageDigest});
59
117
  need(payload.implementation_sha256===implementationSha256(root,changedFiles),'snapshot_changed');
60
118
  // Atomic no-replace publication, unlike rename which could overwrite approval.
61
- fs.linkSync(temp,handoffPath);
119
+ publishHandoff(parent,handoffPath,temp,bytes,baseline.identity.attempt);
62
120
  fs.unlinkSync(temp);
63
121
  const dir=fs.openSync(parent,fs.constants.O_RDONLY);
64
122
  try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}