@aibyzero/cm-workflow 0.16.8 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,99 @@
1
+ import test,{after} from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn,spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {releaseVerifiedQaResources,inspectOpenQaResources} from '../runtime/js/cm-ai/qa-resource-release.mjs';
9
+ import {readProcessStartTime,inspectWorkerGroup} from '../runtime/js/cm-ai/worker-process-identity.mjs';
10
+ import {qaRoundDeadlineMs} from '../runtime/js/cm-ai/host-qa-executor.mjs';
11
+ import {qaRoundLimit} from '../runtime/js/cm-ai/qa-round-budget.mjs';
12
+ import {inspectRunClosure} from './cm-log-event.mjs';
13
+
14
+ const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-qa-gaps-home-'));
15
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
16
+ process.env.CM_WORKFLOW_HOME=path.join(home,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(home,'logs');
17
+ after(()=>{for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
18
+ fs.rmSync(home,{recursive:true,force:true});});
19
+ const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
20
+ const POSIX={skip:process.platform==='win32'};
21
+
22
+ function fixture(){
23
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-qa-gaps-')));
24
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code');
25
+ fs.mkdirSync(specsDir);fs.mkdirSync(codeProject);
26
+ const log=path.join(specsDir,'运行日志.jsonl'),runId='qa-gap-run-0001';
27
+ const write=(phase,data)=>{const result=spawnSync('python3',[writer,'--workflow','cm-ai','--event','resource','--phase',phase,
28
+ '--runtime','codex','--project-root',codeProject,'--specs-dir',specsDir,'--run-id',runId,'--detail','fixture',
29
+ '--data-json',JSON.stringify(data)],{timeout:10000});assert.equal(result.status,0,String(result.stderr));};
30
+ return {root,specsDir,codeProject,log,runId,write};
31
+ }
32
+ const until=async(predicate,ms=5000)=>{const end=Date.now()+ms;while(Date.now()<end&&!predicate())await new Promise(r=>setTimeout(r,25));};
33
+
34
+ // Q13/Q26: a cleanup_failed QA command resource is released by the host only
35
+ // with the proof its journaled process group is gone; anything else stays open.
36
+ test('cleanup_failed QA command resources are released only once their process group is proven gone',POSIX,async()=>{
37
+ const f=fixture();const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{detached:true,stdio:'ignore'});child.unref();
38
+ try{
39
+ const pid=child.pid,startTime=readProcessStartTime(pid);assert.notEqual(startTime,null);
40
+ for(const id of ['qa-command-live','qa-command-legacy']){
41
+ f.write('acquired',{resource_id:id,resource_kind:'qa_command',cleanup_required:true});
42
+ f.write('cleanup_failed',{resource_id:id,resource_kind:'qa_command',...(id==='qa-command-live'?{pid,process_start_time:startTime}:{})});
43
+ }
44
+ assert.equal(inspectRunClosure(f.log,f.runId).closed,false);
45
+ let result=releaseVerifiedQaResources({specsDir:f.specsDir,codeProject:f.codeProject,runId:f.runId});
46
+ assert.deepEqual(result.released,[]);
47
+ assert.deepEqual(result.open.map(item=>[item.resourceId,item.verdict]),[['qa-command-live','alive'],['qa-command-legacy','unrecorded']]);
48
+ process.kill(-pid,'SIGKILL');
49
+ await until(()=>{try{process.kill(-pid,0);return false;}catch(error){return error.code==='ESRCH';}});
50
+ result=releaseVerifiedQaResources({specsDir:f.specsDir,codeProject:f.codeProject,runId:f.runId});
51
+ assert.deepEqual(result.released,['qa-command-live']);assert.deepEqual(result.open.map(item=>item.resourceId),['qa-command-legacy']);
52
+ const released=fs.readFileSync(f.log,'utf8').trim().split('\n').map(JSON.parse).findLast(row=>row.phase==='released');
53
+ assert.equal(released.verification,'process_group_gone');assert.equal(released.pid,pid);
54
+ // Idempotent: nothing left to release; the legacy row still keeps the run open.
55
+ assert.deepEqual(releaseVerifiedQaResources({specsDir:f.specsDir,codeProject:f.codeProject,runId:f.runId}).released,[]);
56
+ assert.equal(inspectRunClosure(f.log,f.runId).closed,false);
57
+ assert.deepEqual(inspectOpenQaResources({specsDir:f.specsDir,runId:f.runId}).map(row=>row.resource_id),['qa-command-legacy']);
58
+ }finally{try{process.kill(-child.pid,'SIGKILL');}catch{}fs.rmSync(f.root,{recursive:true,force:true});}
59
+ });
60
+
61
+ test('worker group inspection treats Windows, permission errors and unreadable start times as unknown',()=>{
62
+ const fail=code=>()=>{throw Object.assign(new Error(code),{code});};
63
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'x'},{platform:'win32'}),'unknown');
64
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'x'},{platform:'darwin',kill:fail('EPERM')}),'unknown');
65
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'x'},{platform:'darwin',kill:fail('ESRCH')}),'gone');
66
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'Mon'},{platform:'darwin',kill:()=>true,startTimeOf:()=>'Mon'}),'alive');
67
+ // The pid now belongs to a process started at another time: the recorded group ended.
68
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'Mon'},{platform:'darwin',kill:()=>true,startTimeOf:()=>'Tue'}),'gone');
69
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'Mon'},{platform:'darwin',kill:()=>true,startTimeOf:()=>null}),'unknown');
70
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:null},{platform:'darwin',kill:()=>true}),'unknown');
71
+ let calls=0;
72
+ assert.equal(inspectWorkerGroup({pid:4242,startTime:'Mon'},{platform:'darwin',kill:target=>{calls++;if(target>0)fail('ESRCH')();return true;}}),'alive',
73
+ 'members of the group outlive the leader');
74
+ assert.equal(calls,2);
75
+ for(const pid of [0,1,-5,1.5,2**31])assert.equal(inspectWorkerGroup({pid,startTime:'x'},{platform:'darwin'}),'unknown');
76
+ });
77
+
78
+ // Q12: the whole-round deadline scales with the per-case limit and the case count.
79
+ test('QA round deadline scales with commands, logic and browser cases',()=>{
80
+ const plan={modes:['commands','logic','browser'],commands:[{id:'a'},{id:'b'}],
81
+ cases:[{kind:'logic'},{kind:'browser'},{kind:'browser'},{kind:'browser'}]};
82
+ assert.equal(qaRoundDeadlineMs({timeoutMs:1800000,requestTimeoutMs:3600000,configuration:{plan}}),
83
+ 2*1800000+3600000+3*2*3600000+60000);
84
+ assert.equal(qaRoundDeadlineMs({timeoutMs:1800000,requestTimeoutMs:60000,configuration:{plan:{modes:['browser'],commands:[],cases:[{kind:'browser'}]}}}),1800000);
85
+ assert.equal(qaRoundDeadlineMs({timeoutMs:1800000,requestTimeoutMs:3600000,configuration:{plan:{...plan,cases:Array(40).fill({kind:'browser'})}}}),24*3600000);
86
+ assert.equal(qaRoundDeadlineMs({timeoutMs:2000}),2000);
87
+ assert.deepEqual([0,1,2,3].map(qaRoundLimit),[3,4,5,5]);
88
+ });
89
+
90
+ // The second-batch blocks wait for a person: the stuck notifier classifies them so.
91
+ test('notify classifies the new answer-gap blocks as stuck',async()=>{
92
+ const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
93
+ for(const row of [{state:'blocked',code:'develop_interrupted',pendingAction:'resume',outcome:'recorded'},
94
+ {state:'blocked',code:'complete_commit_interrupted',pendingAction:'complete',outcome:'reported'},
95
+ {state:'blocked',code:'develop_out_of_scope',pendingAction:'resume',outcome:'advanced'},
96
+ {state:'fixture_completed',code:'qa_resources_open',pendingAction:'none',outcome:'blocked'}])
97
+ assert.equal(classifyDriveResult('cm-ai',{result:row}),'stuck',JSON.stringify(row));
98
+ assert.equal(classifyDriveResult('cm-fix',{result:{stage:'regression_blocked',blockedRerun:{pending:'regression',used:0,limit:2}}}),'stuck');
99
+ });
@@ -80,15 +80,7 @@ function buildExecution(f,{twoAttempts=false}={}){
80
80
  examinedPaths:reviewPaths(request.payload.reviewPackage),findings:verdict==='approved'?[]:
81
81
  [{id:'F1',severity:'P2',path:'a.js',message:'Review again',evidence:'Synthetic first attempt'}],summary:'Synthetic review'}};
82
82
  }}],
83
- reviewInvocation:{developerThreadId:'host-author',excludedThreadIds:['main'],
84
- authorize:(request,{authorizationAt})=>{
85
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.identity.attempt}`,adapterId:'codex-review-adapter',
86
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
87
- reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
88
- hostContextId:'main',decisionId:`decision-${request.identity.attempt}`,decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
89
- return {...body,grantDigest:digest(body)};
90
- }},
91
- hostDecision:{status:'approved'},
83
+ reviewInvocation:{developerThreadId:'host-author',excludedThreadIds:['main']},
92
84
  check:createHostCheck({cwd:f.codeProject,commands:[{id:'content',command:[process.execPath,'-e',
93
85
  "require('node:assert/strict').match(require('node:fs').readFileSync('a.js','utf8'),/^new( 2)?\\n$/)"]}]})};
94
86
 
@@ -44,9 +44,9 @@ const environment={kind:'web',carrier:'browser',target:'fixture',scope:'local'};
44
44
  const syntax=[{id:'unit',command:[process.execPath,'--check','a.mjs'],caseIds:[]}];
45
45
 
46
46
  // The real current-conversation factory builds the built-in QA executor.
47
- const conversation=(f,commands=syntax)=>createConversationExecution(f.definition,'host-session-1',
47
+ const conversation=(f,commands=syntax,criticalPaths=undefined)=>createConversationExecution(f.definition,'host-session-1',
48
48
  {call:async()=>{throw new Error('not dispatched');}},null,null,
49
- {qa:{commands,environment},documentationPaths:[],applicableAgentFiles:[]},true,'claude');
49
+ {qa:{commands,environment,...(criticalPaths===undefined?{}:{criticalPaths})},documentationPaths:[],applicableAgentFiles:[]},true,'claude');
50
50
  async function opens(f,mode,execution,options){
51
51
  const run=await openControlRun(f.definition,mode,execution,options);run.close();
52
52
  }
@@ -88,13 +88,7 @@ function synthetic(f,{commands=syntax,browser=null}={}){
88
88
  onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
89
89
  return {status:'succeeded',value:{verdict:'approved',packageDigest:review.payload.reviewPackage.packageDigest,
90
90
  examinedPaths:reviewPaths(review.payload.reviewPackage),findings:[],summary:'Synthetic review'}};}}],
91
- reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],authorize:(review,{authorizationAt})=>{
92
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${review.identity.attempt}`,adapterId:'codex-review-adapter',
93
- invocationId:review.invocationId,requestDigest:review.requestDigest,identity:review.identity,reviewerId:'reviewer',
94
- logicalContextId:review.contextId,packageDigest:review.payload.reviewPackage.packageDigest,hostContextId:'control',
95
- decisionId:'decision',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
96
- return {...body,grantDigest:digest(body)};}},
97
- hostDecision:{status:'approved'},check:createHostCheck({cwd:f.codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
91
+ reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']},check:createHostCheck({cwd:f.codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
98
92
  qaLogHome:logHome,
99
93
  qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:'qa-decision',identity:binding.identity,
100
94
  packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T00:00:00Z'})},
@@ -155,3 +149,12 @@ test('#14 a store fingerprinted in the historical plan form still opens and adva
155
149
  assert.equal((await run.host.handle(request('advance'))).code,'qa_passed');run.close();
156
150
  assert.equal(JSON.parse(fs.readFileSync(state)).fingerprints.config,digest(legacy));
157
151
  });
152
+
153
+ test('N6 registered critical paths use existing workflow QA seam and fingerprint',async()=>{
154
+ const f=fixture();userRuntimes('codex-codes');
155
+ const registry={payment:['src/payments/**'],api:['a.mjs']};
156
+ const execution=conversation(f,syntax,registry);
157
+ await opens(f,'create',execution);
158
+ await opens(f,'resume',conversation(f,syntax,registry));
159
+ await assert.rejects(opens(f,'resume',conversation(f,syntax,{payment:['src/billing/**']})),{code:'fingerprint_mismatch'});
160
+ });
@@ -32,7 +32,7 @@ function events(onEvent,thread){
32
32
  {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},
33
33
  {event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
34
34
  }
35
- async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0}={}){
35
+ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0,rejectedCauseReviews=0}={}){
36
36
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'qa-fix-session-')));
37
37
  const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.value';
38
38
  fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
@@ -56,7 +56,7 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0}={}){
56
56
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
57
57
  }};
58
58
  const executionFor=live=>{
59
- const execution=createConversationExecution(definition,live,bridge,review,1,workflow,true,'codex',
59
+ const execution=createConversationExecution(definition,live,bridge,review,null,workflow,true,'codex',
60
60
  live===A?{}:{originalHostContextId:A});
61
61
  execution.check=createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]});
62
62
  execution.reviewers[0].run=async(request,{onEvent})=>{
@@ -86,9 +86,12 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0}={}){
86
86
  const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
87
87
  if(++causeReviews<=lostCauseReviews){onEvent({event:'thread.started',provider_thread:`lost-child-review-${causeReviews}`});
88
88
  throw Error('Synthetic lost cause review');}
89
- events(onEvent,'synthetic-child-review');
90
- return {status:'succeeded',value:{verdict:'approved',packageDigest:data.reviewPackage.packageDigest,
91
- examinedPaths:['value.mjs'],findings:[],summary:'Synthetic cause review'}};
89
+ // A later independent review needs a fresh reviewer thread.
90
+ events(onEvent,causeReviews>lostCauseReviews+1?`synthetic-child-review-${causeReviews}`:'synthetic-child-review');
91
+ const rejected=causeReviews<=lostCauseReviews+rejectedCauseReviews;
92
+ return {status:'succeeded',value:{verdict:rejected?'changes_requested':'approved',packageDigest:data.reviewPackage.packageDigest,
93
+ examinedPaths:['value.mjs'],findings:rejected?[{id:'F1',severity:'P2',path:'value.mjs',message:'Cause is incomplete',evidence:'Fixture finding'}]:[],
94
+ summary:'Synthetic cause review'}};
92
95
  }});
93
96
  const configuration={hostContextId:childHost,defect:'Value must be 2',qaSource,
94
97
  causeReview:{...reviewHost(A).reviewer,...(causeContext?{contextId:causeContext}:{})},
@@ -97,15 +100,15 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0}={}){
97
100
  const childDir=path.join(specsDir,'.reviews','.execution',fix.identity.runId),statePath=path.join(childDir,'state.json');
98
101
  const bound=operation=>({...request(operation),packageDigest:failed.packageDigest,testRunId:qaSource.testRunId});
99
102
  const close=()=>{owner?.close();owner=null;};
100
- const open=async(live,{allowStart=true,template=false,allowAbandon=false,lostDiagnosis=false}={})=>{
103
+ const open=async(live,{allowStart=true,template=false,allowAbandon=false,lostDiagnosis=false,extraPermissions=[],controlPolicy=null}={})=>{
101
104
  close();const execution=executionFor(live);assert.equal(execution.configuration.hostContextId,A);
102
105
  parent=await openControlRun(definition,'resume',execution);
103
106
  const rh=reviewHost(live);
104
107
  const {qaSource:ignored,...templateConfiguration}=configuration;
105
108
  owner=createQaFixOwnerHost({parent,hostContextId:live,parentHostContextId:execution.configuration.hostContextId,
106
- reopenParent:()=>openControlRun(definition,'resume',execution),allowStart,
109
+ reopenParent:()=>openControlRun(definition,'resume',execution),allowStart,controlPolicy,
107
110
  ...(template?{template:{specsRoot:specsDir,feature,identity,configuration:templateConfiguration}}:{fix}),
108
- fixPermissions:allowAbandon?[...permissions,'--allow-abandon']:permissions,
111
+ fixPermissions:[...permissions,...(allowAbandon?['--allow-abandon']:[]),...extraPermissions],
109
112
  fixAuthorities:{authority:rh.authority,finalAuthority:rh.finalAuthority},
110
113
  fixExecution:{...rh.execution,prepare,bridge:{async call(kind){assert.equal(kind,'fix_diagnose');
111
114
  if(lostDiagnosis)throw Error('Synthetic lost diagnosis');return diagnosis;}}}});
@@ -120,7 +123,7 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0}={}){
120
123
 
121
124
  // Exercise the actual CLI assembly as well as the direct owner. The CLI only
122
125
  // resumes/status/reviews here: these operations do not require a native sandbox.
123
- async function cli(f,live,operation,{runtime='codex',flags=[]}={}){
126
+ async function cli(f,live,operation,{runtime='codex',flags=[],diagnosed=diagnosis}={}){
124
127
  f.close();fs.writeFileSync(path.join(f.root,'fix.json'),JSON.stringify(f.fix));
125
128
  const args=['serve','--config',path.join(f.root,'run.json'),'--mode','resume','--host-context',live,'--allow-development',
126
129
  '--original-host-context',A,'--review-config',path.join(f.root,'review.json'),'--workflow-config',path.join(f.root,'workflow.json'),'--allow-qa',
@@ -143,7 +146,7 @@ async function cli(f,live,operation,{runtime='codex',flags=[]}={}){
143
146
  if(row.type==='host_request'){
144
147
  assert(['fix_learning','fix_diagnose'].includes(row.kind),row.kind);
145
148
  const result=row.kind==='fix_learning'
146
- ?{contextDigest:row.payload.contextDigest,status:'no_relevant_lesson',summary:'Synthetic fixture'}:diagnosis;
149
+ ?{contextDigest:row.payload.contextDigest,status:'no_relevant_lesson',summary:'Synthetic fixture'}:diagnosed;
147
150
  child.stdin.write(JSON.stringify({type:'host_result',sessionId:row.sessionId,callId:row.callId,
148
151
  requestDigest:row.requestDigest,result})+'\n');
149
152
  }
@@ -189,6 +192,21 @@ for(const operation of ['fix_status','fix_advance'])test(`live cause reviewer is
189
192
  assert.deepEqual(fs.readFileSync(f.statePath),bytes);
190
193
  });
191
194
 
195
+ test('v2 child recovery refuses a stale child snapshot with unchanged parent and preserves child records',async t=>{
196
+ const f=await fixture(t),policy={version:2,development:'conversation',bootstrap:'disabled',qa:'run',qaFix:'manual'};
197
+ let owner=await f.open(A,{controlPolicy:policy,allowAbandon:true});
198
+ await owner.handle(f.bound('fix_advance'));
199
+ const preview=(await owner.handle(f.bound('fix_status'))).childControlTarget;
200
+ assert.equal(preview.runId,f.fix.identity.runId);assert.equal(preview.revision,JSON.parse(fs.readFileSync(f.statePath)).revision);
201
+ // Advance the real child only; the completed parent identity/package stay unchanged.
202
+ await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'});
203
+ const bytes=fs.readFileSync(f.statePath);
204
+ await assert.rejects(owner.handle({...f.bound('fix_action'),fixOperation:'abandon_step',reason:'Synthetic stale recovery',expectedFixControl:preview}),
205
+ {code:'snapshot_changed'});
206
+ assert.deepEqual(fs.readFileSync(f.statePath),bytes);
207
+ assert.equal((await owner.handle(f.request('status'))).state,'fixture_completed');
208
+ });
209
+
192
210
  test('owner requires a valid live host id',async t=>{
193
211
  const f=await fixture(t);
194
212
  for(const hostContextId of [undefined,'invalid host'])assert.throws(()=>createQaFixOwnerHost({hostContextId,parentHostContextId:A,
@@ -247,7 +265,9 @@ test('QA-fix child abandons a lost local diagnosis only with its dedicated CLI f
247
265
  const request={...f.bound('fix_action'),fixOperation:'abandon_step',reason:'Child diagnosis response lost'};
248
266
  const before=fs.readFileSync(f.statePath);
249
267
  const denied=await cli(f,A,request);
250
- assert.match(denied.stderr,/fix_abandon_unavailable/);
268
+ assert.equal(denied.code,0,denied.stderr);
269
+ assert.deepEqual([denied.result?.outcome,denied.result?.code],['rejected','qa_fix_action_authorization_required'],JSON.stringify(denied.result));
270
+ assert.match(denied.result.reason,/--allow-qa-fix-abandon(/);
251
271
  assert.deepEqual(fs.readFileSync(f.statePath),before);
252
272
  const allowed=await cli(f,A,request,{flags:['--allow-qa-fix-abandon']});
253
273
  assert.equal(allowed.code,0,allowed.stderr);
@@ -266,11 +286,15 @@ test('#15 a QA-fix child cause review without a result is abandoned once through
266
286
  assert.equal(reviewed.fixStage,'unknown');assert.equal(reviewed.actionResult.reviewAbandonable,'cause_review');
267
287
  const request={...f.bound('fix_action'),fixOperation:'abandon_review',reason:'Child cause reviewer confirmed stopped'};
268
288
  const before=fs.readFileSync(f.statePath);
269
- await assert.rejects(owner.handle(request),{code:'fix_review_abandon_authorization_required'});
289
+ const refused=await owner.handle(request);
290
+ assert.deepEqual([refused.outcome,refused.code],['rejected','qa_fix_action_authorization_required']);
291
+ assert.match(refused.reason,/--allow-qa-fix-abandon-review/);
292
+ assert.equal((await owner.handle(f.request('status'))).state,'fixture_completed');
270
293
  assert.deepEqual(fs.readFileSync(f.statePath),before);
271
294
  f.close();
272
295
  const local=await cli(f,A,request,{flags:['--allow-qa-fix-abandon']});
273
- assert.match(local.stderr,/fix_review_abandon_authorization_required/);assert.deepEqual(fs.readFileSync(f.statePath),before);
296
+ assert.equal(local.result?.code,'qa_fix_action_authorization_required',JSON.stringify(local.result));
297
+ assert.match(local.result.reason,/--allow-qa-fix-abandon-review/);assert.deepEqual(fs.readFileSync(f.statePath),before);
274
298
  const allowed=await cli(f,A,request,{flags:['--allow-qa-fix-abandon-review']});
275
299
  assert.equal(allowed.code,0,allowed.stderr);assert.equal(allowed.result?.fixStage,'cause_review_required');
276
300
  assert(f.records().some(row=>row.id==='fix-cause-abandoned'));
@@ -278,3 +302,61 @@ test('#15 a QA-fix child cause review without a result is abandoned once through
278
302
  assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');
279
303
  assert.equal(f.records().find(row=>row.id==='fix-cause-retry-started').payload.providerThreadId,'synthetic-child-review');
280
304
  });
305
+
306
+ // Q23/F08: a rejected child cause review reaches rediagnosis_required. Before this
307
+ // the parent fix_action refused rediagnose, so the only exit was closing the parent
308
+ // and reopening the child with cm-fix-host. Now the parent host forwards it to the
309
+ // same cm-fix dispatcher under --allow-qa-fix-rediagnosis, and the child continues.
310
+ test('Q23 a QA-fix child rediagnoses through the parent host fix_action, then its round-2 cause review proceeds',async t=>{
311
+ const f=await fixture(t,{rejectedCauseReviews:1});
312
+ let owner=await f.open(A);
313
+ assert.equal((await owner.handle(f.bound('fix_advance'))).fixStage,'cause_review_required');
314
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'rediagnosis_required');
315
+ f.close();
316
+ const request={...f.bound('fix_action'),fixOperation:'rediagnose',reason:'根因审查要求补充跨层证据'};
317
+ const before=fs.readFileSync(f.statePath);
318
+ // Without the parent flag: an explicit refusal naming it, nothing written, parent reopened.
319
+ const denied=await cli(f,A,request);
320
+ assert.equal(denied.code,0,denied.stderr);
321
+ assert.deepEqual([denied.result?.outcome,denied.result?.code],['rejected','qa_fix_action_authorization_required'],JSON.stringify(denied.result));
322
+ assert.match(denied.result.reason,/--allow-qa-fix-rediagnosis/);assert.equal(denied.result.guidance.authorizationGranted,false);
323
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
324
+ // A missing reason is still the original cm-fix refusal, reported with its code.
325
+ const reasonless=await cli(f,A,{...request,reason:'第一行\n第二行'},{flags:['--allow-qa-fix-rediagnosis']});
326
+ assert.deepEqual([reasonless.result?.outcome,reasonless.result?.code],['rejected','fix_rediagnosis_reason_invalid'],JSON.stringify(reasonless.result));
327
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
328
+ const revised={...diagnosis,rootCause:'Wrong constant; revised after review',crossLayer:false};
329
+ const allowed=await cli(f,A,request,{flags:['--allow-qa-fix-rediagnosis'],diagnosed:revised});
330
+ assert.equal(allowed.code,0,allowed.stderr);
331
+ assert.equal(allowed.result?.fixStage,'cause_review_required',JSON.stringify(allowed.result));
332
+ assert.deepEqual(f.records().slice(0,JSON.parse(before).records.length),JSON.parse(before).records,'journal is append-only');
333
+ assert(f.records().some(row=>row.id==='fix-rediagnosis-intent'));
334
+ assert.equal(f.records().find(row=>row.id==='fix-rediagnosis-result').payload.rootCause,revised.rootCause);
335
+ // The batch continues: the second, independent cause review approves and publishes cause-r2.
336
+ owner=await f.open(A);
337
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');
338
+ assert(fs.readdirSync(path.join(path.dirname(f.childDir),'..')).some(name=>/-cause-r2\.md$/.test(name)));
339
+ });
340
+
341
+ // Q23/F25: recover_final_review and rerun_blocked_step reach the same dispatcher;
342
+ // a stage that does not qualify is the original cm-fix refusal, not host_request_failed.
343
+ test('Q23 recover_final_review and rerun_blocked_step through fix_action report the original cm-fix refusal codes',async t=>{
344
+ const f=await fixture(t);
345
+ let owner=await f.open(A,{extraPermissions:['--allow-final-review-recovery','--allow-rerun-blocked-step']});
346
+ assert.equal((await owner.handle(f.bound('fix_advance'))).fixStage,'cause_review_required');
347
+ const before=fs.readFileSync(f.statePath);
348
+ const recovery=await owner.handle({...f.bound('fix_action'),fixOperation:'recover_final_review',invocationId:'final-review-invocation',
349
+ reviewPackageDigest:'a'.repeat(64),previousInvocationStopped:true,reason:'旧审查进程已退出'});
350
+ assert.deepEqual([recovery.outcome,recovery.code],['rejected','fix_review_recovery_unavailable'],JSON.stringify(recovery));
351
+ const rerun=await owner.handle({...f.bound('fix_action'),fixOperation:'rerun_blocked_step',reason:'环境已修好'});
352
+ assert.deepEqual([rerun.outcome,rerun.code],['rejected','fix_blocked_rerun_unavailable'],JSON.stringify(rerun));
353
+ assert.equal((await owner.handle(f.request('status'))).state,'fixture_completed');
354
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
355
+ f.close();owner=await f.open(A);
356
+ const missing=await owner.handle({...f.bound('fix_action'),fixOperation:'recover_final_review',invocationId:'final-review-invocation',
357
+ reviewPackageDigest:'a'.repeat(64),previousInvocationStopped:true,reason:'旧审查进程已退出'});
358
+ assert.deepEqual([missing.code,missing.fixOperation],['qa_fix_action_authorization_required','recover_final_review']);
359
+ assert.match(missing.reason,/--allow-qa-fix-final-review-recovery/);
360
+ const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
361
+ assert.equal(classifyDriveResult('cm-ai',{result:missing}),'stuck');
362
+ });
@@ -0,0 +1,41 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {readDecision,recordCmAiQaDecision,findCmAiQaDecision} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
7
+ const identity={repositoryId:'fixture',runId:'fixed-log',taskId:'T-001',attempt:1},packageDigest='a'.repeat(64);
8
+ const decision=(status,score,reason)=>({decisionId:'qa-fixed',identity,packageDigest,status,score,reason,at:'2026-10-12T00:00:00Z'});
9
+ test('N6 decision accepts null scores for every status and preserves legacy thresholds',()=>{
10
+ for(const [status,reason] of [['skipped','no_fixed_trigger'],['skipped','merged_to_feature_qa'],['triggered','payment,api'],['blocked','host_request_timeout']])
11
+ assert.equal(readDecision(decision(status,null,reason),identity,packageDigest).score,null);
12
+ for(const [status,score] of [['skipped',4],['skipped',7],['triggered',8],['triggered',20],['blocked',4],['blocked',20]])
13
+ assert.equal(readDecision(decision(status,score,'historical'),identity,packageDigest).score,score);
14
+ });
15
+ test('N6 legacy decision rejects illegal non-null scores including coercible values',()=>{
16
+ for(const status of ['skipped','triggered','blocked'])for(const score of [undefined,'4','8',false,true,{},[],3,21,4.5])
17
+ assert.throws(()=>readDecision(decision(status,score,'historical'),identity,packageDigest),`${status}/${JSON.stringify(score)}`);
18
+ for(const [status,score] of [['skipped',8],['triggered',7]])
19
+ assert.throws(()=>readDecision(decision(status,score,'historical'),identity,packageDigest));
20
+ });
21
+ test('N6 null skip logs reason and changed file source, keeps old bytes and merge event',()=>{
22
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-fixed-log-')));
23
+ try{
24
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code');fs.mkdirSync(specsDir);fs.mkdirSync(codeProject);
25
+ const log=path.join(specsDir,'运行日志.jsonl'),old='{"historical":"byte exact"}\n';fs.writeFileSync(log,old);
26
+ const binding={specsDir,codeProject,feature:'1.work',identity,packageDigest,logHome:path.join(root,'logs')};
27
+ const value={...decision('skipped',null,'no_fixed_trigger'),changedFilesSource:'handoff_only'};
28
+ recordCmAiQaDecision({...binding,decision:value});
29
+ recordCmAiQaDecision({...binding,decision:value});
30
+ assert(fs.readFileSync(log,'utf8').startsWith(old));
31
+ const row=fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse).at(-1);
32
+ assert.equal(row.detail,'跳过:no_fixed_trigger');assert.equal(row.changed_files_source,'handoff_only');assert.equal(row.score,null);
33
+ const {codeProject:_,logHome:__,...query}=binding;
34
+ assert.equal(findCmAiQaDecision(query).changedFilesSource,'handoff_only');
35
+ const merged={...binding,identity:{...identity,runId:'fixed-merge'},decision:{...decision('skipped',null,'merged_to_feature_qa'),identity:{...identity,runId:'fixed-merge'}}};
36
+ recordCmAiQaDecision(merged);
37
+ const rows=fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
38
+ assert.equal(rows.filter(row=>row.phase==='qa_merge').length,1);
39
+ assert.equal(rows.at(-1).reason,'merged_to_feature_qa');
40
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
41
+ });
@@ -78,3 +78,10 @@ test('a single recovery flag with --allow-qa passes the launch guards', () => ba
78
78
  assert.equal(line(withFlag),line(without));
79
79
  assert.equal(withFlag.status,without.status);
80
80
  }));
81
+
82
+ test('N6 QA critical paths accept grouped relative globs and reject malformed registration',()=>{
83
+ const criticalPaths={migration:['db/migrations/**'],authentication:['src/login.mjs'],authorization:['src/access/*.mjs'],payment:['src/payment?.mjs'],api:['src/api/**']};
84
+ assert.deepEqual(validateHostWorkflowConfiguration({...workflow(undefined),qa:{...qa(undefined),criticalPaths}}).qa.criticalPaths,criticalPaths);
85
+ for(const value of [null,[],{unknown:['src/**']},{api:'src/**'},{api:['../src/**']},{api:['src/{a,b}.mjs']}])
86
+ assert.throws(()=>validateHostWorkflowConfiguration({...workflow(undefined),qa:{...qa(undefined),criticalPaths:value}}));
87
+ });
@@ -29,8 +29,7 @@ const POSIX={skip:process.platform==='win32'?'host-check QA commands and the fix
29
29
  const identity={repositoryId:'qa-rerun-fixture',runId:'qa-rerun-run',taskId:'T-001',attempt:1};
30
30
  const simulator={kind:'app',carrier:'ios-simulator',target:'Fixture-iPhone',scope:'local'};
31
31
  const service={kind:'service',carrier:'cli',target:'node',scope:'local'};
32
- const lowRisk={scores:{scope:1,risk:1,accumulation:1,boundary:1},
33
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
32
+ const lowRisk={confirmed:true};
34
33
 
35
34
  // The QA command stands in for xcodebuild/simulator scripts. It reads a mode
36
35
  // file outside both roots, so switching the "environment" never touches the
@@ -115,7 +114,7 @@ function failingStartShim(f){
115
114
  function launch(f,{mode='resume',operation='advance',workflow=null,extra=[],answers={},review=true,pathPrefix=null}={}){
116
115
  return new Promise((resolve,reject)=>{
117
116
  const args=['serve','--config',f.config,'--mode',mode,'--host-context','session-A','--allow-development',
118
- '--review-config',f.reviewFile,...(review?['--allow-review-attempt','1']:[]),
117
+ '--review-config',f.reviewFile,...(review?[]:[]),
119
118
  ...(workflow?['--workflow-config',workflow,'--allow-qa']:[]),...extra];
120
119
  const env=pathPrefix?{...f.env,PATH:pathPrefix+path.delimiter+f.env.PATH}:f.env;
121
120
  const child=spawn(process.execPath,[cli,...args],{env,stdio:['pipe','pipe','pipe']});
@@ -250,19 +249,21 @@ test('#13 a host-declared BLOCKED simulator case re-runs on unchanged code with
250
249
  assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['BLOCKED','PASS']);
251
250
  });
252
251
 
253
- test('#13 an unavailable QA command (killed, no exit code) re-runs; the round budget still caps at three',POSIX,async t=>{
252
+ // Q14: rounds ended by a host or environment gap (here a killed command) do not
253
+ // count toward the three-round budget, but at most two are given back per run.
254
+ test('#13 an unavailable QA command (killed, no exit code) re-runs; host-caused rounds give back at most two',POSIX,async t=>{
254
255
  const f=fixture(t),workflow=f.workflow('workflow',probeQa());
255
256
  f.environment('killed');
256
257
  const first=done(await launch(f,{mode:'create',workflow}));
257
258
  assert.equal(first.code,'qa_result_blocked',JSON.stringify(first));
258
- for(let round=2;round<=3;round++){
259
+ for(let round=2;round<=5;round++){
259
260
  const again=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
260
261
  assert.equal(again.code,'qa_result_blocked',JSON.stringify(again));
261
262
  }
262
263
  const exhausted=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
263
264
  assert.equal(exhausted.code,'qa_round_invalid',JSON.stringify(exhausted));
264
- assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2,3]);
265
- assert.deepEqual(testRuns(f,'superseded').map(row=>row.blocked_cases),[['probe'],['probe']]);
265
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2,3,4,5]);
266
+ assert.deepEqual(testRuns(f,'superseded').map(row=>row.blocked_cases),[['probe'],['probe'],['probe'],['probe']]);
266
267
  });
267
268
 
268
269
  test('#13 the environment recovers: an unavailable command reaches run_done on the same approved code',POSIX,async t=>{
@@ -303,7 +304,7 @@ test('#26 a wrong QA workflow config is revised before any QA round, without con
303
304
  const f=fixture(t);
304
305
  const wrong=f.workflow('workflow-old',{commands:[{id:'probe',command:[process.execPath,'-e','process.exit(3)'],caseIds:[]}],environment:service});
305
306
  const fixed=f.workflow('workflow-new',probeQa());
306
- const waiting=done(await launch(f,{mode:'create',workflow:wrong,review:false}));
307
+ const waiting=done(await launch(f,{mode:'create',workflow:wrong,operation:'start'}));
307
308
  assert.equal(waiting.state,'awaiting_review',JSON.stringify(waiting));
308
309
  const before=f.journal();
309
310
  const drift=await launch(f,{workflow:fixed,review:false});
@@ -404,16 +405,18 @@ test('#7 decision chain: one linked supersession of a timeout decision, read by
404
405
  });
405
406
 
406
407
  // A QA call stopped as a whole (qa_execution_timeout, or the host gone) leaves no
407
- // complete and no report. Here the probe command passes, TC-001 gets no session
408
- // answer within qa.timeoutMs, and the host dies while TC-002 waits.
408
+ // complete and no report. Here the probe command passes and TC-001 gets no session
409
+ // answer within qa.timeoutMs. Q07: the session may still drive the device, so the
410
+ // host stops the call (qa_device_unverified) and never dispatches TC-002.
409
411
  async function timedOutCall(t){
410
412
  const f=fixture(t,{browser:2}),workflow=f.workflow('workflow',probeQa({environment:simulator,timeoutMs:1500}));
411
413
  const browserQa=['--browser-qa','available'];
412
414
  const aborted=await launch(f,{mode:'create',workflow,extra:browserQa,
413
415
  answers:{qa_browser:row=>row.payload.case.id==='TC-001'?'IGNORE':'KILL'}});
414
- assert.notEqual(aborted.code,0);
416
+ assert.equal(aborted.asked.filter(kind=>kind==='qa_browser').length,1);
417
+ assert.match(JSON.stringify(aborted),/qa_device_unverified/);
415
418
  const recorded=testRuns(f).map(row=>[row.phase,row.case_id]);
416
- assert.deepEqual(recorded,[['start',undefined],['case_start','TC-001'],['case_blocked','TC-001'],['case_start','TC-002']]);
419
+ assert.deepEqual(recorded,[['start',undefined],['case_start','TC-001'],['case_blocked','TC-001']]);
417
420
  assert.equal(testRuns(f,'case_blocked')[0].host_request_timeout,true);
418
421
  return {f,workflow,browserQa};
419
422
  }
@@ -445,7 +448,46 @@ test('#26c --rerun-unknown-qa supersedes a call stopped as a whole whose only no
445
448
  assert.equal(done(await launch(f,{workflow,extra:browserQa})).state,'run_done');
446
449
  });
447
450
 
448
- test('#26c a session-declared BLOCKED, a FAIL or an unattested older timeout row still refuses --rerun-unknown-qa',POSIX,async t=>{
451
+ // Q06/Q11: the call stopped as a whole after the session itself declared a case
452
+ // BLOCKED (or the host judged an evidence gap). That is a host or answer problem,
453
+ // not a product verdict: --rerun-unknown-qa supersedes it with host_blocked_cases
454
+ // and the next round does not count toward the three-round budget (Q14).
455
+ test('#26c a stopped call with a session-declared BLOCKED is superseded and rerun',POSIX,async t=>{
456
+ const {f,workflow,browserQa}=await timedOutCall(t);
457
+ const original=fs.readFileSync(f.log,'utf8');
458
+ fs.writeFileSync(f.log,original.trim().split('\n').map(line=>{const row=JSON.parse(line);
459
+ return JSON.stringify(row.event==='test_run'&&row.phase==='case_blocked'
460
+ ?{...row,host_declared_blocked:true,host_request_timeout:false,answered_verdict:'BLOCKED'}:row);}).join('\n')+'\n');
461
+ const unknown=done(await launch(f,{workflow,extra:browserQa}));
462
+ assert.equal(unknown.code,'qa_execution_unknown');
463
+ const rerun=done(await launch(f,{workflow,extra:[...browserQa,'--rerun-unknown-qa'],answers:{qa_browser:pass(f)}}));
464
+ assert.equal(rerun.state,'run_done',JSON.stringify(rerun));
465
+ const [superseded]=testRuns(f,'superseded');
466
+ assert.equal(superseded.reason,'host_request_timeout');
467
+ assert.deepEqual([superseded.timed_out_cases,superseded.host_blocked_cases,superseded.partial_pass_cases],[[],['TC-001'],[]]);
468
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2]);
469
+ });
470
+
471
+ // The approved contract, not the row, decides [需确认]: an unresolved expectation
472
+ // refuses even when the row claims a host-judged cleanup gap.
473
+ test('#26c the approved contract refuses an unresolved [需确认] case before host-fault eligibility',POSIX,async t=>{
474
+ const {f}=await timedOutCall(t);
475
+ const {inspectCmAiQaRecovery}=await import('../runtime/js/cm-ai/cm-ai-qa-log.mjs');
476
+ const original=fs.readFileSync(f.log,'utf8');
477
+ fs.writeFileSync(f.log,original.trim().split('\n').map(line=>{const row=JSON.parse(line);
478
+ return JSON.stringify(row.event==='test_run'&&row.phase==='case_blocked'
479
+ ?{...row,host_request_timeout:false,blocked_reason:'cleanup',answered_verdict:'PASS'}:row);}).join('\n')+'\n');
480
+ const start=testRuns(f,'start')[0];
481
+ const binding={specsDir:f.specsDir,feature:start.feature,packageDigest:start.package_digest,
482
+ identity:{repositoryId:start.repository_id,runId:start.run_id,taskId:start.task,attempt:1}};
483
+ const recovery=inspectCmAiQaRecovery(binding,{timedOut:true,requestTimeoutMs:1500});
484
+ assert.deepEqual([recovery.timedOutCases,recovery.hostBlockedCases],[[],['TC-001']]);
485
+ const source=path.join(f.specsDir,start.feature,'test-cases.json'),contract=JSON.parse(fs.readFileSync(source,'utf8'));
486
+ contract.cases.find(item=>item.id==='TC-001').expected=['[需确认] synthetic expectation'];fs.writeFileSync(source,JSON.stringify(contract));
487
+ assert.throws(()=>inspectCmAiQaRecovery(binding,{timedOut:true,requestTimeoutMs:1500}),{code:'qa_execution_unknown'});
488
+ });
489
+
490
+ test('#26c an undistinguished BLOCKED, a FAIL or an unattested older timeout row still refuses --rerun-unknown-qa',POSIX,async t=>{
449
491
  const {f,workflow,browserQa}=await timedOutCall(t);
450
492
  const original=fs.readFileSync(f.log,'utf8');
451
493
  const variant=edit=>original.trim().split('\n').map(line=>{const row=JSON.parse(line);
@@ -454,8 +496,11 @@ test('#26c a session-declared BLOCKED, a FAIL or an unattested older timeout row
454
496
  const start=testRuns(f,'case_start')[0].at;return {...rest,at:new Date(Date.parse(start)+seconds*1000).toISOString().replace(/\.\d{3}Z$/,'Z')};};
455
497
  const attest=['--qa-environment-failure','session gave no TC-001 answer before the deadline'];
456
498
  for(const [name,edit,code,extra] of [
457
- ['session-declared',row=>({...row,host_declared_blocked:true,host_request_timeout:false}),'qa_execution_unknown',attest],
458
499
  ['other BLOCKED',row=>({...row,host_request_timeout:false}),'qa_execution_unknown',attest],
500
+ ['unresolved expectation',row=>({...row,host_request_timeout:false,blocked_reason:'needs_confirmation'}),'qa_execution_unknown',attest],
501
+ // A browser FAIL the host downgraded for its evidence stays a product verdict.
502
+ ['downgraded FAIL',row=>({...row,host_request_timeout:false,blocked_reason:'evidence',answered_verdict:'FAIL'}),'qa_execution_unknown',attest],
503
+ ['host-judged without the session verdict',row=>({...row,host_request_timeout:false,blocked_reason:'cleanup'}),'qa_execution_unknown',attest],
459
504
  ['FAIL',row=>({...row,phase:'case_complete',result:'FAIL',host_request_timeout:undefined}),'qa_execution_unknown',attest],
460
505
  ['older row, window not elapsed',legacy(0),'qa_execution_unknown',attest],
461
506
  // An older host also wrote this row for a PASS answered near the deadline but
@@ -9,7 +9,7 @@ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
9
9
  import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
10
10
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
11
  import {createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
12
- import {writeHandoff} from '../experiments/js-orchestration/native-gate-fixture.mjs';
12
+ import {writeHandoff} from './fixtures/native-gate-fixture.mjs';
13
13
 
14
14
  const identity={repositoryId:'fixture',runId:'review-drift',taskId:'T-001',attempt:1};
15
15
  const terminal=(request,result)=>({version:1,invocationId:request.invocationId,