@aibyzero/cm-workflow 0.21.7 → 0.25.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 (227) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +64 -0
  3. package/README.md +15 -1
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +63 -19
  12. package/docs/js-workflow-control.md +67 -31
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +2 -2
  15. package/docs/user-guide.md +1 -1
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/claude-probe-diagnosis.mjs +21 -0
  20. package/runtime/js/cm-ai/claude-review-stream.mjs +20 -7
  21. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -2
  22. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  23. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  24. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  25. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  27. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  28. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  29. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  30. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  32. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  33. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  34. package/runtime/js/cm-ai/host-check.mjs +4 -2
  35. package/runtime/js/cm-ai/host-conversation-execution.mjs +29 -2
  36. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  37. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  38. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  39. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  40. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  41. package/runtime/js/cm-ai/host-session.mjs +1 -1
  42. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  43. package/runtime/js/cm-ai/host.mjs +1 -1
  44. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  45. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  46. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  47. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  48. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  49. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  50. package/runtime/js/cm-ai/review-package.mjs +25 -4
  51. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  52. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  53. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  54. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  55. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  56. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  57. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  58. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  59. package/runtime/js/cm-ai/worker-claude-developer.mjs +3 -1
  60. package/runtime/js/cm-ai/worker-claude.mjs +5 -1
  61. package/runtime/js/cm-check/host.mjs +13 -3
  62. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  63. package/runtime/js/cm-fix/execution.mjs +47 -9
  64. package/runtime/js/cm-fix/finish.mjs +9 -1
  65. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  66. package/runtime/js/cm-idea/session.mjs +22 -3
  67. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  68. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  69. package/runtime/js/cm-prd/analysis.mjs +27 -9
  70. package/runtime/js/cm-prd/change.mjs +29 -8
  71. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  72. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  73. package/runtime/js/cm-prd/review-channels.mjs +5 -0
  74. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  75. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  76. package/runtime/js/cm-prd/review-publication.mjs +2 -1
  77. package/runtime/js/cm-prd/self-check.mjs +121 -9
  78. package/runtime/js/cm-prd/session.mjs +55 -13
  79. package/runtime/js/cm-prd/summary.mjs +34 -6
  80. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  81. package/runtime/js/cm-refactor/records.mjs +82 -11
  82. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  83. package/runtime/js/executor-version.mjs +81 -0
  84. package/runtime/js/python-log-writer.mjs +15 -0
  85. package/runtime/js/run-analysis.mjs +136 -11
  86. package/runtime/logging.md +6 -0
  87. package/runtime/review.md +2 -1
  88. package/scripts/ci-test-weights.json +1 -0
  89. package/scripts/cm-ai-admission.mjs +27 -1
  90. package/scripts/cm-ai-admission.test.mjs +34 -2
  91. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  92. package/scripts/cm-ai-batch-drive.mjs +54 -17
  93. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  94. package/scripts/cm-ai-batch-host.mjs +64 -11
  95. package/scripts/cm-ai-batch-host.test.mjs +23 -3
  96. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  97. package/scripts/cm-ai-batch-merge.mjs +102 -0
  98. package/scripts/cm-ai-batch-plan.mjs +55 -2
  99. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  100. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  101. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  102. package/scripts/cm-ai-batch-run.mjs +437 -34
  103. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  104. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  105. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  106. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  107. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  108. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  109. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  110. package/scripts/cm-ai-drive.mjs +66 -14
  111. package/scripts/cm-ai-drive.test.mjs +13 -3
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  113. package/scripts/cm-ai-host.mjs +20 -9
  114. package/scripts/cm-ai-host.test.mjs +12 -0
  115. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  116. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  117. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  118. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  119. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  120. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  121. package/scripts/cm-ai-run.mjs +42 -11
  122. package/scripts/cm-ai-run.test.mjs +26 -0
  123. package/scripts/cm-ai-supersede.test.mjs +10 -2
  124. package/scripts/cm-capability-gate.test.mjs +1 -1
  125. package/scripts/cm-check-host.test.mjs +54 -0
  126. package/scripts/cm-check-runtime.sh +27 -15
  127. package/scripts/cm-check-update.mjs +83 -8
  128. package/scripts/cm-check-update.test.mjs +114 -1
  129. package/scripts/cm-claude-developer-worker.test.mjs +29 -1
  130. package/scripts/cm-claude-managed-preflight.test.mjs +126 -0
  131. package/scripts/cm-claude-probe.test.mjs +5 -0
  132. package/scripts/cm-claude-review-stream.test.mjs +4 -1
  133. package/scripts/cm-claude-worker.test.mjs +29 -0
  134. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  135. package/scripts/cm-developer-self-review.test.mjs +27 -0
  136. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  137. package/scripts/cm-efficiency-response.test.mjs +2 -1
  138. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  139. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  140. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  141. package/scripts/cm-executor-version-records.test.mjs +256 -0
  142. package/scripts/cm-executor-version.test.mjs +250 -0
  143. package/scripts/cm-external-model-host.test.mjs +6 -1
  144. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  145. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  146. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  147. package/scripts/cm-fix-drive.mjs +7 -2
  148. package/scripts/cm-fix-drive.test.mjs +45 -0
  149. package/scripts/cm-fix-entry.mjs +5 -2
  150. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  151. package/scripts/cm-fix-host.mjs +9 -2
  152. package/scripts/cm-fix-review-preflight.mjs +2 -0
  153. package/scripts/cm-fix-review-verification-integration.test.mjs +19 -0
  154. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  155. package/scripts/cm-host-check.test.mjs +12 -0
  156. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  157. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  158. package/scripts/cm-idea-drive.mjs +5 -2
  159. package/scripts/cm-idea-entry.mjs +5 -2
  160. package/scripts/cm-idea-host.mjs +3 -1
  161. package/scripts/cm-init-drive.mjs +8 -5
  162. package/scripts/cm-init-entry.mjs +5 -2
  163. package/scripts/cm-init-host.mjs +6 -2
  164. package/scripts/cm-log-event.mjs +10 -2
  165. package/scripts/cm-log-event.test.mjs +29 -0
  166. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  167. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  168. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  169. package/scripts/cm-prd-completion.test.mjs +67 -4
  170. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  171. package/scripts/cm-prd-drive.mjs +91 -21
  172. package/scripts/cm-prd-drive.test.mjs +126 -4
  173. package/scripts/cm-prd-entry.mjs +5 -2
  174. package/scripts/cm-prd-host.mjs +89 -20
  175. package/scripts/cm-prd-host.test.mjs +17 -8
  176. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  177. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  178. package/scripts/cm-prd-review-gate.mjs +13 -5
  179. package/scripts/cm-prd-review-publication.test.mjs +34 -0
  180. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  181. package/scripts/cm-prd-self-check.test.mjs +1 -1
  182. package/scripts/cm-refactor-drive.mjs +10 -4
  183. package/scripts/cm-refactor-entry.mjs +5 -2
  184. package/scripts/cm-refactor-host.mjs +3 -1
  185. package/scripts/cm-release-smoke.sh +3 -2
  186. package/scripts/cm-run-analysis.test.mjs +373 -1
  187. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  188. package/scripts/cm-skill-hints-exam.mjs +3 -1
  189. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  190. package/scripts/cm-skill-hints.mjs +106 -10
  191. package/scripts/cm-skill-hints.test.mjs +162 -6
  192. package/scripts/cm-skill-judge.mjs +2 -1
  193. package/scripts/cm-task-gate.mjs +88 -18
  194. package/scripts/cm-task-scope.test.mjs +1 -1
  195. package/scripts/cm-test-drive.mjs +13 -8
  196. package/scripts/cm-test-entry.mjs +5 -2
  197. package/scripts/cm-test-host.mjs +3 -1
  198. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  199. package/scripts/cm-workflow-config.test.mjs +8 -3
  200. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  201. package/scripts/fixtures/prd-review-gate-python-oracle.py +10 -1
  202. package/scripts/policy-binding-compat.test.mjs +3 -2
  203. package/scripts/scan-public-safety.py +1 -0
  204. package/scripts/shell-pipe-early-exit.test.mjs +96 -0
  205. package/scripts/test-cm-prd-review-gate.py +55 -0
  206. package/scripts/test-shell-compat.sh +7 -5
  207. package/skills/cm-ai/SKILL.md +1 -1
  208. package/skills/cm-ai/references/N1-init.md +1 -1
  209. package/skills/cm-ai/references/N4-review.md +2 -2
  210. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  211. package/skills/cm-ai/references/js-host-recovery.md +5 -1
  212. package/skills/cm-ai/references/js-host.md +17 -8
  213. package/skills/cm-check/SKILL.md +3 -0
  214. package/skills/cm-fix/references/isolated-review.md +1 -1
  215. package/skills/cm-fix/references/js-host.md +20 -0
  216. package/skills/cm-fix/references/test-extension.md +1 -1
  217. package/skills/cm-prd/SKILL.md +8 -6
  218. package/skills/cm-prd/references/ai-draft.md +81 -0
  219. package/skills/cm-prd/references/change-mode.md +2 -0
  220. package/skills/cm-prd/references/greenfield.md +2 -0
  221. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  222. package/skills/cm-prd/references/js-host.md +9 -6
  223. package/skills/cm-prd/references/light-mode.md +19 -0
  224. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  225. package/skills/cm-prd/references/spec-self-check.md +1 -0
  226. package/skills/cm-prd/references/summary-card.md +1 -0
  227. package/templates/auto-update/cm-update.sh +2 -2
@@ -1,6 +1,6 @@
1
1
  import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import {operatorGuidance,guidanceText} from '../runtime/js/cm-ai/operator-guidance.mjs';
3
+ import {operatorGuidance,guidanceText,reviewLimitCard,reviewLimitCardLines} from '../runtime/js/cm-ai/operator-guidance.mjs';
4
4
  import {batchMemberResult} from './cm-ai-batch-run.mjs';
5
5
 
6
6
  const identity={repositoryId:'fixture',runId:'guidance-run',taskId:'T-001',attempt:1};
@@ -188,3 +188,134 @@ test('invalid checkpoint package material remains a preservation-only diagnostic
188
188
  assert.equal(JSON.stringify(input),before);
189
189
  }
190
190
  });
191
+
192
+ // Regression: review_limit used to fall through to the generic "当前流程受阻" text with no decision support.
193
+ const limitEvidence=()=>({rounds:[
194
+ {attempt:1,packageDigest:'p1',verdict:'changes_requested',summary:'r1 summary',findings:[{id:'F1',severity:'P2',path:'a.js',message:'fix a'}]},
195
+ {attempt:2,packageDigest:'p2',verdict:'changes_requested',summary:'r2 summary',findings:[{id:'F2',severity:'P1',path:'a.js',message:'still wrong'},
196
+ {id:'F3',severity:'P2',path:'b.js',message:'new file issue'}]}],
197
+ packageAttempt:2,packageDigest:'p2',checks:[{id:'content',outcome:'passed'},{id:'lint',outcome:'failed'}],changes:[{path:'a.js',kind:'modified'}],
198
+ files:[1,2].flatMap(round=>['handoff','review'].map(kind=>({round,kind,present:true})))});
199
+ test('review_limit gives a read-only decision card instead of the generic blocked fallback',()=>{
200
+ for(const protocol of ['legacy','v2']){
201
+ const input=result('blocked','review_limit','none',{identity:{...identity,attempt:2},reviewLimitCard:reviewLimitCard(limitEvidence())});
202
+ const before=JSON.stringify(input);
203
+ input.guidance=operatorGuidance(input,{protocol});
204
+ assert.doesNotMatch(input.guidance.summary,/当前流程受阻/);assert.match(input.guidance.summary,/两轮审查已用完/);
205
+ assert.equal(input.guidance.recoveryOperation,null);assert.equal(input.guidance.authorizationGranted,false);
206
+ assert.equal(input.reviewLimitCard.authorizationGranted,false);assert.equal(input.reviewLimitCard.dispatchedCalls,0);
207
+ const text=guidanceText(input);
208
+ assert.match(text,/决策卡(只读,不放行/);assert.match(text,/content PASS;lint FAIL/);assert.match(text,/a\.js(修改)/);
209
+ assert.match(text,/第 1 次审查 changes_requested,1 条意见:r1 summary/);assert.match(text,/1\/2 条落在第 1 次已指出的文件/);
210
+ assert.match(text,/检查实跑(第 2 次审查的审查包)/);
211
+ assert(text.indexOf('可用出口')<text.indexOf('第 1 次审查'),'exits come before reviewer text');
212
+ assert.match(text,/第 2 次审查 P1 a\.js:still wrong/);
213
+ assert(text.indexOf('第 2 次审查 changes_requested')<text.indexOf('第 1 次审查 P2'),'all round summaries precede details');assert.doesNotMatch(text,/缺少:/);
214
+ assert.match(text,/可用出口:supersede/);assert.match(text,/human_correction(人工补正/);
215
+ assert.match(text,/review_continuation(当前运行未提供第三次受控审查(仅新版单任务运行))/);
216
+ assert.match(text,protocol==='v2'?/supersedeTarget/:/--supersede-reviewed-evidence/);
217
+ const {guidance,...rest}=input;assert.equal(JSON.stringify(rest),before,'card rendering cannot mutate the result');
218
+ }
219
+ });
220
+ test('review_limit decision card names every missing fact and never invents evidence',()=>{
221
+ const evidence=limitEvidence();evidence.rounds.pop();evidence.checks=null;evidence.changes=null;evidence.files[3].present=false;
222
+ const card=reviewLimitCard(evidence);
223
+ assert.deepEqual([...card.missing],['审查回执(只找到 1 份,应有 2 份)','最后一轮审查包(检查实跑结果)',
224
+ '最后一轮审查包(改动清单)','第 2 轮审查报告文件']);
225
+ assert.equal(card.checks,null);assert.equal(card.changes,null);
226
+ assert.deepEqual([...reviewLimitCard(null).missing],['运行回放证据(无法读取,以下各项均未确认)']);
227
+ const input=result('blocked','review_limit','none',{reviewLimitCard:reviewLimitCard(null)});input.guidance=operatorGuidance(input);
228
+ assert.match(guidanceText(input),/检查实跑:UNKNOWN/);assert.match(guidanceText(input),/改动文件:UNKNOWN/);
229
+ const forged={...reviewLimitCard(limitEvidence()),authorizationGranted:true};
230
+ const other=result('blocked','review_limit','none',{reviewLimitCard:forged});other.guidance=operatorGuidance(other);
231
+ assert.doesNotMatch(guidanceText(other),/决策卡(只读/,'a card claiming authority is not rendered');
232
+ const blocked=result('blocked','review_blocked','none',{reviewLimitCard:reviewLimitCard(limitEvidence())});
233
+ blocked.guidance=operatorGuidance(blocked);assert.doesNotMatch(guidanceText(blocked),/决策卡(只读/);
234
+ });
235
+ test('review_limit card bounds and sanitizes reviewer text',()=>{
236
+ const evidence=limitEvidence();
237
+ evidence.rounds[1].findings=Array.from({length:12},(_,i)=>({id:`F${i}`,severity:'P2',path:'a.js',message:`line\u001b[31m${'x'.repeat(400)}`}));
238
+ const card=reviewLimitCard(evidence);
239
+ assert.equal(card.rounds[1].findings.length,8);assert.equal(card.rounds[1].findingsTotal,12);
240
+ assert(card.rounds[1].findings.every(f=>!/[\x00-\x1f]/.test(f.message)&&f.message.length<=241));
241
+ const input=result('blocked','review_limit','none',{reviewLimitCard:card});input.guidance=operatorGuidance(input);
242
+ assert.match(guidanceText(input),/第 2 次审查另有 4 条,见原审查回执/);
243
+ });
244
+
245
+ test('a batch member card never offers the third controlled review the batch entry cannot grant',()=>{
246
+ const evidence=limitEvidence();
247
+ const input=result('blocked','review_limit','none',{identity:{...identity,attempt:2},
248
+ reviewLimitCard:reviewLimitCard(evidence,{continuation:{available:true,reason:null}})});
249
+ input.guidance=operatorGuidance(input,{protocol:'v2'});
250
+ assert.match(input.guidance.nextStep,/--review-continuation-reason/,'single-task entry offers it');
251
+ const member=batchMemberResult(input,{protocol:'v2',taskKey:'1.work/T-001'});
252
+ assert.equal(member.reviewLimitCard.exits.find(e=>e.id==='review_continuation').available,false);
253
+ assert.doesNotMatch(guidanceText(member),/--review-continuation/);assert.match(guidanceText(member),/批次成员不提供第三次受控审查/);
254
+ });
255
+
256
+ // dogfood 2026-12-01:审查意见指向规格本身(规格写死代理做不到的手段),续审只认已批准规格、拒收对话里批准的例外;
257
+ // 决策卡须直接给出「先改规格再重开」的出口,而不是让人误用第三次受控审查。
258
+ test('review_limit card offers a spec change exit and says the third review only honours the approved spec',()=>{
259
+ for(const continuation of [null,{available:true,reason:null}]){
260
+ const card=reviewLimitCard(limitEvidence(),{continuation});
261
+ const exit=card.exits.find(e=>e.id==='spec_change');
262
+ assert.equal(exit?.available,true);assert.match(exit.description,/--change/);assert.match(exit.description,/supersede/);
263
+ const input=result('blocked','review_limit','none',{identity:{...identity,attempt:2},reviewLimitCard:card});
264
+ input.guidance=operatorGuidance(input,{protocol:'v2'});
265
+ assert.match(guidanceText(input),/spec_change(/);
266
+ if(continuation)assert.match(card.exits.find(e=>e.id==='review_continuation').description,/只认已批准规格/);
267
+ }
268
+ const rejected=result('blocked','review_continuation_rejected','none',{identity:{...identity,attempt:2},reviewLimitCard:reviewLimitCard(limitEvidence())});
269
+ rejected.guidance=operatorGuidance(rejected,{protocol:'v2'});assert.match(rejected.guidance.nextStep,/规格本身/);
270
+ });
271
+ // Review r1/r2 (minor): an old run already stopped at review_limit sees the same exit after an upgrade.
272
+ // It stays read-only guidance there: no grant, no dispatch, no continuation.
273
+ test('an old run card shows spec_change only as read-only guidance',()=>{
274
+ const card=reviewLimitCard(limitEvidence());
275
+ assert.equal(card.readOnly,true);assert.equal(card.authorizationGranted,false);assert.equal(card.dispatchedCalls,0);
276
+ assert.deepEqual(card.exits.map(e=>[e.id,e.available]),[['supersede',true],['spec_change',true],['review_continuation',false],['human_correction',false]]);
277
+ const old=result('blocked','review_limit','none',{identity:{...identity,attempt:2},reviewLimitCard:card});
278
+ old.guidance=operatorGuidance(old,{protocol:'legacy'});
279
+ assert.doesNotMatch(guidanceText(old),/--review-continuation/);
280
+ // Review (todo r1): assert the rendered exits line itself, not text nextStep also carries.
281
+ const exitsLine=reviewLimitCardLines(card).find(line=>line.startsWith('可用出口:'));
282
+ assert.match(exitsLine,/^可用出口:supersede(.*;spec_change(意见指向规格本身/);
283
+ });
284
+ // dogfood 2026-12-01(问题 20):旧运行留在代码根的文件会让重开报 supersede_code_drift,卡片和前提要先说。
285
+ test('v2 supersede exit and prerequisites warn about files the old run left in the code root',()=>{
286
+ const card=reviewLimitCard(limitEvidence(),{continuation:null});
287
+ const exit=card.exits.find(e=>e.id==='supersede').description;
288
+ assert.match(exit,/supersede_code_drift/);assert.match(exit,/恢复到原路径和原内容/);assert.match(exit,/开工后新增的文件才可移出/);
289
+ assert.doesNotMatch(exit,/--accept-superseded-code-drift|--supersede-reviewed-evidence|--supersede-target|--supersede-reason/,'the card hands out no launch flag');
290
+ const input=result('blocked','review_limit','none',{identity:{...identity,attempt:2},reviewLimitCard:card});
291
+ input.guidance=operatorGuidance(input,{protocol:'v2'});
292
+ assert(input.guidance.prerequisites.some(item=>/supersede_code_drift/.test(item)&&/恢复到原路径和原内容/.test(item)),
293
+ JSON.stringify(input.guidance.prerequisites));
294
+ });
295
+
296
+ // 2026-12-01 探针实跑:批次功能末尾停在 fixture_completed/qa_triggered(pendingAction qa_execution),
297
+ // guidance 为 null,用户不知道 QA 为什么没跑、能怎么办。
298
+ test('qa_triggered without an executor explains why QA did not run and names the real exit per entry',()=>{
299
+ for(const protocol of ['legacy','v2']){
300
+ const input=result('fixture_completed','qa_triggered','qa_execution');input.guidance=operatorGuidance(input,{protocol});
301
+ assert.ok(input.guidance,`${protocol} single-task guidance`);
302
+ assert.equal(input.guidance.recoveryOperation,null);assert.equal(input.guidance.authorizationGranted,false);
303
+ assert.match(input.guidance.summary,/没有挂 QA 执行器/);assert.match(input.guidance.summary,/不是 QA PASS/);
304
+ assert.match(input.guidance.nextStep,/补挂 QA/);
305
+ if(protocol==='v2'){assert.match(input.guidance.nextStep,/qa 改成 "run"/);assert.doesNotMatch(input.guidance.nextStep,/--allow-qa/);}
306
+ else assert.match(input.guidance.nextStep,/--allow-qa/);
307
+ const batch=batchMemberResult(input,{protocol,taskKey:'1.work/T-001'});
308
+ assert.ok(batch.guidance,`${protocol} batch guidance`);assert.equal(batch.guidance.recoveryOperation,null);
309
+ assert.match(batch.guidance.nextStep,/批次入口不能补开 QA/);
310
+ assert.match(batch.guidance.nextStep,/cm-ai-batch-plan/);
311
+ // The redo is a superseding run, whose gate refuses a task still checked in tasks.md.
312
+ assert.match(batch.guidance.nextStep,/取消本批次.*tasks\.md 改回 - \[ \]/);
313
+ // Decided before the batch is cancelled: the supersede code-drift gate sees the task's code.
314
+ assert.match(batch.guidance.nextStep,/取消批次前.*supersede_code_drift.*--accept-superseded-code-drift.*取消本批次/);
315
+ // Codex 第三轮:保留的改动不会重新受审,比较的是整个代码树。
316
+ assert.match(batch.guidance.nextStep,/整个代码树/);assert.match(batch.guidance.nextStep,/当成已有代码,不进新运行的审查改动/);assert.doesNotMatch(batch.guidance.nextStep,/由新运行重新审查/);
317
+ assert.match(batch.guidance.nextStep,protocol==='v2'?/inspect-history.*supersedeTarget/:/--supersede-reviewed-evidence 和单行 --supersede-reason/);
318
+ assert.doesNotMatch(batch.guidance.nextStep,/--expected-control/);
319
+ if(protocol==='v2')assert.doesNotMatch(batch.guidance.nextStep,/--allow-qa/);
320
+ }
321
+ });
@@ -18,6 +18,7 @@ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
18
18
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
19
19
  import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
20
20
  import {completionSummary} from '../runtime/js/cm-ai/completion-summary.mjs';
21
+ import {outstandingFeatureQa} from '../runtime/js/cm-ai/project-qa-gate.mjs';
21
22
 
22
23
  const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-project-qa-gate-'));
23
24
  const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
@@ -420,6 +421,31 @@ test('#18 a permission-only change to the delivered file still requires correcti
420
421
  assert.equal((await p.advance(p.first,p.firstExecution(),'resume',{rerunBlockedQa:true})).code,'context_refreshed');
421
422
  });
422
423
 
424
+ // Review q1: a periodic QA leaves browser cases to the feature-completion QA; a feature
425
+ // whose last task was finished outside N6 never had it, so that PASS does not close it.
426
+ test('a terminal feature whose latest PASS was a periodic QA with deferred browser cases stays outstanding',()=>{
427
+ const specsDir=fs.mkdtempSync(path.join(isolated,'periodic-'));
428
+ const base={schema_version:1,workflow:'cm-ai',node:'N6',feature:'1.work',repository_id:'r',run_id:'run-5',task:'T-005',
429
+ attempt:1,package_digest:'a'.repeat(64)};
430
+ const rows=deferred=>[{...base,event:'qa',decision_id:'qa-5',status:'triggered',reason:'five_tasks_without_qa'},
431
+ {...base,event:'test_run',qa_decision_id:'qa-5',operation_id:'t-5',phase:'start',...(deferred?{periodic_deferred_cases:[{id:'TC-002'}]}:{})},
432
+ {...base,event:'test_run',qa_decision_id:'qa-5',operation_id:'t-5',phase:'complete',result:'PASS'}];
433
+ const write=deferred=>fs.writeFileSync(path.join(specsDir,'运行日志.jsonl'),rows(deferred).map(row=>JSON.stringify(row)).join('\n')+'\n');
434
+ write(true);
435
+ assert.deepEqual(outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:0}]}).map(item=>item.status),['qa_periodic_only']);
436
+ assert.deepEqual(outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:2}]}),[]);
437
+ const inspected=outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:0}],inspect:()=>({status:'passed'})});
438
+ assert.deepEqual(inspected.map(item=>item.status),['qa_periodic_only']);
439
+ // Review q2: the run finalizing the project is checked too (its own evidence check
440
+ // only asks for a PASS).
441
+ assert.deepEqual(outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:0}],currentRunId:'run-5',
442
+ inspect:()=>({status:'passed'})}).map(item=>item.status),['qa_periodic_only']);
443
+ assert.deepEqual(outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:1}],currentRunId:'run-5'}),[]);
444
+ fs.rmSync(path.join(specsDir,'运行日志.jsonl'));write(false);
445
+ assert.deepEqual(outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:0}]}),[]);
446
+ assert.deepEqual(outstandingFeatureQa({specsDir,features:[{name:'1.work',pending:0}],currentRunId:'run-5'}),[]);
447
+ });
448
+
423
449
  test('#17 a feature completed outside N6 has no completion QA and blocks run_done',async()=>{
424
450
  const p=project();
425
451
  // T-002 was ticked by hand: no run, no QA row for 1.work.
@@ -360,3 +360,21 @@ test('Q23 recover_final_review and rerun_blocked_step through fix_action report
360
360
  const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
361
361
  assert.equal(classifyDriveResult('cm-ai',{result:missing}),'stuck');
362
362
  });
363
+
364
+ // Executor release (0.22.0): a child FIX a newer release created is refused with its
365
+ // own code and upgrade exit, never folded into host_request_failed; the parent reopens.
366
+ test('a child FIX created by a newer release is refused with its reason and the parent reopens',async t=>{
367
+ const f=await fixture(t);
368
+ let owner=await f.open(A);await owner.handle(f.bound('fix_advance'));f.close();
369
+ const {revision,...data}=JSON.parse(fs.readFileSync(f.statePath,'utf8'));
370
+ assert.equal(data.version,2);
371
+ const newer={...data,createdBy:{version:1,release:'99.0.0'}};
372
+ fs.writeFileSync(f.statePath,JSON.stringify({...newer,revision:digest(newer)})+'\n',{mode:0o600});
373
+ const bytes=fs.readFileSync(f.statePath);
374
+ owner=await f.open(B);
375
+ const refused=await owner.handle(f.bound('fix_status'));
376
+ assert.equal(refused.outcome,'blocked');assert.equal(refused.code,'run_created_by_newer_executor');
377
+ assert.match(refused.reason,/此运行由 CM 99\.0\.0 创建/);
378
+ assert.deepEqual(fs.readFileSync(f.statePath),bytes);
379
+ assert.equal((await owner.handle(f.request('status'))).state,'fixture_completed');
380
+ });
@@ -0,0 +1,335 @@
1
+ // Third controlled review (review-continuation-authorized): no creation switch;
2
+ // an eligible v2 single-task run on review_limit takes one explicit launch-only
3
+ // grant, one per task, original two rounds kept, and a rejected third review
4
+ // stops back on the decision card.
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import os from 'node:os';
10
+ import {openControlRun,controlLaunchTarget} from './cm-ai-run.mjs';
11
+ import {gapFixture,gapExecution,definition,identity,records} from './cm-ai-answer-gap-fixture.mjs';
12
+ import {readRunnerHistory,reviewContinuationBinding,developBudgetExhausted} from '../runtime/js/cm-ai/durable-runner-state.mjs';
13
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
14
+ import {isSupportedExecutionPlatform} from '../runtime/js/cm-ai/execution-platform.mjs';
15
+ import {createHash} from 'node:crypto';
16
+
17
+ const skip=!isSupportedExecutionPlatform();
18
+ const policy={version:2,development:'conversation',bootstrap:'disabled',qa:'run',qaFix:'disabled'};
19
+ const selected=f=>({...definition(f),taskSelection:{version:1,taskId:identity(1).taskId},featureSelection:{version:1,feature:f.feature}});
20
+ const execution=(f,options)=>{const value=gapExecution(f,options);value.configuration.controlPolicy=policy;return value;};
21
+ async function session(f,mode,exec,actions,options={}){
22
+ const run=await openControlRun(selected(f),mode,exec,options);
23
+ try{return await actions(run.controlHost,run);}finally{run.close();}
24
+ }
25
+ let serial=0;
26
+ const send=(host,operation,attempt=1,extra={})=>host.handle({version:2,requestId:`continuation-${++serial}`,operation,identity:identity(attempt),...extra});
27
+ const history=f=>{const rows=records(f);return readRunnerHistory(rows,rows[0].payload.config,3);};
28
+ const reviews=f=>path.join(f.specsDir,'.reviews');
29
+ const evidence=(f,suffix)=>path.join(reviews(f),`work-T-002-${suffix}`);
30
+ const launchTarget=f=>controlLaunchTarget(JSON.parse(fs.readFileSync(f.store,'utf8')));
31
+ const tasksDone=f=>fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('[x]');
32
+ // Two real rounds, both changes_requested: the run stops on review_limit.
33
+ async function limited(t){
34
+ const f=gapFixture(t,'review-continuation');
35
+ await session(f,'create',execution(f,{developer:['one\n'],verdicts:['changes_requested']}),async host=>{
36
+ const delivered=await send(host,'start');assert.equal(delivered.state,'awaiting_review',JSON.stringify(delivered));
37
+ assert.equal((await send(host,'decision',1,{packageDigest:delivered.packageDigest})).state,'changes_requested');
38
+ });
39
+ await session(f,'resume',execution(f,{developer:['two\n'],verdicts:['changes_requested']}),async host=>{
40
+ const delivered=await send(host,'start',2);assert.equal(delivered.state,'awaiting_review',JSON.stringify(delivered));
41
+ const stopped=await send(host,'decision',2,{packageDigest:delivered.packageDigest});
42
+ assert.equal(stopped.code,'review_limit',JSON.stringify(stopped));
43
+ });
44
+ return f;
45
+ }
46
+ const status=f=>session(f,'resume',execution(f,{}),host=>send(host,'status',2));
47
+ async function grant(f,options={}){
48
+ const run=await openControlRun(selected(f),'resume',execution(f,{}),{
49
+ expectedControl:launchTarget(f),reviewContinuationReason:'Owner disputes r2; one bounded correction and a fresh review',...options});
50
+ run.close();
51
+ }
52
+
53
+ test('only an eligible v2 single-task run may be authorized; a legacy run refuses without a journal write',{skip},async t=>{
54
+ const f=await limited(t),rows=records(f),config=rows[0].payload.config,h=history(f);
55
+ assert.equal(Object.hasOwn(config,'reviewContinuation'),false,'no creation-time switch is frozen');
56
+ assert.doesNotThrow(()=>reviewContinuationBinding(rows,h.state,config));
57
+ for(const change of [{controlPolicy:undefined},{controlPolicy:{...config.controlPolicy,development:'provider'}},
58
+ {parallelSelection:{version:1,group:['T-002','T-003']}},{developer:{...config.developer,requestedModel:'gpt-provider'}},
59
+ {codeProjectPaths:[{name:'app',path:'.'}]},
60
+ // A batch member's fixed run-ID shape (cm-ai-batch-run.mjs batchTaskRunId).
61
+ {identity:{...config.identity,runId:`task-${'a'.repeat(48)}`}}])
62
+ assert.throws(()=>reviewContinuationBinding(rows,h.state,{...config,...change}),{code:'review_continuation_unavailable'},JSON.stringify(change));
63
+ for(const change of [{code:'review_blocked'},{attempt:1},{taskCommit:{}},{cancellationRequested:true}])
64
+ assert.throws(()=>reviewContinuationBinding(rows,{...h.state,...change},config),{code:'review_continuation_unavailable'},JSON.stringify(change));
65
+ // A legacy (non-v2) launch cannot carry the grant at all.
66
+ await assert.rejects(openControlRun(selected(f),'resume',gapExecution(f,{}),{expectedControl:launchTarget(f),
67
+ reviewContinuationReason:'legacy launch'}));
68
+ assert.deepEqual(records(f),rows);assert.equal(fs.existsSync(evidence(f,'review-continuation.json')),false);
69
+ });
70
+
71
+ test('approved third review completes through the controlled correction and keeps both original rounds',{skip},async t=>{
72
+ const f=await limited(t),before=records(f);
73
+ assert.equal(Object.hasOwn(before[0].payload.config,'reviewContinuation'),false);
74
+ const r1=fs.readFileSync(evidence(f,'r1.md')),r2=fs.readFileSync(evidence(f,'r2.md')),a2=fs.readFileSync(evidence(f,'a2-handoff.json'));
75
+ const offered=await status(f);
76
+ assert.equal(offered.reviewLimitCard.exits.find(e=>e.id==='review_continuation').available,true);
77
+ assert.match(offered.guidance.nextStep,/--review-continuation-reason/);
78
+ assert.equal(offered.guidance.recoveryOperation,null);assert.equal(offered.guidance.authorizationGranted,false);
79
+ await grant(f);
80
+ const authorized=records(f);assert.deepEqual(authorized.slice(0,before.length),before);
81
+ assert.equal(authorized.at(-1).payload.type,'review-continuation-authorized');
82
+ const marker=fs.readFileSync(evidence(f,'review-continuation.json'));
83
+ assert.equal(authorized.at(-1).payload.markerSha256,createHash('sha256').update(marker).digest('hex'));
84
+ // A crash between the journal append and the marker write: the run repairs
85
+ // the identical marker from its journal before the correction record.
86
+ fs.unlinkSync(evidence(f,'review-continuation.json'));
87
+ await session(f,'resume',execution(f,{developer:['three\n'],verdicts:['approved']}),async host=>{
88
+ const again=await send(host,'status',2);assert.equal(again.state,'changes_requested');
89
+ const delivered=await send(host,'start',2);assert.equal(delivered.state,'awaiting_review',JSON.stringify(delivered));
90
+ assert.equal((await send(host,'decision',2,{packageDigest:delivered.packageDigest})).state,'approved');
91
+ // Crash between linking the sealed receipt and removing the gate's temp: a second
92
+ // link. Other files' links (a gate-shaped name and a loose one) sit beside it and
93
+ // must survive the same healing pass that removes the receipt's temp.
94
+ const dir=fs.realpathSync(reviews(f)),orphan=path.join(dir,'.cm-gate-00000000-0000-4000-8000-000000000000');
95
+ fs.linkSync(evidence(f,'controlled-correction-receipt.json'),orphan);
96
+ const notes=path.join(dir,'manual-notes.md');fs.writeFileSync(notes,'notes\n');
97
+ const loose=path.join(dir,'.cm-gate-'+'-'.repeat(36)),peer=path.join(dir,'.cm-gate-11111111-1111-4111-8111-111111111111');
98
+ fs.linkSync(notes,loose);fs.linkSync(notes,peer);
99
+ assert.equal(fs.lstatSync(evidence(f,'controlled-correction-receipt.json')).nlink,2);
100
+ assert.equal((await send(host,'complete',2,{packageDigest:delivered.packageDigest})).state,'fixture_completed');
101
+ assert.equal(fs.existsSync(orphan),false);assert.equal(fs.lstatSync(evidence(f,'controlled-correction-receipt.json')).nlink,1);
102
+ assert(fs.existsSync(loose)&&fs.existsSync(peer),'links to other files survive');assert.equal(fs.lstatSync(notes).nlink,3);
103
+ });
104
+ const h=history(f);
105
+ assert.equal(h.state.receipts.length,3);
106
+ assert.deepEqual(h.state.receipts.map(r=>[r.identity.attempt,r.result.verdict]),[[1,'changes_requested'],[2,'changes_requested'],[2,'approved']]);
107
+ assert.equal(h.state.attempt,2);assert(tasksDone(f));
108
+ assert.deepEqual(records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id).slice(-3),
109
+ ['develop-2-continuation','review-2-continuation','complete-2-continuation']);
110
+ for(const [file,bytes] of [['r1.md',r1],['r2.md',r2],['a2-handoff.json',a2]])assert(fs.readFileSync(evidence(f,file)).equals(bytes),file);
111
+ for(const suffix of ['controlled-correction.json','controlled-correction-handoff.json','controlled-correction.md','controlled-correction-receipt.json'])
112
+ assert(fs.existsSync(evidence(f,suffix)),suffix);
113
+ assert.equal(JSON.parse(fs.readFileSync(evidence(f,'controlled-correction-receipt.json'),'utf8')).verdict,'approved');
114
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'a.mjs'),'utf8'),'three\n');
115
+ assert(fs.readFileSync(evidence(f,'review-continuation.json')).equals(marker),'marker repaired byte for byte');
116
+ });
117
+
118
+ test('rejected third review stops on the decision card; no fourth round, no second grant',{skip},async t=>{
119
+ const f=await limited(t);await grant(f);
120
+ let rejected;
121
+ await session(f,'resume',execution(f,{developer:['three\n'],verdicts:['changes_requested']}),async host=>{
122
+ rejected=await send(host,'advance',2);
123
+ });
124
+ assert.equal(rejected.state,'blocked');assert.equal(rejected.code,'review_continuation_rejected',JSON.stringify(rejected));
125
+ assert.equal(f.calls.developer,3);assert.equal(tasksDone(f),false);
126
+ const card=rejected.reviewLimitCard;
127
+ assert.deepEqual(card.rounds.map(r=>r.verdict),['changes_requested','changes_requested','changes_requested']);
128
+ assert.equal(card.exits.find(e=>e.id==='review_continuation').available,false);
129
+ assert.match(rejected.guidance.summary,/第三次受控审查仍未通过/);assert.doesNotMatch(rejected.guidance.nextStep,/--review-continuation/);
130
+ assert.equal(JSON.parse(fs.readFileSync(evidence(f,'controlled-correction-receipt.json'),'utf8')).verdict,'blocked');
131
+ // Crash before the projection was written: status reports it, advance heals it
132
+ // from the journaled receipt and the decision card comes back.
133
+ // Crash between linking the review and removing its temp: a second hard link.
134
+ const orphan=path.join(reviews(f),'.cm-review-00000000-0000-4000-8000-000000000000');
135
+ fs.linkSync(evidence(f,'controlled-correction.md'),orphan);
136
+ const pending=await status(f);assert.equal(pending.code,'review_publication_required');
137
+ assert.deepEqual(pending.reviewLimitCard.missing,[],'a doubly linked review is still present');
138
+ assert.equal(pending.reviewLimitCard.rounds.length,3,'the card stays visible while publication is pending');
139
+ await session(f,'resume',execution(f,{}),async host=>{assert.equal((await send(host,'advance',2)).code,'review_continuation_rejected');});
140
+ assert.equal(fs.existsSync(orphan),false);assert.equal(fs.lstatSync(evidence(f,'controlled-correction.md')).nlink,1);
141
+ const review=fs.readFileSync(evidence(f,'controlled-correction.md')),receipt=fs.readFileSync(evidence(f,'controlled-correction-receipt.json'));
142
+ for(const suffix of ['controlled-correction.md','controlled-correction-receipt.json'])fs.unlinkSync(evidence(f,suffix));
143
+ const missingNow=await status(f);assert.equal(missingNow.code,'review_publication_required');
144
+ assert.deepEqual(missingNow.reviewLimitCard.missing,['第三次受控审查的审查报告文件','第三次受控审查的封存回执文件']);
145
+ await session(f,'resume',execution(f,{}),async host=>{
146
+ const healed=await send(host,'advance',2);assert.equal(healed.code,'review_continuation_rejected',JSON.stringify(healed));
147
+ assert.equal(healed.reviewLimitCard.rounds.length,3);
148
+ });
149
+ assert(fs.readFileSync(evidence(f,'controlled-correction.md')).equals(review));
150
+ assert(fs.readFileSync(evidence(f,'controlled-correction-receipt.json')).equals(receipt));
151
+ const before=records(f);
152
+ await session(f,'resume',execution(f,{}),async host=>{
153
+ const again=await send(host,'advance',2);assert.equal(again.code,'review_continuation_rejected');
154
+ });
155
+ assert.equal(f.calls.developer,3,'no fourth development');
156
+ await assert.rejects(grant(f,{expectedControl:launchTarget(f)}),{code:'review_continuation_used'});
157
+ assert.equal(records(f).filter(row=>row.payload.type==='review-continuation-authorized').length,1);
158
+ assert.deepEqual(records(f),before,'a refused grant writes nothing');
159
+ });
160
+
161
+ test('one per task: existing continuation or correction evidence refuses before any journal write',{skip},async t=>{
162
+ const f=await limited(t),before=records(f);
163
+ for(const name of ['review-continuation.json','controlled-correction.json','human-correction.json']){
164
+ fs.writeFileSync(evidence(f,name),'{}\n');
165
+ const card=(await status(f)).reviewLimitCard;
166
+ assert.equal(card.exits.find(e=>e.id==='review_continuation').available,false,name);
167
+ await assert.rejects(grant(f),{code:'review_continuation_used'});
168
+ fs.unlinkSync(evidence(f,name));assert.deepEqual(records(f),before);
169
+ }
170
+ fs.mkdirSync(path.join(reviews(f),'.superseded'),{recursive:true});
171
+ fs.writeFileSync(path.join(reviews(f),'.superseded','work-T-002-review-continuation.json.0123456789abcdef'),'{}\n');
172
+ await assert.rejects(grant(f),{code:'review_continuation_used'});assert.deepEqual(records(f),before);
173
+ });
174
+
175
+ test('continuation correction must change the reviewed code; an unchanged delivery is never reviewed',{skip},async t=>{
176
+ const f=await limited(t);await grant(f);
177
+ await session(f,'resume',execution(f,{developer:['two\n','three\n'],verdicts:['approved']}),async host=>{
178
+ // The continuation holds exactly one develop and one review slot from its
179
+ // authorization: an unchanged correction spends its only delivery.
180
+ const unchanged=await send(host,'start',2);
181
+ assert.equal(unchanged.code,'develop_retry_limit',JSON.stringify(unchanged));
182
+ assert.equal(history(f).state.cache.findLast(entry=>entry.effect.kind==='develop').result.code,'develop_unchanged_after_review');
183
+ assert.equal(fs.existsSync(evidence(f,'controlled-correction.json')),false,'no record before a real revision');
184
+ assert.equal(f.calls.developer,3);
185
+ });
186
+ // Review r1 of finding 12: the terminal reason names the continuation caps, and replay
187
+ // without the retry-limit row still sees no delivery that could be reviewed.
188
+ const h=history(f);assert.match(h.state.reason,/上限 6)/);
189
+ const rows=records(f).slice(0,-1),before=readRunnerHistory(rows,rows[0].payload.config,3);
190
+ assert.equal(developBudgetExhausted(before.state,before.developRecheckEffects,before.developmentRework,before.reviewContinuation),true);
191
+ });
192
+
193
+ test('replay refuses a forged or misplaced authorization record',{skip},async t=>{
194
+ const f=await limited(t);await grant(f);
195
+ const rows=records(f),config=rows[0].payload.config;
196
+ // Reseal the chain and keep each authorization bound to its resealed predecessor,
197
+ // so only the field under test differs from a genuine record.
198
+ const reseal=list=>{for(let i=0;i<list.length;i++){const {digest:_d,...body}=list[i];body.previousDigest=i?list[i-1].digest:null;
199
+ if(body.payload.type==='review-continuation-authorized')body.payload={...body.payload,fromDigest:list[i-1].digest};
200
+ list[i]={...body,digest:digest(body)};}return list;};
201
+ assert.equal(readRunnerHistory(reseal(structuredClone(rows)),config,3).reviewContinuation.reason.length>0,true,'reseal alone keeps a valid history');
202
+ const forged=structuredClone(rows);forged.at(-1).payload.receiptDigests=[...forged.at(-1).payload.receiptDigests].reverse();
203
+ assert.throws(()=>readRunnerHistory(reseal(forged),config,3),{code:'runner_history_mismatch'});
204
+ const twice=structuredClone(rows);twice.push({...structuredClone(rows.at(-1)),seq:rows.length+1,id:`runner.${String(rows.length+1).padStart(6,'0')}`});
205
+ twice.at(-1).payload.fromDigest=rows.at(-1).digest;
206
+ assert.throws(()=>readRunnerHistory(reseal(twice),config,3),{code:'review_continuation_unavailable'});
207
+ });
208
+
209
+ test('the gate refuses a runner-owned correction without the run marker',{skip},async t=>{
210
+ const g=await limited(t);
211
+ const {prepareContinuationCorrection}=await import('../runtime/js/cm-ai/review-continuation.mjs');
212
+ assert.throws(()=>prepareContinuationCorrection({reviewsDir:fs.realpathSync(reviews(g)),feature:'work',task:'T-002',
213
+ projectRoot:g.codeProject,reason:'no journaled authorization'}),/continuation marker/);
214
+ // A hand-written marker is not a run: it must carry every field and name a retained JS run.
215
+ const prepare=()=>prepareContinuationCorrection({reviewsDir:fs.realpathSync(reviews(g)),feature:'work',task:'T-002',
216
+ projectRoot:g.codeProject,reason:'forged marker'});
217
+ fs.writeFileSync(evidence(g,'review-continuation.json'),JSON.stringify({protocol:'cm-ai-review-continuation',feature:'work',task:'T-002'}));
218
+ assert.throws(prepare,/continuation marker/);
219
+ const forged=runId=>fs.writeFileSync(evidence(g,'review-continuation.json'),JSON.stringify({version:1,protocol:'cm-ai-review-continuation',
220
+ feature:'work',task:'T-002',repositoryId:'answer-gap',runId,fromDigest:'0'.repeat(64),at:'2026-11-29T00:00:00.000Z'}));
221
+ forged('no-such-run');assert.throws(prepare,/retained JS run/);
222
+ forged('..');assert.throws(prepare,/continuation marker/);
223
+ // The real run exists, but its journal never authorized a continuation (pilot on, no grant).
224
+ forged('answer-gap-run');assert.throws(prepare,/journal to hold this continuation authorization/);
225
+ // A real grant whose authorization record was rewritten and the chain resealed:
226
+ // fields match the marker, but the record no longer replays.
227
+ const h=await limited(t);await grant(h);
228
+ const raw=JSON.parse(fs.readFileSync(h.store,'utf8')),rows=raw.records,last=rows.at(-1);
229
+ last.payload.receiptDigests=[...last.payload.receiptDigests].reverse();
230
+ const {digest:_old,...body}=last;rows[rows.length-1]={...body,digest:digest(body)};
231
+ const {revision:_rev,...state}=raw;raw.revision=digest(state);
232
+ fs.writeFileSync(h.store,JSON.stringify(raw)+'\n');
233
+ assert.throws(()=>prepareContinuationCorrection({reviewsDir:fs.realpathSync(reviews(h)),feature:'work',task:'T-002',
234
+ projectRoot:h.codeProject,reason:'forged journal'}),/journal to hold this continuation authorization/);
235
+ assert.equal(fs.existsSync(evidence(g,'controlled-correction.json')),false);
236
+ });
237
+
238
+ // dogfood 2026-12-01(问题 12):检查失败或未改动的补正交付占掉名额后,续审仍要可用;
239
+ // 续审在原 6 次上限之外自带开发、审查各一次的名额(用户 2026-12-01 决定)。
240
+ test('a continuation carries its own develop and review slots beyond the original 6-call bound',{skip},async t=>{
241
+ const f=gapFixture(t,'review-continuation-budget');
242
+ await session(f,'create',execution(f,{developer:['one\n'],verdicts:['changes_requested']}),async host=>{
243
+ const delivered=await send(host,'start');
244
+ assert.equal((await send(host,'decision',1,{packageDigest:delivered.packageDigest})).state,'changes_requested');
245
+ });
246
+ // An unchanged a2 delivery spends a counted developer call before the real one.
247
+ await session(f,'resume',execution(f,{developer:['one\n','two\n'],verdicts:['changes_requested']}),async host=>{
248
+ assert.equal((await send(host,'start',2)).code,'develop_unchanged_after_review');
249
+ const delivered=await send(host,'start',2);
250
+ assert.equal((await send(host,'decision',2,{packageDigest:delivered.packageDigest})).code,'review_limit');
251
+ });
252
+ const card=(await status(f)).reviewLimitCard;
253
+ assert.equal(card.exits.find(e=>e.id==='review_continuation').available,true);
254
+ await grant(f);
255
+ await session(f,'resume',execution(f,{developer:['three\n'],verdicts:['approved']}),async host=>{
256
+ const delivered=await send(host,'start',2);assert.equal(delivered.state,'awaiting_review',JSON.stringify(delivered));
257
+ assert.equal((await send(host,'decision',2,{packageDigest:delivered.packageDigest})).state,'approved');
258
+ assert.equal((await send(host,'complete',2,{packageDigest:delivered.packageDigest})).state,'fixture_completed');
259
+ });
260
+ assert(tasksDone(f));
261
+ });
262
+
263
+ test('a correction that turns a reviewed file into an in-project symlink still reaches the third review',{skip},async t=>{
264
+ const f=await limited(t);
265
+ assert.equal(history(f).original.version>=2,true);
266
+ await grant(f);
267
+ const exec=execution(f,{developer:['unused\n'],verdicts:['approved']}),run=exec.developer.run;
268
+ exec.developer.run=async(request,control)=>{
269
+ const result=await run(request,control),target=path.join(f.codeProject,'a.mjs');
270
+ fs.rmSync(target);fs.symlinkSync('requirements.md',target);return result;
271
+ };
272
+ await session(f,'resume',exec,async host=>{
273
+ const delivered=await send(host,'start',2);assert.equal(delivered.state,'awaiting_review',JSON.stringify(delivered));
274
+ const reviewed=await send(host,'decision',2,{packageDigest:delivered.packageDigest});
275
+ assert.equal(reviewed.state,'approved',JSON.stringify(reviewed));
276
+ assert.equal((await send(host,'complete',2,{packageDigest:delivered.packageDigest})).state,'fixture_completed');
277
+ });
278
+ assert(fs.lstatSync(path.join(f.codeProject,'a.mjs')).isSymbolicLink());assert(tasksDone(f));
279
+ });
280
+
281
+ test('commit plans above four evidence files must pin the controlled correction record, review and receipt',async()=>{
282
+ const {planBytes}=await import('../runtime/js/cm-ai/task-commit-codec.mjs');
283
+ const before=Buffer.from('- [ ] T-002: fixture\n'),after=Buffer.from('- [x] T-002: fixture\n');
284
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
285
+ const plan=names=>{const body={version:1,protocol:'cm-mark-done-plan',feature:'work',taskId:'T-002',attempt:2,tasksPath:'/specs/1.work/tasks.md',
286
+ mode:0o644,beforeBase64:before.toString('base64'),afterBase64:after.toString('base64'),beforeDigest:sha(before),afterDigest:sha(after),
287
+ taskRevision:'a'.repeat(64),evidence:names.sort().map(name=>({path:`/specs/.reviews/${name}`,revision:'b'.repeat(64)}))};
288
+ return {...body,planDigest:digest(body)};};
289
+ const ordinary=['work-T-002-a1-handoff.json','work-T-002-r1.md','work-T-002-a2-handoff.json','work-T-002-r2.md'];
290
+ assert.doesNotThrow(()=>planBytes(plan(ordinary)));
291
+ assert.throws(()=>planBytes(plan([...ordinary,'work-T-002-extra.md'])),{code:'invalid_plan'});
292
+ const correction=['work-T-002-controlled-correction.json','work-T-002-controlled-correction.md','work-T-002-controlled-correction-receipt.json'];
293
+ assert.doesNotThrow(()=>planBytes(plan([...ordinary,...correction,'work-T-002-controlled-correction-handoff.json'])));
294
+ assert.throws(()=>planBytes(plan([...ordinary,...correction.slice(0,2),'work-T-002-controlled-correction-handoff.json'])),{code:'invalid_plan'});
295
+ // Missing an original round file is not a correction plan either.
296
+ assert.throws(()=>planBytes(plan([...ordinary.slice(0,2),...correction])),{code:'invalid_plan'});
297
+ });
298
+
299
+ test('healing skips a temp that vanished after listing and heals every evidence file in one pass',async t=>{
300
+ const {healAtomicTempLinks}=await import('./cm-task-gate.mjs');
301
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-heal-')));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
302
+ const file=name=>{const p=path.join(dir,name);fs.writeFileSync(p,name);return p;};
303
+ const temp=n=>path.join(dir,`.cm-gate-0000000${n}-0000-4000-8000-000000000000`);
304
+ // Regression: removing the first file's temp made the second file's scan read it and throw ENOENT.
305
+ const receipt=file('work-T-002-controlled-correction-receipt.json'),record=file('work-T-002-controlled-correction.json');
306
+ fs.linkSync(receipt,temp(1));fs.linkSync(record,temp(2));
307
+ assert.doesNotThrow(()=>healAtomicTempLinks(dir,[receipt,record]));
308
+ assert.deepEqual([fs.lstatSync(receipt).nlink,fs.lstatSync(record).nlink],[1,1]);
309
+ assert.equal(fs.existsSync(temp(1))||fs.existsSync(temp(2)),false);
310
+ // A peer temp removed by its own writer between listing and reading is skipped.
311
+ const handoff=file('work-T-002-controlled-correction-handoff.json');fs.linkSync(handoff,temp(9));
312
+ const realLstat=fs.lstatSync,realList=fs.readdirSync;let removed=false;
313
+ // Pin the listing so the vanished name is visited before the handoff's own temp.
314
+ t.mock.method(fs,'readdirSync',(target,...rest)=>{const names=realList(target,...rest),first='.cm-gate-00000003-0000-4000-8000-000000000000';
315
+ return names.includes(first)?[first,...names.filter(name=>name!==first)]:names;});
316
+ t.mock.method(fs,'lstatSync',(target,...rest)=>{
317
+ if(!removed&&String(target).endsWith('.cm-gate-00000003-0000-4000-8000-000000000000')){removed=true;
318
+ throw Object.assign(new Error('gone'),{code:'ENOENT'});}
319
+ return realLstat(target,...rest);});
320
+ fs.writeFileSync(temp(3),'peer temp');
321
+ assert.doesNotThrow(()=>healAtomicTempLinks(dir,[handoff]));
322
+ t.mock.restoreAll();
323
+ assert(removed,'the vanished temp was visited');assert.equal(fs.lstatSync(handoff).nlink,1);
324
+ // Another file's gate-shaped temp listed first: only the inode comparison keeps it.
325
+ const notes=file('manual-notes.md'),receipt2=file('work-T-003-controlled-correction-receipt.json');
326
+ const peer=path.join(dir,'.cm-gate-11111111-1111-4111-8111-111111111111'),own=path.join(dir,'.cm-gate-22222222-2222-4222-8222-222222222222');
327
+ fs.linkSync(notes,peer);fs.linkSync(receipt2,own);
328
+ const realReaddir=fs.readdirSync;
329
+ t.mock.method(fs,'readdirSync',(target,...rest)=>{const names=realReaddir(target,...rest);
330
+ return [path.basename(peer),...names.filter(name=>name!==path.basename(peer))];});
331
+ healAtomicTempLinks(dir,[receipt2]);
332
+ t.mock.restoreAll();
333
+ assert.equal(fs.existsSync(peer),true,'a link to another file survives');assert.equal(fs.existsSync(own),false);
334
+ assert.deepEqual([fs.lstatSync(notes).nlink,fs.lstatSync(receipt2).nlink],[2,1]);
335
+ });