@aibyzero/cm-workflow 0.17.0 → 0.17.1

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 (52) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +6 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +8 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  9. package/docs/installation.md +1 -1
  10. package/docs/js-workflow-control.md +3 -1
  11. package/package.json +1 -1
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  13. package/runtime/js/cm-ai/control-policy.mjs +3 -2
  14. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  15. package/runtime/js/cm-ai/host-check.mjs +3 -1
  16. package/runtime/js/cm-ai/host-session.mjs +41 -8
  17. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  18. package/runtime/js/cm-ai/host-tool-bridge.mjs +22 -9
  19. package/runtime/js/cm-ai/operator-guidance.mjs +56 -30
  20. package/runtime/js/cm-ai/task-runner.mjs +5 -2
  21. package/runtime/js/cm-prd/summary.mjs +27 -12
  22. package/runtime/review.md +9 -0
  23. package/scripts/cm-ai-batch-host.test.mjs +21 -9
  24. package/scripts/cm-ai-batch-run.mjs +12 -6
  25. package/scripts/cm-ai-control-policy.test.mjs +68 -0
  26. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +3 -2
  27. package/scripts/cm-ai-drive.test.mjs +3 -3
  28. package/scripts/cm-ai-host-fixture.mjs +9 -6
  29. package/scripts/cm-ai-host-protected.test.mjs +1 -1
  30. package/scripts/cm-ai-host.test.mjs +15 -0
  31. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  32. package/scripts/cm-ai-review-timeout.test.mjs +20 -0
  33. package/scripts/cm-check-drive-files.mjs +1 -1
  34. package/scripts/cm-check-host.test.mjs +1 -1
  35. package/scripts/cm-claude-probe.test.mjs +26 -0
  36. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  37. package/scripts/cm-claude-worker.test.mjs +16 -0
  38. package/scripts/cm-drive-liveness.test.mjs +83 -0
  39. package/scripts/cm-external-batch-host.test.mjs +8 -6
  40. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  41. package/scripts/cm-host-liveness.test.mjs +150 -0
  42. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  43. package/scripts/cm-notify.test.mjs +50 -16
  44. package/scripts/cm-prd-drive.test.mjs +1 -1
  45. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  46. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  47. package/scripts/cm-prd-summary.test.mjs +31 -0
  48. package/scripts/cm-release-smoke.sh +2 -14
  49. package/scripts/cm-test-suite.mjs +109 -0
  50. package/scripts/cm-test-suite.test.mjs +162 -0
  51. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  52. package/skills/cm-ai/references/js-host.md +33 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-workflow",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
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/AGENTS.md CHANGED
@@ -101,4 +101,8 @@ Read the relevant files under `.claude/rules/` when modifying shell scripts, doc
101
101
 
102
102
  - **失败终态计数与执行结论分别处理**:只从原生 CLI 的原会话终态读取官方 usage,失败仍失败;通用 error notice 不覆盖后续 turn.failed 的计数。按 provider 原生字段映射 cache-write 和 reasoning,reasoning 只作 output 子集,缺失明确 unavailable;记录失败不能重派或放行。来源:可选执行优化独立审查的失败终态与原生字段修复;证据:`scripts/cm-efficiency-usage.test.mjs` 的四 worker 成功/失败/缺失、双失败方言与字段冲突用例,`scripts/test-cm-native-usage.py` 的子集与去重用例。该教训随本轮改动待独立审查。
103
103
 
104
+ - **「只登记不阻断」要覆盖每一层校验,入口本身也算**:历史 feature 的容错分支只包住了后续读取,回执闸门 `inspectPrdReview` 本身在 try 之外;补上后,自检修订核对 `inspectPrdSplitDesign` 又经另一条路径重查同一旧回执(交叉审查发现)。历史文件被批准的变更改动后,任一路径都会拦下整批摘要。给某类对象定「只登记」规则时,从第一个可能抛出的调用开始纳入同一边界,并用「当前对象仍严格、不带范围仍严格、准备后再变仍拒绝」三条反例锁住。来源:2026-10-12 AI潮第 7 批 prepare_summary 被 1.bootstrap 旧拆分回执阻断;证据:`runtime/js/cm-prd/summary.mjs`、`scripts/cm-prd-summary.test.mjs` 的历史回执产物变更两条用例、`scripts/cm-prd-self-check-revision.test.mjs` 的历史自检修订用例及改坏核对。该教训随本轮改动待独立审查。
105
+
104
106
  - **基线复现不能代替失败根因**:区分测试正文与清理钩子失败;相同基线失败只说明不是新增回归,丢失原 cause 后仍保留未知。预检与夹具失败只记录有限系统字段,不打印原 message/stderr,不把能力受限或超时改成通过;夹具总截止与已有驱动预算对齐,产品预算和业务断言保持原值。来源:执行优化回归的启动错误丢失、清理失败和外层夹具超时收尾;证据:`scripts/cm-efficiency-diagnostics.test.mjs` 的无真实枚举/监听错误注入、`scripts/cm-ai-batch-drive.test.mjs` 的实际 live 用例,以及保存的原始失败与基线对照。该教训随本轮改动待独立审查。
107
+
108
+ - **传输探活不得替代业务进展或持久事实**:心跳只报告存活;阶段截止取既有执行预算,嵌套阶段结束恢复外层原期限。关闭保护按独立操作对象核对归属,不能以可重复 requestId 释放另一在途操作,故障清理也不能记成用户取消。来源:宿主防空等与防误关;证据:`scripts/cm-host-liveness.test.mjs`、`scripts/cm-drive-liveness.test.mjs`、`scripts/cm-host-stage-observer.test.mjs` 的拒关、重复 ID、嵌套期限、断连和无状态副作用用例。[已结构化]
package/CHANGELOG.md CHANGED
@@ -5,7 +5,12 @@
5
5
 
6
6
  ## 未发布
7
7
 
8
- (暂无)
8
+ ## 0.17.1 — 2026-10-13
9
+
10
+ - **新建批次的摘要不再被历史 feature 的旧回执拦住**:已批准的历史 feature 在其审查回执之后经 `--change` 正常修改过时,`prepare_summary` 以前在回执闸门处直接报 `prd_review_artifact_changed`,整批无法发布待审。现在历史 feature 的回执闸门失败、以及带自检修订记录时对同一旧回执的修订核对失败,都与其他历史归档问题一样只登记进摘要附注(「归档不可用,已登记未重审」),当前 feature 和不带范围的调用仍严格阻断;准备后历史文件再变化,发布照样拒绝。
11
+ - **宿主在途操作与空等有明确出口**:`host_busy` 返回原请求、阶段和开始时间;默认关闭拒绝在途操作,显式强制关闭报告中断。九类驾驶员启用每5秒传输心跳,并按既有检查/审查预算与连接期限退出,给出中文原因;心跳不延长业务期限,不写 journal、不改配置指纹。没有新增心跳文件,也不自动把任务完成等同于宿主可退出。
12
+ - **恢复指引与实际控制入口一致**:分别说明 legacy/v2、单任务/批次的恢复合同,v2 不再被引导使用不支持的旧参数;统一当前测试清单与隔离目录,补齐既有失败夹具的有界诊断,并更新贡献指南和架构说明。运行身份、历史记录和旧运行原有兼容/拒绝边界保持不变。
13
+ - **Claude 审查启动预检兼容初始化前的显示通知**:Claude Code 2.1.289 的 `system/ui_invalidate` 以前被解析器判为 `missing_init`,导致预检在消息请求前终止。现在按固定、无正文通知接纳,继续核对会话与共享通知上限;通知不能代替初始化或审查结果,未知消息仍拒绝。预检继续精确匹配完整模型 ID,没有扩大权限、重试或超时预算。
9
14
 
10
15
  ## 0.17.0 — 2026-10-12
11
16
 
package/CONTRIBUTING.md CHANGED
@@ -46,6 +46,53 @@ manifest, checks the local workflow root through BYZ, and installs the Codex
46
46
  plugin under a disposable home; it does not modify the caller's normal Codex
47
47
  plugin state.
48
48
 
49
+ ## JavaScript test groups
50
+
51
+ Use Node.js 24.14+ for the full suite, plus Python 3.9+ and Git for the fixtures
52
+ that call them. Node.js 18 remains the minimum for the shared-authority checks
53
+ listed in CI. No npm dependency install, BYZ installation or plugin installation
54
+ is needed to list or run these groups:
55
+
56
+ ```bash
57
+ node scripts/cm-test-suite.mjs check
58
+ node scripts/cm-test-suite.mjs list ordinary
59
+ node scripts/cm-test-suite.mjs list native
60
+ node scripts/cm-test-suite.mjs list history
61
+ node scripts/cm-test-suite.mjs run ordinary
62
+ node scripts/cm-test-suite.mjs run native --concurrency 1
63
+ node scripts/cm-test-suite.mjs run history --concurrency 4
64
+ ```
65
+
66
+ | Group | Coverage and requirements |
67
+ | --- | --- |
68
+ | `ordinary` | All `scripts/*.test.mjs` except the fixed native group; new tests are included automatically. CI runs four weighted shards. |
69
+ | `native` | Nine files that need a local Codex CLI and working native sandbox. Linux hosts must permit the sandbox's network isolation. These tests are also required by release smoke. |
70
+ | `history` | `experiments/js-orchestration/*.test.mjs`; historical compatibility evidence. CI allows this job to fail, but the local command still exits unsuccessfully on a failing test. |
71
+
72
+ The entrypoint creates temporary `CM_WORKFLOW_HOME` and `CM_WORKFLOW_LOG_HOME`
73
+ directories for each run and removes them when the runner exits. It does not
74
+ change `HOME` or `CODEX_HOME`, install tools, request external services, or retry
75
+ failures. Fixtures retain their own platform checks and local subprocess or
76
+ loopback requirements. Missing native capabilities are not a passing native run.
77
+
78
+ Use `--concurrency N` to choose test-file concurrency explicitly. Without that
79
+ option, Node's existing default applies. Select the same weighted shards as CI
80
+ with the existing `ci-test-shards.mjs` implementation:
81
+
82
+ ```bash
83
+ node scripts/cm-test-suite.mjs list ordinary --shards 4 --index 0
84
+ node scripts/cm-test-suite.mjs run ordinary --shards 4 --index 0 --concurrency 2
85
+ ```
86
+
87
+ Shard indices start at zero. Run indices 0 through 3 to cover all four shards.
88
+ An empty run selection, an invalid inventory, and failed tests return nonzero;
89
+ interrupts are forwarded to the test process group on POSIX. The entrypoint
90
+ does not change fixture timeouts. The fixed native list lives only in
91
+ `scripts/cm-test-suite.mjs`; `scripts/cm-test-suite.test.mjs` pins its approval
92
+ fingerprint and verifies that ordinary plus native cover every current script
93
+ test exactly once. Changes to the native list require explicit review of that
94
+ fingerprint and the reason for excluding a test from hosted CI.
95
+
49
96
  ## Skill trigger diagnostics
50
97
 
51
98
  Treat trigger quality as a routing contract, not marketing copy. Test each
package/README.md CHANGED
@@ -17,6 +17,13 @@
17
17
 
18
18
  ## 最近更新
19
19
 
20
+ **0.17.1**
21
+
22
+ - **PRD 历史回执不再阻断当前新批次**:旧 feature 的归档问题只登记附注,当前规格和准备后的漂移仍严格核对。
23
+ - **宿主防空等与防误关**:驾驶员使用传输心跳和阶段期限;`host_busy` 说明原操作仍在执行,默认关闭拒绝在途工作。
24
+ - **Claude 审查预检恢复正常启动**:兼容初始化前的 `ui_invalidate` 显示通知,保留原有解析和权限边界。
25
+ - **恢复提示与贡献者测试入口对齐**:保留旧运行合同,统一测试清单并补齐失败诊断。详见[更新日志](CHANGELOG.md)。
26
+
20
27
  **0.17.0**
21
28
 
22
29
  - **升级注意**:新建 `cm-ai` 运行改用 `--control-config` 选能力(`development` / `bootstrap` / `qa` / `qaFix` 四个模式),不再传一串 `--allow-*`;`--human-authorized` 已删除。已经在跑的旧运行继续按原协议走完,两种入口不能互用。
@@ -240,7 +247,7 @@ $cm-check
240
247
 
241
248
  仓库直接分发 Skills 和脚本,无需在仓库根目录运行 `npm install` 或构建。完整安装行为、覆盖范围和卸载说明见[安装指南](docs/installation.md)。
242
249
 
243
- 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.17.0 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
250
+ 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.17.1 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
244
251
 
245
252
  ## 升级旧版本
246
253
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.17.0
1
+ 0.17.1
@@ -14,7 +14,12 @@ flowchart LR
14
14
  Skills --> TaskGates["runtime/task-gates.md"]
15
15
  Skills --> Logging["runtime/logging.md"]
16
16
  Skills --> External["runtime/external-expert.md"]
17
- RuntimeJS["runtime/js/cm-ai: shipped source + active N1/N2 admission"]
17
+ Skills --> Driver["scripts/cm-ai-drive / cm-ai-batch-drive"]
18
+ Driver --> Host["cm-ai-host / cm-ai-batch-host"]
19
+ Host --> RuntimeJS["runtime/js/cm-ai: owner / runner / gates"]
20
+ RuntimeJS --> Durable["specs .reviews/.execution: journal + checkpoints"]
21
+ RuntimeJS --> ToolRequest["current-session tool requests / configured workers"]
22
+ ToolRequest --> RuntimeJS
18
23
  Skills --> References["flow references: N1-N8 / PRD modes"]
19
24
  Skills --> Templates["templates/"]
20
25
  Skills --> Specs["requirements / design / tasks / optional test-cases"]
@@ -81,13 +86,21 @@ native filenames. Workflow assets resolve relative to the active Skill; no flow
81
86
  may hardcode a Codex cache path or treat `~/.claude` as the universal source
82
87
  root.
83
88
 
84
- `runtime/js/cm-ai/` is the sole source root for the accepted JS orchestration
85
- modules. `experiments/js-orchestration/` keeps thin re-exports plus historical
86
- fixtures so prior evidence paths remain readable. The active `cm-ai` Skill owns
87
- conversation/tool orchestration and invokes the shared JS gates directly; the
88
- dormant full-host factory is not a prerequisite and Claude does not need a second
89
- adapter protocol. Platform installation evidence and real task dogfood remain
90
- separate F09 work.
89
+ `runtime/js/cm-ai/` is the sole source root for JS orchestration modules.
90
+ `experiments/js-orchestration/` keeps thin re-exports plus historical fixtures
91
+ so prior evidence paths remain readable. New cm-ai tasks use the shared JS host
92
+ by default. The Skill selects the supported entry and fulfills its tool requests;
93
+ the driver transports requests and responses, and the host/runner owns phase
94
+ transitions, durable evidence and completion gates. `scripts/cm-ai-host.mjs`
95
+ assembles the single-task host through `scripts/cm-ai-run.mjs`; the batch host
96
+ coordinates the same task owners. Codex and Claude use this shared chain with
97
+ their configured execution adapters.
98
+
99
+ Existing JS runs resume with their original identity and stored configuration.
100
+ The explicitly selected legacy conversation flow still uses the shared task
101
+ gates; it does not take ownership of an existing JS run or migrate its journal.
102
+ Source wiring, isolated CLI fixtures, installation and real-provider dogfood are
103
+ separate evidence: one does not establish the others or universal platform support.
91
104
 
92
105
  The npm package includes root release notes through the `package.json` files
93
106
  allowlist. The Codex installer copies `CHANGELOG.md` alongside `README.md` and
@@ -129,11 +142,14 @@ them. Historical completed tasks are not automatically reopened.
129
142
  Parallel writers also pass the same gate tool with distinct registered
130
143
  worktrees and branches; failure downgrades execution to serial.
131
144
 
132
- This gate checks declarations and content-bound review evidence; it does not make
133
- one provider's result evidence for another provider. Codex and Claude both keep
134
- conversation orchestration in the active Skill and use the same JS gates, while a
135
- fresh context supplies independent review. Real durable N1–N8 dogfood and authorized
136
- installation evidence remain later work; no Claude-native adapter is required.
145
+ This gate checks source declarations and content-bound review evidence; it does
146
+ not authenticate a reviewer or resist a session with full filesystem write access.
147
+ The default JS owner records review results and controls completion; the current
148
+ session fulfills host requests without replacing that durable state. The legacy
149
+ conversation flow invokes the same completion gates explicitly. Fresh review
150
+ contexts and package bindings limit accidental self-review and stale evidence;
151
+ neither provider names nor `independent: true` prove identity. Platform support
152
+ and real-provider execution must be reported against their own verified evidence.
137
153
 
138
154
  ## Current-session driver evidence
139
155
 
@@ -0,0 +1,48 @@
1
+ # Claude review preflight rejects a display notice before init
2
+
3
+ ## Symptom and reproduction
4
+
5
+ Claude Code 2.1.289 emits `system/ui_invalidate` before `system/init` during a
6
+ local, synthetic review preflight. The old decoder returns `missing_init`; the
7
+ worker then stops its own process group. The probe observes only an empty
8
+ startup health request and no messages request, so it correctly refuses to pass.
9
+ Exit 143 is the cleanup consequence, not evidence of a user cancellation or a
10
+ timeout. This probe does not establish the user's account or model access.
11
+
12
+ ## Affected chain and minimal change
13
+
14
+ `cm-ai-host.mjs preflight` → `previewClaudeTools` → `claudeWorker` →
15
+ `createClaudeReviewStream`. The decoder is the first failing edge. It already
16
+ accepts a bounded `dev_intent` notice before init. It now accepts the observed
17
+ `ui_invalidate` subtype there and after init, reporting only a fixed notice.
18
+
19
+ The existing session validation and shared 32-notice cap still apply. This
20
+ notice cannot initialize a turn or provide a verdict. Missing init, mismatched
21
+ sessions, unknown subtypes, post-terminal messages and tool/content violations
22
+ remain failures. Probe HTTP checks, sandbox rules, timeouts, arguments,
23
+ fingerprints, execution storage and developer parsing are unchanged.
24
+
25
+ The reproduction also used a short CLI model alias. The CLI resolves aliases
26
+ to full model IDs, while the existing probe requires the outgoing model to
27
+ equal the configured ID. Live comparisons therefore use the observed full ID;
28
+ model equality is not weakened to make the preflight pass.
29
+
30
+ ## Regression evidence
31
+
32
+ - `cm-claude-review-stream.test.mjs`: pre/post-init notices preserve results and
33
+ observer events; body-free output, session, incomplete/terminal and shared
34
+ budget boundaries remain enforced.
35
+ - `cm-claude-worker.test.mjs`: the startup prefix no longer causes premature
36
+ cleanup; no init or a different session cannot produce success.
37
+ - `cm-claude-probe.test.mjs`: a local sandboxed child emits the prefix before
38
+ POST, exercising the actual failed ordering. Startup-only requests still fail.
39
+
40
+ Before the fix, six of the seven selected regression cases failed. After the
41
+ fix, all 57 tests in these three files passed. Removing only the pre-init
42
+ whitelist entry makes the selected POST regression fail again. Adjacent tests,
43
+ independent implementation review and live two-scenario outcomes are retained
44
+ in the task's local evidence; those checks are not implied by a preflight pass.
45
+
46
+ Applied project lessons: provider dialects belong at the adapter boundary;
47
+ process termination is not user cancellation; tests must be collected by CI;
48
+ real review evidence must precede task completion. 已复盘,无新增项目教训。
@@ -76,7 +76,7 @@ Install or upgrade with the same command:
76
76
  npx @aibyzero/cm-workflow@latest install
77
77
  ```
78
78
 
79
- To pin a version, use `npx @aibyzero/cm-workflow@0.17.0 install` from outside
79
+ To pin a version, use `npx @aibyzero/cm-workflow@0.17.1 install` from outside
80
80
  the CM Workflow source checkout (for example, your home directory). Inside a
81
81
  checkout with the same package name and version, npm can select the local
82
82
  uninstalled package and report `cm-workflow: command not found`.
@@ -79,8 +79,10 @@ cm-ai 宿主返回的可选 `guidance` 说明当前阻塞与下一步:`summary
79
79
  取得它尚未转发的中间内容;无需为这个显示修复重跑或修改正在执行的业务任务。
80
80
 
81
81
  状态卡展示最近开始的阶段,不汇总并行任务;旧 QA/收尾结果仍记在原运行历史,不能覆盖
82
- 其他任务的状态卡。只读 `status` 不落盘刷新。事件更新没有定时心跳,最后更新时间不能
82
+ 其他任务的状态卡。只读 `status` 不落盘刷新。状态卡事件更新没有定时心跳,最后更新时间不能
83
83
  证明进程仍存活;状态文件也不能代替 journal、独立审查或任务完成门禁。
84
+ 驾驶员连接另有 opt-in JSONL 探活、busy 在途详情、默认拒绝在途关闭及独立等待期限;见
85
+ [探活、等待与关闭](../skills/cm-ai/references/js-host.md#探活等待与关闭)。该传输诊断不写入状态卡、journal 或运行指纹。
84
86
  恢复时重放 QA 配置修订、补齐缺失的日志镜像,都不算新阶段,不会重新认领或刷新状态卡。
85
87
 
86
88
  ## cm-fix 本地 unknown 步骤的人工放弃
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -33,6 +33,12 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
33
33
  b: typeof block?.type === 'string' && /^[A-Za-z_]{1,32}$/.test(block.type) ? block.type : null,
34
34
  t: typeof tool === 'string' && /^[A-Za-z0-9_.:-]{1,64}$/.test(tool) ? tool : null,
35
35
  e: typeof isError === 'boolean' ? isError : null});
36
+ const startupNotice = subtype => {
37
+ if (noticeCount >= 32) reject('unexpected_event');
38
+ noticeCount++;
39
+ if (subtype === 'dev_intent') reportClaudeDevIntentNotice(onNotice);
40
+ else try { if (typeof onNotice === 'function') onNotice({kind:'claude_system_notice', subtype:'ui_invalidate'}); } catch {}
41
+ };
36
42
  return Object.freeze({
37
43
  accept(message) {
38
44
  if (!message || typeof message !== 'object' || Array.isArray(message)) reject('invalid_event');
@@ -41,11 +47,11 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
41
47
  || message.session_id.length > 256) reject('invalid_session');
42
48
  if (session !== null && session !== message.session_id) reject('session_mismatch');
43
49
  if (stage === 'init') {
44
- if (message.type === 'system' && message.subtype === 'dev_intent') {
45
- if (noticeCount >= 32) reject('unexpected_event');
46
- noticeCount++;
50
+ // CLI 2.1.289 emits UI invalidation before init. It has no review
51
+ // result and never initializes a turn; retain only its fixed subtype.
52
+ if (message.type === 'system' && ['dev_intent','ui_invalidate'].includes(message.subtype)) {
47
53
  session = message.session_id;
48
- reportClaudeDevIntentNotice(onNotice);
54
+ startupNotice(message.subtype);
49
55
  return;
50
56
  }
51
57
  if (message.type !== 'system' || message.subtype !== 'init') reject('missing_init');
@@ -62,10 +68,8 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
62
68
  return;
63
69
  }
64
70
  if (message.type === 'system') {
65
- if (message.subtype === 'dev_intent') {
66
- if (noticeCount >= 32) reject('unexpected_event');
67
- noticeCount++;
68
- reportClaudeDevIntentNotice(onNotice);
71
+ if (['dev_intent','ui_invalidate'].includes(message.subtype)) {
72
+ startupNotice(message.subtype);
69
73
  return;
70
74
  }
71
75
  if (message.subtype === 'thinking_tokens') {
@@ -1,5 +1,6 @@
1
1
  // Execution choices and stale-command protection, not human authentication.
2
2
  import fs from 'node:fs';
3
+ import {projectOperatorGuidance} from './operator-guidance.mjs';
3
4
  import {digest,json,need,shape,validIdentity,hex,id} from './effect-contract.mjs';
4
5
  import {parseModelJson} from './model-configuration-file.mjs';
5
6
 
@@ -77,7 +78,7 @@ export function withControlPolicyHost(host,{identity,snapshot,launchTarget=null}
77
78
  need(recovering||!Object.hasOwn(request,'expectedControl'),'invalid_input');
78
79
  const {expectedControl,...wire}=request;wire.version=1;
79
80
  // A busy poll cannot publish a recovery target.
80
- if(busy)return host.handle(wire);
81
+ if(busy)return projectOperatorGuidance(await host.handle(wire),{protocol:'v2'});
81
82
  busy=true;ownsBusy=true;
82
83
  if(recovering){
83
84
  checking=false;
@@ -92,7 +93,7 @@ export function withControlPolicyHost(host,{identity,snapshot,launchTarget=null}
92
93
  need(digest(wire.identity)===digest(status.identity),'snapshot_changed');
93
94
  }
94
95
  checking=false;
95
- const result=await host.handle(wire);
96
+ const result=projectOperatorGuidance(await host.handle(wire),{protocol:'v2'});
96
97
  if(request.operation==='fix_status'&&result.childControlTarget){
97
98
  const parent=await host.handle({version:1,requestId:request.requestId,operation:'status',identity});
98
99
  return {...result,controlTarget:{...controlTarget(parent,snapshot()),child:readFixControlTarget(result.childControlTarget)}};
@@ -61,15 +61,22 @@ export function deliberatelyUnanswered(message){
61
61
  if(!deliberateStop){deliberateStop=true;process.on('exit',()=>{process.exitCode=2;});}
62
62
  return Object.assign(new Error(message),{code:'confirm_reask_decision_required'});
63
63
  }
64
- export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null}){
65
- const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
64
+ // Transport-only budgets: no field is added to a run or its configuration hash.
65
+ // The long fallback covers hosts that cannot advertise individual phase budgets.
66
+ export const DRIVE_LIVENESS_DEFAULTS=Object.freeze({startupMs:60000,operationMs:21600000,
67
+ heartbeatMs:30000,graceMs:30000,closeMs:5000,killMs:1000,pollMs:250});
68
+ export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null,liveness={}}){
69
+ const budget={...DRIVE_LIVENESS_DEFAULTS,...liveness};
70
+ for(const value of Object.values(budget))if(!Number.isSafeInteger(value)||value<1)throw Error('driver_liveness_invalid');
71
+ const ownGroup=process.platform!=='win32';
72
+ const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe'],detached:ownGroup,
73
+ env:{...process.env,CM_HOST_HEARTBEAT:'1'}});
66
74
  const control=new AbortController();
67
75
  child.stderr.on('data',chunk=>process.stderr.write(chunk));
68
- // After a rejected reply the session is ended; later rows get no answer.
69
- const send=value=>{if(!child.stdin.writableEnded)child.stdin.write(JSON.stringify(value)+'\n');};
70
76
  let done=false,refused=false,rejected=null,unanswered=false,finalRow=null,noticed=false,failureCode=null;
71
- // Optional stuck/done notice (runtime/js/notify.mjs): decided once when the
72
- // host is gone. It is loaded lazily and can never change exit code or output.
77
+ let sessionId=null,ready=false,heartbeat=false,lastBeat=0,waitingFor='drive',stopping=false,closed=false;
78
+ let deadline=Date.now()+budget.startupMs,phase='startup',closeDeadline=null,killTimer=null,forceTimer=null;
79
+ // Optional notices never change the result or make watchdog failures successful.
73
80
  const notice=failure=>{
74
81
  if(noticed)return;noticed=true;
75
82
  if(rejected!==null)failure='host_response_rejected';else if(!failure&&unanswered&&!finalRow)failure='host_request_unanswered';
@@ -78,51 +85,143 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
78
85
  return fields?notify(fields):null;
79
86
  }).catch(()=>{});
80
87
  };
81
- readline.createInterface({input:child.stdout}).on('line',async line=>{
88
+ const signalOwnHost=(signal,cleanup=false)=>{
89
+ if((closed&&!cleanup)||!child.pid)return;
90
+ try{if(ownGroup)process.kill(-child.pid,signal);else child.kill(signal);}catch{}
91
+ };
92
+ const fail=(code,reason,message)=>{
93
+ if(stopping||closed)return;
94
+ stopping=true;failureCode=reason;control.abort();process.exitCode=code;
95
+ stderr(`${reason}:${message};未写入成功或取消结果;清理仅覆盖本驾驶员创建的进程组,脱离该组的后代须另行核对,恢复前请核对原运行`);
96
+ // Only the process/group created here is eligible for cleanup. Never inspect
97
+ // or signal PIDs received from a host message or another run's heartbeat.
98
+ signalOwnHost('SIGTERM');
99
+ killTimer=setTimeout(()=>{
100
+ signalOwnHost('SIGKILL',true);
101
+ if(closed)return;
102
+ forceTimer=setTimeout(()=>{child.stdin.destroy();child.stdout.destroy();child.stderr.destroy();child.unref();clearInterval(watchdog);notice(failureCode);},budget.killMs);
103
+ forceTimer.unref();
104
+ },budget.killMs);
105
+ // Keep cleanup alive after the host exits: same-group workers can ignore
106
+ // SIGTERM and use stdio:ignore, so child.close does not prove group exit.
107
+ };
108
+ const send=value=>{
109
+ if(stopping||closed)return;
110
+ if(child.stdin.destroyed||child.stdin.writableEnded){fail(74,'host_pipe_closed','宿主输入管道没有可写端');return;}
111
+ try{child.stdin.write(JSON.stringify(value)+'\n',error=>{if(error)fail(74,'host_pipe_closed','宿主输入管道已关闭,无法发送请求');});}
112
+ catch{fail(74,'host_pipe_closed','宿主输入管道已关闭,无法发送请求');}
113
+ };
114
+ const closeHost=force=>{
115
+ if(stopping||closed)return;
116
+ closeDeadline=Date.now()+budget.closeMs;
117
+ if(force)stderr('显式 force 关闭无法继续应答的宿主;在途步骤可能进入 unknown,请核对原运行');
118
+ send({type:'host_close',sessionId,...(force?{force:true}:{})});
119
+ if(force&&!heartbeat){
120
+ stderr('旧宿主未声明关闭握手能力:已显式请求 force,随后结束输入以兼容旧宿主;在途步骤可能进入 unknown');
121
+ child.stdin.end();
122
+ }
123
+ };
124
+ const phaseDeadlines=new Map();
125
+ const phaseBudget=inFlight=>{
126
+ const candidates=[];
127
+ for(const [prefix,value,id] of [['call',inFlight?.call,inFlight?.call?.callId],
128
+ ['native',inFlight?.nativeStage,inFlight?.nativeStage?.id]]){
129
+ if(typeof id!=='string'||!Number.isSafeInteger(value?.deadlineMs))continue;
130
+ const key=`${prefix}:${id}`;
131
+ // Keep the first announced deadline, including while a nested phase is
132
+ // active. A heartbeat or return to its enclosing phase cannot extend it.
133
+ if(!phaseDeadlines.has(key))phaseDeadlines.set(key,value.deadlineMs+budget.graceMs);
134
+ candidates.push({key,deadline:phaseDeadlines.get(key)});
135
+ }
136
+ if(candidates.length){phase=candidates.map(item=>item.key).join('|');deadline=Math.min(...candidates.map(item=>item.deadline));}
137
+ else if(phase!=='operation'){phase='operation';deadline=Date.now()+budget.operationMs;}
138
+ };
139
+ const watchdog=setInterval(()=>{
140
+ if(stopping||closed)return;
141
+ const now=Date.now();
142
+ if(closeDeadline!==null){if(now>closeDeadline)fail(failureCode==='host_exited'?71:75,failureCode==='host_exited'?'host_exited':'host_close_timeout','宿主或其继承管道未在关闭期限内退出');return;}
143
+ if(ready&&heartbeat&&now-lastBeat>budget.heartbeatMs){fail(72,'host_heartbeat_timeout','宿主心跳超时,进程可能已卡死');return;}
144
+ if(now>deadline)fail(ready?73:70,ready?'host_stage_timeout':'host_start_timeout',ready?'当前阶段超过已声明期限或有界后备期限':'宿主未在启动期限内发出 host_ready');
145
+ },budget.pollMs);
146
+ child.stdin.on('error',()=>fail(74,'host_pipe_closed','宿主输入管道已关闭,无法继续写入'));
147
+ child.stdin.on('close',()=>{if(!done&&!refused&&!unanswered&&rejected===null&&!stopping&&!closed&&failureCode!=='host_exited')fail(74,'host_pipe_closed','宿主输入管道提前关闭');});
148
+ const lines=readline.createInterface({input:child.stdout});
149
+ lines.on('line',async line=>{
82
150
  let row;try{row=JSON.parse(line);}catch{process.stdout.write(line+'\n');return;}
151
+ if(stopping||closed||done)return;
152
+ if(row.type==='host_heartbeat'){
153
+ if(ready&&heartbeat&&row.sessionId===sessionId){lastBeat=Date.now();phaseBudget(row.inFlight);}
154
+ return;
155
+ }
83
156
  if(row.type==='host_ready'){
157
+ if(ready)return;
158
+ ready=true;sessionId=row.sessionId;heartbeat=Boolean(row.heartbeat);lastBeat=Date.now();
159
+ phase='operation';deadline=Date.now()+budget.operationMs;
84
160
  if(beforeRequest){
85
161
  let refusal;
86
162
  try{refusal=await beforeRequest();}catch(error){refusal=`发送操作前的准备失败:${error.message}`;}
87
- if(refusal){refused=true;failureCode='driver_refused';stderr(refusal);process.exitCode=2;send({type:'host_close',sessionId:row.sessionId});child.stdin.end();return;}
163
+ if(stopping||closed)return;
164
+ if(refusal){refused=true;failureCode='driver_refused';stderr(refusal);process.exitCode=2;closeHost(false);return;}
88
165
  }
89
166
  send({requestId:'drive',operation,...request});return;
90
167
  }
91
168
  if(row.type==='host_request'){
169
+ if(done||unanswered||rejected!==null)return;
92
170
  let result;
93
171
  try{result=await answerFor(row,answers,paths,{signal:control.signal});}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
94
- if(control.signal.aborted)return;
172
+ if(control.signal.aborted||stopping||closed)return;
95
173
  if(result===null){
96
- unanswered=true;
97
- stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答;这一步会留在 unknown`);
98
- send({type:'host_close',sessionId:row.sessionId});return;
174
+ unanswered=true;process.exitCode=deliberateStop?2:1;
175
+ stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答`);
176
+ closeHost(true);return;
99
177
  }
100
178
  stderr(`应答 ${row.kind}`);
101
179
  send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
102
180
  return;
103
181
  }
104
182
  if(row.type==='host_response'){
183
+ if(row.code==='host_close_busy'){
184
+ stderr('host_close_busy:宿主仍有在途工作;继续等待原请求结果');closeDeadline=null;return;
185
+ }
186
+ if(row.accepted===true&&row.closing===true){child.stdin.end();return;}
105
187
  if(row.accepted===false&&rejected===null){
106
- rejected=typeof row.code==='string'?row.code:'host_response_rejected';
107
- control.abort();
108
- stderr(`宿主拒收了应答:${rejected};${rejectedReplyHint(rejected)}。驾驶员不再等待,已结束会话;宿主会把这一步记为 unknown`);
109
- child.stdin.end();
188
+ rejected=typeof row.code==='string'?row.code:'host_response_rejected';control.abort();process.exitCode=1;
189
+ stderr(`宿主拒收了应答:${rejected};${rejectedReplyHint(rejected)}`);
190
+ closeHost(true);
110
191
  }
111
192
  return;
112
193
  }
113
- if(row.requestId==='drive'){
114
- done=true;finalRow=row;
115
- control.abort();
194
+ if(row.requestId===waitingFor||row.requestId==='drive'){
195
+ if(row.error?.code==='host_busy'){
196
+ const inFlight=row.error.inFlight;
197
+ if(typeof inFlight?.requestId==='string')waitingFor=inFlight.requestId;
198
+ phaseBudget(inFlight);stderr(`host_busy:上一步仍在执行,继续等待 ${waitingFor} 的结果`);return;
199
+ }
200
+ done=true;finalRow=row;control.abort();
116
201
  process.stdout.write(JSON.stringify(row,null,2)+'\n');
117
202
  const guidance=guidanceText(row.result);if(guidance)stderr(guidance);
118
203
  if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
119
204
  if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
120
- process.exitCode=hostResponseFailed(row)||rejected!==null?1:0;
121
- child.stdin.end();
205
+ process.exitCode=deliberateStop||refused?2:hostResponseFailed(row)||rejected!==null||unanswered?1:0;
206
+ // Normal EOF follows a final result. The explicit force compatibility
207
+ // path for a legacy host is separately logged by closeHost above.
208
+ closeDeadline=Date.now()+budget.closeMs;child.stdin.end();
209
+ }
210
+ });
211
+ child.on('error',()=>fail(71,'host_start_failed','宿主进程无法启动'));
212
+ child.on('exit',(code,signal)=>{
213
+ control.abort();
214
+ if(!done&&!refused&&!stopping&&!unanswered&&rejected===null){
215
+ failureCode='host_exited';stderr(`host_exited:宿主在给出结果前退出了,exit ${code},signal ${signal??'none'}`);process.exitCode=71;closeDeadline=Date.now()+budget.closeMs;
122
216
  }
123
217
  });
124
- child.on('error',error=>{control.abort();stderr(`宿主启动失败:${error.message}`);process.exitCode=1;notice('host_start_failed');});
125
- child.on('exit',code=>{control.abort();if(!done&&!refused){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
126
- // 'close' waits for the host's stdout, so a final row still in flight is seen.
127
- child.on('close',()=>notice(failureCode??(done?null:'host_exited')));
218
+ // close drains stdout so a buffered final result can still determine outcome.
219
+ child.on('close',()=>{
220
+ // stdout has drained now; absence of a final result is definitive. Clean
221
+ // this spawn's process group even if ignored stdio let its leader close.
222
+ if(!done&&!refused&&!unanswered&&rejected===null&&!stopping)fail(71,'host_exited','宿主未返回结果,清理其在途进程组');
223
+ closed=true;control.abort();clearInterval(watchdog);
224
+ if(!stopping)clearTimeout(killTimer);
225
+ clearTimeout(forceTimer);lines.close();notice(failureCode??(done?null:'host_exited'));
226
+ });
128
227
  }
@@ -1,6 +1,7 @@
1
1
  // Runs host-configured, already-authorized project checks. Commands may execute
2
2
  // project code; specsRoot opts into Codex's native sandbox for that subprocess.
3
3
  // Without specsRoot this preserves the existing direct host-check behavior.
4
+ import {beginHostStage} from './host-stage-observer.mjs';
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
6
7
  import {spawn} from 'node:child_process';
@@ -55,6 +56,7 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
55
56
  ...(signature?{signatureMatched:original.signatureMatched}:{})});continue;
56
57
  }
57
58
  notify({phase:'start',id:item.id});
59
+ const endStage=beginHostStage('check',timeoutMs);
58
60
  const result=await new Promise(resolve=>{
59
61
  let child;
60
62
  try{
@@ -126,7 +128,7 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
126
128
  evidence:prefix+(summary.length?` (${summary.join(', ')})`:'')});
127
129
  }
128
130
  });
129
- });
131
+ }).finally(endStage);
130
132
  notify({phase:'complete',id:item.id,outcome:result.outcome,exitCode:result.exitCode});
131
133
  need(!signal.aborted,'cancelled');
132
134
  results.push({id:item.id,command:item.command,...result,...(signature?{signatureMatched}:{})});