@aibyzero/cm-workflow 0.16.2 → 0.16.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 (155) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +147 -0
  4. package/README.md +44 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +46 -7
  8. package/docs/next-steps.md +100 -0
  9. package/docs/untested-branches.md +24 -18
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
  12. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +7 -1
  14. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  15. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  17. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  18. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  19. package/runtime/js/cm-ai/effect-contract.mjs +4 -3
  20. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  22. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  23. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  24. package/runtime/js/cm-ai/host-session.mjs +10 -3
  25. package/runtime/js/cm-ai/host.mjs +1 -1
  26. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  27. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  28. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  29. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  30. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  31. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  32. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  33. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  34. package/runtime/js/cm-fix/dossier.mjs +40 -1
  35. package/runtime/js/cm-fix/execution.mjs +360 -83
  36. package/runtime/js/cm-fix/host.mjs +7 -3
  37. package/runtime/js/cm-fix/layout.mjs +14 -6
  38. package/runtime/js/cm-fix/progress.mjs +14 -0
  39. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  40. package/runtime/js/cm-fix/red-test.mjs +7 -6
  41. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  42. package/runtime/js/cm-fix/regression.mjs +16 -10
  43. package/runtime/js/cm-fix/repair.mjs +16 -13
  44. package/runtime/js/cm-fix/test-author.mjs +2 -1
  45. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  46. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  47. package/runtime/js/cm-prd/analysis.mjs +68 -16
  48. package/runtime/js/cm-prd/change.mjs +21 -1
  49. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  50. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  51. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  52. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  53. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  54. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  55. package/runtime/js/cm-prd/review-host.mjs +2 -0
  56. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  57. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  58. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  59. package/runtime/js/cm-prd/session.mjs +5 -5
  60. package/runtime/js/cm-prd/split-design.mjs +67 -0
  61. package/runtime/js/cm-prd/summary.mjs +57 -10
  62. package/runtime/js/cm-refactor/workflow.mjs +100 -19
  63. package/runtime/js/specs-status.mjs +6 -2
  64. package/scripts/cm-ai-admission.mjs +2 -0
  65. package/scripts/cm-ai-batch-drive.mjs +251 -0
  66. package/scripts/cm-ai-batch-drive.test.mjs +159 -0
  67. package/scripts/cm-ai-batch-host.mjs +13 -5
  68. package/scripts/cm-ai-batch-host.test.mjs +25 -0
  69. package/scripts/cm-ai-contracts.test.mjs +30 -0
  70. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  71. package/scripts/cm-ai-drive.mjs +335 -0
  72. package/scripts/cm-ai-drive.test.mjs +258 -0
  73. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  74. package/scripts/cm-ai-host.mjs +48 -20
  75. package/scripts/cm-ai-host.test.mjs +79 -0
  76. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  77. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  78. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  79. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  80. package/scripts/cm-ai-run.mjs +59 -11
  81. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  82. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  83. package/scripts/cm-ai-supersede.test.mjs +320 -0
  84. package/scripts/cm-check-drive.mjs +94 -0
  85. package/scripts/cm-check-drive.test.mjs +78 -0
  86. package/scripts/cm-check-entry.mjs +13 -2
  87. package/scripts/cm-check-host.mjs +2 -2
  88. package/scripts/cm-check-host.test.mjs +103 -0
  89. package/scripts/cm-check-runtime.sh +15 -6
  90. package/scripts/cm-claude-developer-worker.test.mjs +40 -1
  91. package/scripts/cm-claude-probe.test.mjs +117 -2
  92. package/scripts/cm-claude-review-stream.test.mjs +43 -0
  93. package/scripts/cm-fix-abandon.test.mjs +383 -0
  94. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  95. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  96. package/scripts/cm-fix-drive.mjs +168 -0
  97. package/scripts/cm-fix-drive.test.mjs +117 -0
  98. package/scripts/cm-fix-escalation.test.mjs +214 -0
  99. package/scripts/cm-fix-execution.test.mjs +26 -0
  100. package/scripts/cm-fix-host.mjs +4 -2
  101. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  102. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  103. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  104. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  105. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  106. package/scripts/cm-host-handoff.test.mjs +37 -0
  107. package/scripts/cm-idea-drive.mjs +99 -0
  108. package/scripts/cm-idea-drive.test.mjs +50 -0
  109. package/scripts/cm-init-drive.mjs +191 -0
  110. package/scripts/cm-init-drive.test.mjs +59 -0
  111. package/scripts/cm-log-event.mjs +9 -0
  112. package/scripts/cm-prd-completion.test.mjs +30 -2
  113. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  114. package/scripts/cm-prd-drive.mjs +314 -0
  115. package/scripts/cm-prd-drive.test.mjs +164 -0
  116. package/scripts/cm-prd-host.mjs +46 -17
  117. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  118. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  119. package/scripts/cm-prd-review-gate.mjs +23 -4
  120. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  121. package/scripts/cm-prd-summary.test.mjs +79 -4
  122. package/scripts/cm-refactor-drive.mjs +237 -0
  123. package/scripts/cm-refactor-drive.test.mjs +77 -0
  124. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  125. package/scripts/cm-refactor-host.test.mjs +1 -48
  126. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  127. package/scripts/cm-specs-status.test.mjs +19 -0
  128. package/scripts/cm-test-drive.mjs +132 -0
  129. package/scripts/cm-test-drive.test.mjs +91 -0
  130. package/scripts/cm-test-session.test.mjs +117 -0
  131. package/scripts/correction-check.test.mjs +38 -0
  132. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  133. package/scripts/fixtures/claude-review-process.mjs +7 -0
  134. package/scripts/fixtures/cm-refactor.mjs +56 -0
  135. package/scripts/test-shell-compat.sh +67 -0
  136. package/skills/cm-ai/SKILL.md +1 -1
  137. package/skills/cm-ai/references/N4-review.md +2 -0
  138. package/skills/cm-ai/references/N8-finish.md +1 -0
  139. package/skills/cm-ai/references/js-host.md +85 -3
  140. package/skills/cm-check/SKILL.md +6 -1
  141. package/skills/cm-check/references/js-host.md +4 -2
  142. package/skills/cm-fix/SKILL.md +11 -4
  143. package/skills/cm-fix/references/js-host.md +67 -2
  144. package/skills/cm-fix/references/test-extension.md +57 -0
  145. package/skills/cm-idea/references/js-host.md +2 -0
  146. package/skills/cm-init/references/js-host.md +2 -0
  147. package/skills/cm-prd/SKILL.md +8 -8
  148. package/skills/cm-prd/references/js-change-recovery.md +71 -0
  149. package/skills/cm-prd/references/js-host.md +64 -2
  150. package/skills/cm-prd/references/spec-self-check.md +14 -2
  151. package/skills/cm-refactor/SKILL.md +5 -0
  152. package/skills/cm-refactor/references/js-batch.md +3 -1
  153. package/skills/cm-refactor/references/js-host.md +49 -0
  154. package/skills/cm-test/references/js-host.md +5 -0
  155. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -14,8 +14,8 @@
14
14
  一次实跑再撞。
15
15
 
16
16
  `scripts/audit-untested-enums.mjs` 扫 `runtime/js` 里 `['a','b'].includes(x)` 形式的枚举,
17
- 逐个看 `scripts/*.test.mjs` 里有没有出现过。写这份文档时的结果:**51 个取值缺覆盖,
18
- 分布在 49 处**。
17
+ 逐个看 `scripts/*.test.mjs` 里有没有出现过。写这份文档时的结果是 51 个取值缺覆盖;补掉 A 类的 `auto_fix: never`、`video`、cm-check `configured`、cm-fix `design_change`、cm-test 中断步骤恢复和 cm-refactor 两条之后现在是
18
+ **38 个,分布在 40 处**(本次从 45 个、42 处降下)。
19
19
 
20
20
  脚本输出的是**候选,不是待办**——内部记录类型和 `typeof` 判断也会被匹配到。下面是人工
21
21
  分好的类。改完代码后重跑脚本对照。
@@ -28,29 +28,35 @@
28
28
 
29
29
  | 取值 | 位置 | 承诺在哪 | 补测试前要先弄清 |
30
30
  | --- | --- | --- | --- |
31
- | `auto_fix: never` | `cm-ai/host-qa-fix.mjs:21` | `templates/cm-workflow.yml` 写着 `explicit \| never \| auto`;`runtime/workflow-config.md` 说它决定「N6 失败后的三分支」 | `never` 下 QA 失败到底该停在哪、和 `explicit` 的差别是什么 |
32
- | 视觉证据 `kind: video` | `cm-ai/review-package.mjs:371` | `cm-fix-host.mjs --help` 明写 `before:{path,sha256,kind:screenshot\|video,...}` | 录屏载体的校验和取证跟截图有没有实质差别 |
33
- | 诊断 `design_change` | `cm-fix/cause-package.mjs` | cm-fix SKILL 第 4 步「升级出口」:停止硬修、转 `$cm-prd --change` 立项 | 这条出口下红灯测试要保留、档案要记「升级立项」,这些有没有真发生 |
34
- | cm-check `configured` | `cm-check/host.mjs:105` | 三态之一(`configured\|degraded\|unknown`) | 什么条件算 configured,和 degraded 的边界 |
35
- | cm-test `snapshot` / `evaluation` | `cm-test/session.mjs:47` | 两种模式**都**没被测过 | 两种模式各自的输入和产物 |
36
- | cm-refactor 规则三态 | `cm-refactor/workflow.mjs:244` | `rule_correct\|rule_missing\|rule_wrong` 全没测过 | 规则判定的输入从哪来、三态各自怎么触发 |
37
- | cm-refactor 四个失败码 | `cm-refactor/workflow.mjs:322` | 全没测过 | 每个码对应的真实冲突场景 |
31
+ | ~~`auto_fix: never`~~ | `cm-ai/host-qa-fix.mjs:21` | 同上 | **已补**:`cm-ai-qa-fix-policy.test.mjs` 钉死三取值各自的去向,并覆盖「轮次耗尽压过策略」这条优先级 |
32
+ | ~~视觉证据 `kind: video`~~ | `cm-ai/review-package.mjs:371` | 同上 | **已补**:`cm-fix-visual-carrier.test.mjs` 验录屏容器格式、声明与字节必须双向一致、哈希绑定 |
33
+ | ~~诊断 `design_change`~~ | `cm-fix/cause-package.mjs` | cm-fix SKILL 第 4 步「升级出口」:停止硬修、转 `$cm-prd --change` 立项 | **已补**:`scripts/cm-fix-escalation.test.mjs` 覆盖保留真实红测、升级档案、终态、崩溃恢复与冲突、普通记录兼容及 QA 父子退出,并做变异验证 |
34
+ | ~~cm-check `configured`~~ | `cm-check/host.mjs:105` | 三态之一(`configured\|degraded\|unknown`) | **已补**:`scripts/cm-check-host.test.mjs` 钉死三态及混合报告原样回传、不改变核心判定,以及非法报告的精确阻断原因 |
35
+ | ~~cm-test `snapshot` / `evaluation`~~ | `cm-test/session.mjs:47` | 中断后允许重做的两种纯读步骤,不是用户模式 | **已补**:`scripts/cm-test-session.test.mjs` 覆盖纯读步骤重做、其它步骤不重做、command/host 原结果回执的身份校验与来源记录,以及全部七种已完成步骤的回放,并做变异验证 |
36
+ | ~~cm-refactor 规则三态~~ | `cm-refactor/workflow.mjs` | `rule_correct\|rule_missing\|rule_wrong` | **已补**:`scripts/cm-refactor-gaps.test.mjs` 覆盖三态、混合裁决、逐文件覆盖、拒绝原因码、隔离通道、报告及裁决后规则传递;规则缺失或错误必须伴随手册修订,仅改行尾空白、换行符及首尾空行也会在报告和试点前拒绝,修订效果仍待独立审查 |
37
+ | ~~cm-refactor 四个失败码~~ | `cm-refactor/workflow.mjs:322` | 冲突或结果不明时停机,不能覆盖别人改动 | **已补**:`scripts/cm-refactor-gaps.test.mjs` 用真实恢复、磁盘改动和原子写入冲突验证四码停机,普通失败则恢复并重试;变异验证限制见下文 |
38
38
 
39
39
  **建议按模块分批**,不要一次全开。cm-prd、cm-refactor、cm-test、cm-check 这四块各自
40
40
  独立,给一条从没走过的分支补测试,得先读懂那条分支本来该是什么行为——读浅了会写出
41
41
  「形状对但没验到点上」的测试,那比没有更糟:它让人以为测过了。
42
42
 
43
+ A 类七条清单已完成,都做了**变异验证**——故意把被测代码改坏,确认测试会红。
44
+ cm-refactor 的 `refactor_unknown_effect` 列表成员是冗余防线:`unknown()` 已覆盖所有公开触发路径。
45
+ 单独移除该成员不改变停机行为,这个变异存活,不宣称被测试捕获;真实恢复用例仍验证结果不明时停机。
46
+ 新写的测试本来就该过,过了不代表验到了点上。
47
+
43
48
  ## B 类:内部协议分支,值得测但不紧急
44
49
 
45
- - `cm-ai/claude-tool-preview.mjs:51` —— `gzip` / `zstd` 传输编码,只测过 `identity`
46
- - `cm-ai/tool-preview.mjs` —— `argument` 提示词传输方式,全部现有用例走 `stdin`
47
- - `cm-ai/contracts.mjs` —— 状态机取值 `waiting_user` / `deny` / `revoked` / `active`
48
- - `cm-ai/durable-runner-state.mjs:215,336` —— `grant_expired` / `clock_invalid`
49
- - `cm-ai/cm-ai-conversation-entry.mjs:48-56` —— `context_refresh` / `run_finalize`
50
- - `cm-prd/correction-check.mjs:28,45` —— `mechanical_failed` / `context_result`
50
+ 清单已清空。六项都在 CI 执行的 `scripts/*.test.mjs` 里有了测试,每条都做过变异验证:
51
51
 
52
- 这些不在用户配置面上,踩中的路径更窄。但 `grant_expired` 和 `clock_invalid` 关系到授权
53
- 凭据的过期判定,真出问题代价不小,排在 B 类的前面。
52
+ | 分支 | 测试文件 |
53
+ | --- | --- |
54
+ | `cm-ai/durable-runner-state.mjs` 的 `grant_expired` / `clock_invalid` | `scripts/cm-ai-review-timeout.test.mjs` |
55
+ | `cm-ai/cm-ai-conversation-entry.mjs` 的 `context_refresh` / `run_finalize` | `scripts/cm-ai-conversation-entry-ops.test.mjs` |
56
+ | `cm-ai/contracts.mjs` 的 `waiting_user` / `deny` / `revoked` / `active` | `scripts/cm-ai-contracts.test.mjs` |
57
+ | `cm-ai/tool-preview.mjs` 的 `argument` | `scripts/cm-claude-probe.test.mjs` |
58
+ | `cm-ai/claude-tool-preview.mjs` 的 `gzip` / `zstd` 与未声明编码 | `scripts/cm-claude-probe.test.mjs`(真实回环监听器;只在 macOS 运行,Linux CI 跳过) |
59
+ | `cm-prd/correction-check.mjs` 的 `mechanical_failed` / `context_result` | `scripts/correction-check.test.mjs` |
54
60
 
55
61
  ## C 类:噪声,不必单独补
56
62
 
@@ -66,7 +72,7 @@
66
72
  ## 这份清单的局限
67
73
 
68
74
  - 只扫 `['a','b'].includes(x)` 这一种写法。`switch`、对象查表、`Set.has` 都漏掉了,
69
- 所以 51 是**下限**不是全部。
75
+ 所以当前的 38 是**下限**不是全部。
70
76
  - 「测试里出现过这个字符串」只能说明它被提到过,不等于那条分支被真正走到并断言了。
71
77
  A 类里每一条仍要人去确认。
72
78
  - 最重要的一点:上表那四个缺陷是**跑真实项目**跑出来的,不是读代码读出来的。这份清单
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.16.2",
3
+ "version": "0.16.4",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -10,6 +10,11 @@ export function reportClaudeRateLimitNotice(raw, onNotice) {
10
10
  try { onNotice({kind:'rate_limit', info}); } catch {}
11
11
  }
12
12
 
13
+ export function reportClaudeDevIntentNotice(onNotice) {
14
+ if (typeof onNotice !== 'function') return;
15
+ try { onNotice({kind:'claude_system_notice', subtype:'dev_intent'}); } catch {}
16
+ }
17
+
13
18
  export function createClaudeReviewStream(onEvent, onNotice = null) {
14
19
  let session = null, stage = 'init', value, noticeCount = 0, thinkingCount = 0, rejectedAttempts = 0;
15
20
  const pendingTools = new Map(), toolIds = new Set();
@@ -22,6 +27,13 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
22
27
  || message.session_id.length > 256) reject('invalid_session');
23
28
  if (session !== null && session !== message.session_id) reject('session_mismatch');
24
29
  if (stage === 'init') {
30
+ if (message.type === 'system' && message.subtype === 'dev_intent') {
31
+ if (noticeCount >= 32) reject('unexpected_event');
32
+ noticeCount++;
33
+ session = message.session_id;
34
+ reportClaudeDevIntentNotice(onNotice);
35
+ return;
36
+ }
25
37
  if (message.type !== 'system' || message.subtype !== 'init') reject('missing_init');
26
38
  session = message.session_id;
27
39
  stage = 'assistant';
@@ -36,6 +48,12 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
36
48
  return;
37
49
  }
38
50
  if (message.type === 'system') {
51
+ if (message.subtype === 'dev_intent') {
52
+ if (noticeCount >= 32) reject('unexpected_event');
53
+ noticeCount++;
54
+ reportClaudeDevIntentNotice(onNotice);
55
+ return;
56
+ }
39
57
  if (message.subtype === 'thinking_tokens') {
40
58
  // Long reviews emit usage heartbeats; worker-claude also caps total output at 1 MB.
41
59
  if (thinkingCount >= 4096) reject('unexpected_event');
@@ -7,6 +7,38 @@ import {spawn} from 'node:child_process';
7
7
  import {gunzipSync,zstdDecompressSync} from 'node:zlib';
8
8
  import {claudeWorker,claudeReviewFingerprint} from './worker-claude.mjs';
9
9
 
10
+ const UNRECOGNIZED_MODEL_MARKER='[claude-code:unrecognized_model]';
11
+ export function createClaudeModelMarkerDetector(onMarker) {
12
+ let matched=0,found=false,reported=false,jsonTail='';
13
+ const report=()=>{
14
+ if(reported||!found)return;
15
+ reported=true;
16
+ let model=null;
17
+ try {
18
+ const value=JSON.parse(jsonTail.trim());
19
+ if(typeof value?.model==='string'&&/^[a-zA-Z0-9._-]+$/.test(value.model))model=value.model;
20
+ }catch{}
21
+ onMarker({reported_model:model});
22
+ jsonTail='';
23
+ };
24
+ return {
25
+ accept(chunk){
26
+ for(const char of String(chunk)){
27
+ if(reported)break;
28
+ if(found){
29
+ if(char==='\n'||char==='\r'){report();continue;}
30
+ if(jsonTail.length<512)jsonTail+=char;
31
+ else report();
32
+ }else if(char===UNRECOGNIZED_MODEL_MARKER[matched]){
33
+ matched++;
34
+ if(matched===UNRECOGNIZED_MODEL_MARKER.length)found=true;
35
+ }else matched=char===UNRECOGNIZED_MODEL_MARKER[0]?1:0;
36
+ }
37
+ },
38
+ finish:report,
39
+ };
40
+ }
41
+
10
42
  export function claudeProbeSandbox(temp,port) {
11
43
  if(!path.isAbsolute(temp)||!Number.isInteger(port)||port<1||port>65535)throw Error('invalid_probe');
12
44
  return `(version 1)(allow default)(deny network*)
@@ -23,7 +55,7 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
23
55
  const fingerprint=claudeReviewFingerprint({cwd,model,cli});
24
56
  const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-claude-probe-')));
25
57
  const observations=[];
26
- const controller=new AbortController();let stoppedByProbe=false;
58
+ const controller=new AbortController();let stoppedByProbe=false,modelMarker=null;
27
59
  const server=http.createServer((request,response)=>{
28
60
  const index=observations.length;
29
61
  if(index<8)observations.push({valid:false});else observations[0]={valid:false};
@@ -84,11 +116,17 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
84
116
  // Internal diagnostic bootstrap: same worker lifecycle, forced sink and synthetic prompt only.
85
117
  // This object is never returned as a passing receipt without examining the captured request.
86
118
  const worker=claudeWorker({cwd,model,cli,preflight,timeoutMs:15000,
87
- spawnProcess:(command,args,options)=>spawnProcess('/usr/bin/sandbox-exec',
88
- ['-p',claudeProbeSandbox(temp,port),command,...args],{...options,env:{...options.env,
119
+ spawnProcess:(command,args,options)=>{
120
+ const child=spawnProcess('/usr/bin/sandbox-exec',
121
+ ['-p',claudeProbeSandbox(temp,port),command,...args],{...options,env:{...options.env,
89
122
  ANTHROPIC_API_KEY:'cm-synthetic-local-probe',ANTHROPIC_BASE_URL:`http://127.0.0.1:${port}`,
90
123
  CLAUDE_CONFIG_DIR:temp,CLAUDE_CODE_TMPDIR:temp,
91
- CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:'1',TMPDIR:temp}})});
124
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:'1',TMPDIR:temp}});
125
+ const detector=createClaudeModelMarkerDetector(value=>{modelMarker=value;});
126
+ child.stderr.on('data',detector.accept);
127
+ child.stderr.once('end',detector.finish);
128
+ return child;
129
+ }});
92
130
  result=await worker({prompt:'Return JSON for synthetic diagnostic task CM-PROBE-001.'},
93
131
  {signal:controller.signal,onEvent:event=>{
94
132
  if(event.event==='process_closed')closeEvidence=event;
@@ -100,10 +138,11 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
100
138
  }
101
139
  const messages=observations.filter(item=>item.startup!==true);
102
140
  return {model,disabledSkills:[],preflight:{provider:'claude',prompt_transport:'stdin',
103
- config_fingerprint:fingerprint,passed:messages.length>=1&&messages.length<=2&&messages.every(message=>message.valid)
141
+ config_fingerprint:fingerprint,passed:modelMarker===null&&messages.length>=1&&messages.length<=2&&messages.every(message=>message.valid)
104
142
  &&stoppedByProbe&&result?.status==='cancelled'&&closeEvidence!==null&&!closeEvidence.timed_out,
105
143
  local_requests:observations.length,message_requests:messages.length,message_requests_expected:'1-2',
106
144
  listener_closed:closed,isolation:'macos-loopback-sandbox',
107
145
  process_code:result?.code??'unknown',stopped_by_probe:stoppedByProbe,exit_code:closeEvidence?.exit_code??null,
108
- request_checks:observations.map(item=>item.startup?{startup:true}:item.checks??{complete:false})}};
146
+ request_checks:[...observations.map(item=>item.startup?{startup:true}:item.checks??{complete:false}),
147
+ ...(modelMarker?[{model_recognized:false,...modelMarker}]:[])]}};
109
148
  }
@@ -14,6 +14,11 @@ const ACCEPTANCE=/^\s*[-*]\s+(?:\[[ xX]\]\s+)?(?:\[(AC-\d{3,})\]|(AC-\d{3,}))(?=
14
14
  const FEATURE=/^(\d+)\.(.+)$/;
15
15
  const TEST_CASE_VALIDATOR=fileURLToPath(new URL('../../../scripts/validate-test-cases.mjs',import.meta.url));
16
16
 
17
+ export function parseCmAiTaskLine(line){
18
+ const match=line.match(TASK);
19
+ return match?{id:match[2],completed:match[1].toLowerCase()==='x'}:null;
20
+ }
21
+
17
22
  // Greenfield's T-001 scaffolds; its subsequent instruction task (normally
18
23
  // T-002) owns init-equivalent rules. Use the existing parser and approval gate.
19
24
  export function inspectCmAiBootstrapTask({specsDir,codeProject,taskId},inProgress=false) {
@@ -354,7 +359,8 @@ export function approveCmAiSpecs(options){
354
359
  const specFiles=buildManifest(specsDir),at=new Date().toISOString();
355
360
  writeSpecsStatus(specsDir,{status:'approved',summaryDigest:status.value?.summaryDigest??null,at,
356
361
  features:discovered.names,specFiles,testCases:specFiles.filter(item=>item.path.endsWith('/test-cases.json')),
357
- approval:{response:options.approvalResponse,at}});
362
+ approval:{response:options.approvalResponse,at},
363
+ ...(status.value&&Object.hasOwn(status.value,'revisionDigest')?{revisionDigest:status.value.revisionDigest}:{})});
358
364
  }catch(error){return refuse(error.code??error.message);}
359
365
  return {projectResults:inspect()};
360
366
  }
@@ -2,8 +2,9 @@
2
2
  import {inspectCmAiAdmission,matchesCmAiTaskSelection} from './cm-ai-admission.mjs';
3
3
  import {inspectCmAiContextRefresh,inspectCmAiTaskLearningInput} from './cm-ai-context-refresh.mjs';
4
4
  import {findCmAiQaDecision,inspectCmAiQaDecision,inspectCmAiQaResult,recordCmAiQaDecision,
5
- latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery} from './cm-ai-qa-log.mjs';
5
+ latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery,inspectCmAiQaConfigurationRecovery} from './cm-ai-qa-log.mjs';
6
6
  import {recordCmAiRunDone} from './cm-ai-run-finalizer.mjs';
7
+ import {REVIEWED_HANDOFF_HINT} from './host-handoff.mjs';
7
8
  import {readHostQaFixHandoff} from './host-qa-fix.mjs';
8
9
  import {digest,freeze,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
9
10
 
@@ -38,6 +39,7 @@ const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approv
38
39
  const summary=(operation,status,outcome)=>freeze({version:1,workflow:'cm-ai',operation:operation.operation,
39
40
  requestDigest:digest(operation),identity:status.identity,outcome,state:status.state,code:status.code??null,
40
41
  packageDigest:status.packageDigest??null,pendingAction:pendingAction(status),
42
+ ...(status.code==='handoff_exists'?{reason:REVIEWED_HANDOFF_HINT}:{}),
41
43
  ...(status.state==='blocked'&&status.calls?.at(-1)?.blockedReason!==undefined
42
44
  ?{blockedReason:status.calls.at(-1).blockedReason}:{})});
43
45
  const correctionSummary=(operation,status)=>status.code==='correction_review_required'
@@ -89,7 +91,7 @@ function effectSummary(operation,result,runner,identity) {
89
91
  boundStatus(runner.status(),next);
90
92
  return summary(operation,boundStatus(result,next),'advanced');
91
93
  }
92
- return summary(operation,boundStatus(result,identity),'advanced');
94
+ return summary(operation,boundStatus(result,identity),result?.code==='handoff_exists'?'blocked':'advanced');
93
95
  }
94
96
 
95
97
  function contextEvidence(options,identity,operation) {
@@ -151,6 +153,8 @@ export function createCmAiConversationEntry(options) {
151
153
  if(runner&&Object.hasOwn(runner,'inspectFixAssociation'))runnerKeys.push('inspectFixAssociation');
152
154
  if(runner&&Object.hasOwn(runner,'acceptCompletedFix'))runnerKeys.push('acceptCompletedFix');
153
155
  if(runner&&Object.hasOwn(runner,'attachQa'))runnerKeys.push('attachQa');
156
+ if(runner&&Object.hasOwn(runner,'reviseQa'))runnerKeys.push('reviseQa');
157
+ if(runner&&Object.hasOwn(runner,'supersedeEvidence'))runnerKeys.push('supersedeEvidence');
154
158
  if(runner&&Object.hasOwn(runner,'inspectBootstrapAdmission'))runnerKeys.push('inspectBootstrapAdmission');
155
159
  shape(runner,runnerKeys);
156
160
  for(const name of ['executeEffect','status','cancel','run'])need(typeof runner[name]==='function');
@@ -158,6 +162,7 @@ export function createCmAiConversationEntry(options) {
158
162
  if(Object.hasOwn(runner,'inspectFixAssociation'))need(typeof runner.inspectFixAssociation==='function');
159
163
  if(Object.hasOwn(runner,'acceptCompletedFix'))need(typeof runner.acceptCompletedFix==='function');
160
164
  if(Object.hasOwn(runner,'attachQa'))need(typeof runner.attachQa==='function');
165
+ if(Object.hasOwn(runner,'reviseQa'))need(typeof runner.reviseQa==='function');
161
166
  if(Object.hasOwn(runner,'inspectBootstrapAdmission'))need(typeof runner.inspectBootstrapAdmission==='function');
162
167
 
163
168
  const hostDecision=Object.hasOwn(options,'hostDecision')?json(options.hostDecision):null;
@@ -292,16 +297,21 @@ export function createCmAiConversationEntry(options) {
292
297
  notCancelled();
293
298
  need(pendingExecution===null,'qa_execution_pending');
294
299
  const binding={specsDir:options.specsDir,feature:options.feature,identity:result.identity,packageDigest:result.packageDigest};
295
- let previous,recovery=null;
300
+ let previous,recovery=null,configurationRecovery=false;
296
301
  try{previous=latestCmAiQaRun(binding);}
297
302
  catch(error){
298
- if(error.code!=='qa_result_incomplete')throw error;
299
- if(rerunUnknownQa){
300
- try{recovery=inspectCmAiQaRecovery(binding);}
301
- catch(error){if(error.code!=='qa_execution_unknown')throw error;}
303
+ if(error.code==='qa_result_superseded'){
304
+ recovery=inspectCmAiQaConfigurationRecovery(binding);
305
+ need(recovery!==null,'qa_revision_invalid');configurationRecovery=true;previous=null;
306
+ }else{
307
+ if(error.code!=='qa_result_incomplete')throw error;
308
+ if(rerunUnknownQa){
309
+ try{recovery=inspectCmAiQaRecovery(binding);}
310
+ catch(error){if(error.code!=='qa_execution_unknown')throw error;}
311
+ }
312
+ if(recovery===null)return summary(operation,{...runner.status(),code:'qa_execution_unknown'},'blocked');
313
+ previous=null;
302
314
  }
303
- if(recovery===null)return summary(operation,{...runner.status(),code:'qa_execution_unknown'},'blocked');
304
- previous=null;
305
315
  }
306
316
  if(rerunBlockedQa){
307
317
  need(previous!==null,'qa_rerun_not_blocked_by_evidence');
@@ -312,8 +322,8 @@ export function createCmAiConversationEntry(options) {
312
322
  const repaired=previous?.status==='failed'&&accepted?.testRunId===previous.testRunId;
313
323
  if(previous===null||repaired||rerunBlockedQa){
314
324
  // Later rounds require an accepted completed repair or explicit
315
- // evidence-only BLOCKED recovery. Unknown and unrepaired FAIL stop.
316
- const qaRound=recovery?recovery.qaRound+(rerunBlockedQa?1:0):(repaired?accepted.qaRound+1:1);
325
+ // evidence recovery/configuration revision. Unknown execution stops.
326
+ const qaRound=recovery?recovery.qaRound+(rerunBlockedQa||configurationRecovery?1:0):(repaired?accepted.qaRound+1:1);
317
327
  need(qaRound>=1&&qaRound<=3,'qa_round_invalid');
318
328
  testRunId=`qa-${digest(recovery?{...binding,previousTestRunId:recovery.testRunId}:
319
329
  repaired?{...binding,qaRound,repair:accepted.evidenceDigest}:binding).slice(0,48)}`;
@@ -321,7 +331,7 @@ export function createCmAiConversationEntry(options) {
321
331
  ...(repaired||recovery?{qaRound}: {})};
322
332
  const logInput={...invocation,...(Object.hasOwn(options,'qaLogHome')?{logHome:options.qaLogHome}:{})};
323
333
  notCancelled();
324
- if(recovery){
334
+ if(recovery&&!configurationRecovery){
325
335
  recordCmAiQaRun({...logInput,testRunId:recovery.testRunId,mode:recovery.mode,
326
336
  caseCount:recovery.caseCount,qaRound:recovery.qaRound,phase:rerunBlockedQa?'superseded':'abandoned',
327
337
  ...(rerunBlockedQa?{expectedEnvironment:qaExecutor.configuration?.environment??null}:{})});
@@ -6,6 +6,8 @@ import {fileURLToPath} from 'node:url';
6
6
  import {digest,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
7
7
  import {readQaAttachment} from './qa-attachment.mjs';
8
8
  import {writeCmAiQaStatus} from './cm-ai-run-finalizer.mjs';
9
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
10
+ import {qaRevisionChain,readQaConfigRevision} from './qa-config-revision.mjs';
9
11
 
10
12
  const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
11
13
  const MiB=1024*1024;
@@ -212,6 +214,15 @@ function blockedEvidenceCases(items,specsDir,environment,code='qa_rerun_not_bloc
212
214
  return blocked.map(row=>row.id).sort();
213
215
  }
214
216
 
217
+ // Supersession is authorized by the owner journal, never a self-reported log digest.
218
+ function validateConfigurationSupersession(row,specsDir,code){
219
+ const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:row.repository_id,runId:row.run_id}});
220
+ const {revisions}=qaRevisionChain(snapshot);
221
+ const record=revisions.find(r=>digest(r)===row.qa_revision_digest),config=snapshot.records[0]?.payload?.config;
222
+ need(record&&record.testRunId===row.operation_id&&record.qaRound===row.attempt
223
+ &&record.packageDigest===row.package_digest&&config?.identity?.taskId===row.task&&config?.taskLearning?.feature===row.feature,code);
224
+ }
225
+
215
226
  // Abandonment reuses a round; superseded completed evidence advances it.
216
227
  function validateRunSequence(items,code='qa_round_invalid',specsDir){
217
228
  const starts=[],ids=new Set();let current=null,abandoned=false,superseded=false;
@@ -234,11 +245,18 @@ function validateRunSequence(items,code='qa_round_invalid',specsDir){
234
245
  }else{
235
246
  need(current&&row.operation_id===current.operation_id&&row.attempt===current.attempt&&!abandoned&&!superseded,code);
236
247
  if(row.phase==='superseded'){
237
- need(current.attempt<3&&row.previous_test_run_id===current.operation_id&&row.reason==='host_evidence_problem'
248
+ need(current.attempt<3&&row.previous_test_run_id===current.operation_id
238
249
  &&row.mode===current.mode&&row.case_count===current.case_count,code);
239
250
  const prior=items.filter(entry=>entry.position<item.position&&entry.row.operation_id===row.operation_id);
240
- const blocked=blockedEvidenceCases(prior,specsDir,row.expected_environment,code);
241
- need(JSON.stringify(row.blocked_cases)===JSON.stringify(blocked),code);superseded=true;
251
+ if(row.reason==='qa_configuration_revision'){
252
+ need(prior.filter(entry=>entry.row.phase==='complete').length===1,code);
253
+ validateConfigurationSupersession(row,specsDir,code);
254
+ }else{
255
+ need(row.reason==='host_evidence_problem',code);
256
+ const blocked=blockedEvidenceCases(prior,specsDir,row.expected_environment,code);
257
+ need(JSON.stringify(row.blocked_cases)===JSON.stringify(blocked),code);
258
+ }
259
+ superseded=true;
242
260
  }
243
261
  if(row.phase==='abandoned'){
244
262
  need(row.previous_test_run_id===current.operation_id&&row.reason==='host_terminated'
@@ -308,6 +326,41 @@ export function latestCmAiQaRun(input) {
308
326
  return {testRunId,...inspectCmAiQaResult({...input,testRunId})};
309
327
  }
310
328
 
329
+ // Configuration revision consumes another round. Unknown in-flight QA must be
330
+ // reconciled separately; changing its configuration is not cancellation proof.
331
+ export function inspectCmAiQaRevisionTarget({specsDir,feature,identity,packageDigest}){
332
+ const input={specsDir,feature,identity,packageDigest};
333
+ latestCmAiQaRun(input);
334
+ const rows=qaRunRows(input),starts=validateRunSequence(rows,'qa_round_invalid',input.specsDir),start=starts.at(-1).row;
335
+ need(start.attempt<3,'qa_round_invalid');
336
+ need(!rows.some(({row})=>row.operation_id===start.operation_id&&['superseded','abandoned'].includes(row.phase)),'qa_revision_pending');
337
+ return {testRunId:start.operation_id,qaRound:start.attempt,mode:start.mode,caseCount:start.case_count};
338
+ }
339
+
340
+ export function inspectCmAiQaConfigurationRecovery(input){
341
+ const rows=qaRunRows(input);
342
+ if(rows.at(-1)?.row.reason!=='qa_configuration_revision'||rows.at(-1)?.row.phase!=='superseded')return null;
343
+ validateRunSequence(rows,'qa_round_invalid',input.specsDir);
344
+ const row=rows.at(-1).row;
345
+ return {testRunId:row.operation_id,qaRound:row.attempt,mode:row.mode,caseCount:row.case_count,superseded:true};
346
+ }
347
+
348
+ export function recordCmAiQaConfigurationRevision(input,raw){
349
+ const record=readQaConfigRevision(raw),{specsDir,feature,identity,packageDigest}=input;
350
+ const rows=qaRunRows({specsDir,feature,identity,packageDigest});
351
+ const existing=rows.find(({row})=>row.phase==='superseded'&&row.qa_revision_digest===digest(record));
352
+ if(existing){
353
+ validateConfigurationSupersession(existing.row,input.specsDir,'qa_revision_invalid');
354
+ if(rows.at(-1)===existing)writeCmAiQaStatus({specsDir,feature,identity,phase:'configuration_revised'});
355
+ return;
356
+ }
357
+ const target=inspectCmAiQaRevisionTarget(input);
358
+ need(target.testRunId===record.testRunId&&target.qaRound===record.qaRound,'qa_revision_invalid');
359
+ const result=recordCmAiQaRun({...input,...target,phase:'superseded',configurationRevision:record});
360
+ writeCmAiQaStatus({specsDir,feature,identity,phase:'configuration_revised'});
361
+ return result;
362
+ }
363
+
311
364
  export function recordCmAiQaRun(input) {
312
365
  const keys=['specsDir','codeProject','feature','identity','packageDigest','testRunId','mode','caseCount','phase'];
313
366
  if(Object.hasOwn(input,'result'))keys.push('result');
@@ -316,6 +369,7 @@ export function recordCmAiQaRun(input) {
316
369
  if(Object.hasOwn(input,'previousTestRunId'))keys.push('previousTestRunId');
317
370
  if(Object.hasOwn(input,'deferredCases'))keys.push('deferredCases');
318
371
  if(Object.hasOwn(input,'expectedEnvironment'))keys.push('expectedEnvironment');
372
+ if(Object.hasOwn(input,'configurationRevision'))keys.push('configurationRevision');
319
373
  shape(input,keys);validIdentity(input.identity);id(input.testRunId);hex(input.packageDigest);
320
374
  text(input.specsDir);text(input.codeProject);text(input.feature);
321
375
  need(['commands','browser','all'].includes(input.mode));
@@ -325,7 +379,12 @@ export function recordCmAiQaRun(input) {
325
379
  need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=3,'qa_round_invalid');
326
380
  const binding={specsDir:input.specsDir,feature:input.feature,identity:input.identity,packageDigest:input.packageDigest};
327
381
  let passed=[],blockedCases=[];
328
- if(input.phase==='superseded'){
382
+ if(input.configurationRevision){
383
+ need(input.phase==='superseded','qa_revision_invalid');
384
+ const record=readQaConfigRevision(input.configurationRevision),target=inspectCmAiQaRevisionTarget(binding);
385
+ need(record.taskAttempt===input.identity.attempt&&record.testRunId===input.testRunId&&target.testRunId===input.testRunId&&record.packageDigest===input.packageDigest
386
+ &&target.qaRound===qaRound&&record.qaRound===qaRound&&target.mode===input.mode&&target.caseCount===input.caseCount,'qa_revision_invalid');
387
+ }else if(input.phase==='superseded'){
329
388
  const previous=inspectCmAiQaRecovery(binding,{blocked:true,environment:input.expectedEnvironment});
330
389
  blockedCases=previous.blockedCases;
331
390
  need(previous.testRunId===input.testRunId&&previous.qaRound===qaRound
@@ -341,7 +400,7 @@ export function recordCmAiQaRun(input) {
341
400
  let previous;
342
401
  if(Object.hasOwn(input,'previousTestRunId')){
343
402
  const rows=qaRunRows(binding),superseded=rows.at(-1)?.row.phase==='superseded';
344
- previous=inspectCmAiQaRecovery(binding,{blocked:superseded,environment:rows.at(-1)?.row.expected_environment});
403
+ previous=inspectCmAiQaConfigurationRecovery(binding)??inspectCmAiQaRecovery(binding,{blocked:superseded,environment:rows.at(-1)?.row.expected_environment});
345
404
  need((previous.abandoned||previous.superseded)&&previous.testRunId===input.previousTestRunId
346
405
  &&previous.qaRound+(superseded?1:0)===qaRound,'qa_round_invalid');
347
406
  }else previous=latestCmAiQaRun(binding);
@@ -372,6 +431,11 @@ export function recordCmAiQaRun(input) {
372
431
  if(input.phase==='abandoned')Object.assign(data,{previous_test_run_id:input.testRunId,reason:'host_terminated',partial_pass_cases:passed});
373
432
  if(input.phase==='superseded')Object.assign(data,{previous_test_run_id:input.testRunId,
374
433
  reason:'host_evidence_problem',blocked_cases:blockedCases,expected_environment:input.expectedEnvironment??null});
434
+ if(input.configurationRevision){
435
+ delete data.blocked_cases;delete data.expected_environment;
436
+ Object.assign(data,{reason:'qa_configuration_revision',qa_revision_digest:digest(input.configurationRevision)});
437
+ validateConfigurationSupersession({...data,run_id:input.identity.runId},input.specsDir,'qa_revision_invalid');
438
+ }
375
439
  if(input.phase==='complete'){
376
440
  const result=json(input.result);shape(result,['result','passed','failed','blocked','report']);
377
441
  for(const key of ['passed','failed','blocked'])need(Number.isSafeInteger(result[key])&&result[key]>=0,'qa_result_invalid');
@@ -462,6 +526,7 @@ function inspectQaResult(input,failureSource,historical=false) {
462
526
  const latestStart=latestStarts.at(-1);
463
527
  if(!historical)need(latestStart.row.operation_id===input.testRunId,'qa_result_stale');
464
528
  const runs=candidates.filter(item=>item.row.operation_id===input.testRunId);
529
+ if(!historical)need(!runs.some(({row})=>row.phase==='superseded'&&row.reason==='qa_configuration_revision'),'qa_result_superseded');
465
530
  need(runs.length>0,'qa_result_invalid');
466
531
  const starts=runs.filter(item=>item.row.phase==='start'),completes=runs.filter(item=>item.row.phase==='complete');
467
532
  need(starts.length===1&&completes.length===1,'qa_result_incomplete');
@@ -47,12 +47,12 @@ function prepareStatus({specs,target},feature,identity,progress=null) {
47
47
  // Existing status file is only the current log projection, not a task store.
48
48
  export function writeCmAiQaStatus({specsDir,feature,identity,caseId,phase,result}) {
49
49
  validIdentity(identity);text(feature);
50
- need(['case_start','case_complete','case_blocked','complete'].includes(phase));
51
- if(phase!=='complete')id(caseId);
52
- else need(['PASS','FAIL','BLOCKED'].includes(result?.result),'qa_result_invalid');
50
+ need(['case_start','case_complete','case_blocked','complete','configuration_revised'].includes(phase));
51
+ if(phase!=='complete'&&phase!=='configuration_revised')id(caseId);
52
+ if(phase==='complete')need(['PASS','FAIL','BLOCKED'].includes(result?.result),'qa_result_invalid');
53
53
  const prepared=prepareStatus(statusTarget(specsDir),feature,identity,{node:'N6',feature,task:identity.taskId,
54
- detail:phase==='complete'?`QA 结果 ${result.result}(通过 ${result.passed} / 失败 ${result.failed} / 阻断 ${result.blocked})`:`QA ${caseId}: ${phase}`,
55
- state:phase==='complete'?{PASS:'qa_passed',FAIL:'qa_failed',BLOCKED:'qa_blocked'}[result.result]:'qa_running',
54
+ detail:phase==='configuration_revised'?'QA 配置已修订,旧结果仅作历史,等待下一轮':phase==='complete'?`QA 结果 ${result.result}(通过 ${result.passed} / 失败 ${result.failed} / 阻断 ${result.blocked})`:`QA ${caseId}: ${phase}`,
55
+ state:phase==='configuration_revised'?'qa_pending':phase==='complete'?{PASS:'qa_passed',FAIL:'qa_failed',BLOCKED:'qa_blocked'}[result.result]:'qa_running',
56
56
  at:new Date().toTimeString().slice(0,8)});
57
57
  try{
58
58
  fs.renameSync(prepared.temporary,prepared.target);
@@ -0,0 +1,68 @@
1
+ // JSONL host driver transport shared by cm-fix and cm-ai. Policy stays in each driver.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {spawn} from 'node:child_process';
5
+ import readline from 'node:readline';
6
+
7
+ export const stderr=line=>process.stderr.write(`[drive] ${line}\n`);
8
+ export const stop=(code,line)=>{stderr(line);process.exit(code);};
9
+
10
+ export function readJson(file,label){
11
+ try{return JSON.parse(fs.readFileSync(file,'utf8'));}
12
+ catch(error){if(error.code==='ENOENT')return undefined;stop(2,`${label} 不是合法 JSON: ${file}`);}
13
+ }
14
+
15
+ export function loadPlanFile({argv=process.argv.slice(2),name,known}){
16
+ const at=argv.indexOf('--plan');
17
+ const operation=argv.find((arg,index)=>index!==at&&index!==at+1&&!arg.startsWith('--'));
18
+ if(at===-1||!argv[at+1]||!operation)stop(2,`用法: ${name} --plan PLAN.json <operation>`);
19
+ if(!known.has(operation))stop(2,`不认识的步骤 ${operation};宿主支持的见 ${name.replace('-drive','-host')} --help`);
20
+ const planPath=path.resolve(argv[at+1]),base=path.dirname(planPath);
21
+ let plan;
22
+ try{plan=JSON.parse(fs.readFileSync(planPath,'utf8'));}
23
+ catch(error){stop(2,`读不了 ${planPath}: ${error.code??error.message}`);}
24
+ return {operation,plan,base};
25
+ }
26
+
27
+ export function requireFields(value,keys){
28
+ for(const key of keys)if(!Object.hasOwn(value,key))stop(2,`PLAN 缺少字段 ${key}`);
29
+ }
30
+
31
+ export function preflightAnswers(kinds,load){
32
+ const answers={};
33
+ for(const kind of kinds)answers[kind]=load(kind);
34
+ return answers;
35
+ }
36
+
37
+ export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor}){
38
+ const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
39
+ child.stderr.on('data',chunk=>process.stderr.write(chunk));
40
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
41
+ let done=false;
42
+ readline.createInterface({input:child.stdout}).on('line',async line=>{
43
+ let row;try{row=JSON.parse(line);}catch{process.stdout.write(line+'\n');return;}
44
+ if(row.type==='host_ready'){send({requestId:'drive',operation,...request});return;}
45
+ if(row.type==='host_request'){
46
+ let result;
47
+ try{result=await answerFor(row,answers,paths);}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
48
+ if(result===null){
49
+ stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答;这一步会留在 unknown`);
50
+ send({type:'host_close',sessionId:row.sessionId});return;
51
+ }
52
+ stderr(`应答 ${row.kind}`);
53
+ send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
54
+ return;
55
+ }
56
+ if(row.type==='host_response')return;
57
+ if(row.requestId==='drive'){
58
+ done=true;
59
+ process.stdout.write(JSON.stringify(row,null,2)+'\n');
60
+ if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
61
+ if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
62
+ process.exitCode=row.error?1:0;
63
+ child.stdin.end();
64
+ }
65
+ });
66
+ child.on('error',error=>{stderr(`宿主启动失败:${error.message}`);process.exitCode=1;});
67
+ child.on('exit',code=>{if(!done){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
68
+ }