@aibyzero/cm-workflow 0.16.8 → 0.16.9

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 (157) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +14 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +25 -1
  8. package/docs/next-steps.md +8 -2
  9. package/docs/user-guide.md +105 -5
  10. package/package.json +2 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  12. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
  13. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
  14. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  15. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  16. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  18. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  19. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  20. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  21. package/runtime/js/cm-ai/host-check.mjs +4 -1
  22. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  23. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  24. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  26. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  27. package/runtime/js/cm-ai/host-session.mjs +1 -1
  28. package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
  29. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  30. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  31. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  32. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  33. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  34. package/runtime/js/cm-ai/review-package.mjs +10 -1
  35. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  36. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  37. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  38. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  39. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  40. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  41. package/runtime/js/cm-fix/execution.mjs +176 -48
  42. package/runtime/js/cm-fix/host.mjs +2 -1
  43. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  44. package/runtime/js/cm-fix/progress.mjs +13 -3
  45. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  46. package/runtime/js/cm-fix/repair.mjs +11 -3
  47. package/runtime/js/cm-fix/test-author.mjs +10 -3
  48. package/runtime/js/cm-idea/session.mjs +67 -4
  49. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  50. package/runtime/js/cm-prd/session.mjs +43 -0
  51. package/runtime/js/cm-refactor/records.mjs +98 -8
  52. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  53. package/runtime/js/cm-test/host.mjs +10 -3
  54. package/runtime/js/cm-test/session.mjs +45 -6
  55. package/runtime/js/notify-safe-read.mjs +49 -0
  56. package/runtime/js/notify-send.mjs +312 -0
  57. package/runtime/js/notify.mjs +137 -33
  58. package/runtime/js/policy-binding-compat.mjs +54 -0
  59. package/scripts/ci-test-shards.mjs +67 -0
  60. package/scripts/ci-test-shards.test.mjs +64 -0
  61. package/scripts/ci-test-weights.json +222 -0
  62. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  63. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  64. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  65. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  66. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  67. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  68. package/scripts/cm-ai-batch-drive.mjs +55 -10
  69. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  70. package/scripts/cm-ai-batch-host.mjs +132 -13
  71. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  72. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  73. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  74. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  75. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  76. package/scripts/cm-ai-batch-run.mjs +184 -22
  77. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  78. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  79. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  80. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  81. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  82. package/scripts/cm-ai-drive.mjs +64 -22
  83. package/scripts/cm-ai-drive.test.mjs +29 -2
  84. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  85. package/scripts/cm-ai-host-fixture.mjs +268 -0
  86. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  87. package/scripts/cm-ai-host.mjs +27 -15
  88. package/scripts/cm-ai-host.test.mjs +17 -759
  89. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  90. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  91. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  92. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  93. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  94. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +56 -10
  95. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  96. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  97. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  98. package/scripts/cm-ai-run.mjs +15 -6
  99. package/scripts/cm-ai-supersede.test.mjs +486 -41
  100. package/scripts/cm-check-drive-files.mjs +8 -0
  101. package/scripts/cm-check-drive.test.mjs +2 -5
  102. package/scripts/cm-check-runtime.sh +4 -2
  103. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  104. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  105. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  106. package/scripts/cm-claude-worker.test.mjs +18 -2
  107. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  108. package/scripts/cm-fix-abandon.test.mjs +163 -10
  109. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  110. package/scripts/cm-fix-drive.mjs +25 -7
  111. package/scripts/cm-fix-host.mjs +8 -7
  112. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  113. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  114. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  115. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  116. package/scripts/cm-host-documentation.test.mjs +49 -0
  117. package/scripts/cm-host-qa-executor.test.mjs +22 -10
  118. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  119. package/scripts/cm-idea-drive.mjs +49 -11
  120. package/scripts/cm-idea-drive.test.mjs +66 -0
  121. package/scripts/cm-idea-host.mjs +106 -16
  122. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  123. package/scripts/cm-init-drive.mjs +41 -7
  124. package/scripts/cm-init-host.mjs +61 -12
  125. package/scripts/cm-log-event.mjs +21 -10
  126. package/scripts/cm-notify-command.test.mjs +900 -0
  127. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  128. package/scripts/cm-notify.mjs +469 -0
  129. package/scripts/cm-notify.test.mjs +221 -4
  130. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  131. package/scripts/cm-prd-drive.mjs +18 -5
  132. package/scripts/cm-prd-drive.test.mjs +15 -0
  133. package/scripts/cm-prd-host.mjs +37 -4
  134. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  135. package/scripts/cm-prd-review-gate.mjs +56 -0
  136. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  137. package/scripts/cm-refactor-drive.mjs +52 -8
  138. package/scripts/cm-refactor-drive.test.mjs +44 -0
  139. package/scripts/cm-refactor-host.test.mjs +10 -6
  140. package/scripts/cm-release-smoke.sh +2 -0
  141. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  142. package/scripts/cm-test-drive.mjs +21 -5
  143. package/scripts/fixtures/claude-review-process.mjs +1 -1
  144. package/scripts/policy-binding-compat.test.mjs +99 -0
  145. package/scripts/scan-public-safety.py +4 -0
  146. package/scripts/validate-public-repo.py +4 -0
  147. package/skills/cm-ai/references/js-host-qa-recovery.md +27 -1
  148. package/skills/cm-ai/references/js-host-recovery.md +120 -8
  149. package/skills/cm-ai/references/js-host.md +14 -7
  150. package/skills/cm-check/SKILL.md +3 -3
  151. package/skills/cm-fix/references/js-host.md +44 -5
  152. package/skills/cm-idea/references/js-host.md +27 -2
  153. package/skills/cm-init/references/js-host.md +16 -3
  154. package/skills/cm-notify/SKILL.md +34 -0
  155. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  156. package/skills/cm-refactor/references/js-host.md +17 -0
  157. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,57 @@
1
+ // Light runtime modules are copied on their own into partial runtimes (scripts/cm-check-drive.test.mjs
2
+ // copies a hand-picked list). The authority here is Node's real module resolver: copy ONLY the allowed
3
+ // files into a fresh temp dir and import the module in a child process. Every import syntax is covered
4
+ // (import{...}from, export ... from, multi-line, top-level dynamic import), with no scanner to fool.
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {spawnSync} from 'node:child_process';
11
+ import {fileURLToPath,pathToFileURL} from 'node:url';
12
+ import {CHECK_DRIVE_COPIED_FILES} from './cm-check-drive-files.mjs';
13
+
14
+ const root=fileURLToPath(new URL('..',import.meta.url));
15
+ const GUIDANCE='runtime/js/cm-ai/operator-guidance.mjs',LIMITS='runtime/js/cm-ai/review-dispatch-limits.mjs';
16
+
17
+ // Copy exactly `files` (optionally appending `append` to `entry`) and import `entry` from the copy.
18
+ function importFromCopy(t,entry,files,append=''){
19
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-light-module-')));
20
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
21
+ for(const file of files){
22
+ fs.mkdirSync(path.dirname(path.join(dir,file)),{recursive:true});fs.copyFileSync(path.join(root,file),path.join(dir,file));
23
+ }
24
+ if(append)fs.appendFileSync(path.join(dir,entry),append);
25
+ return spawnSync(process.execPath,['--input-type=module','-e',`await import(${JSON.stringify(pathToFileURL(path.join(dir,entry)).href)});`],
26
+ {encoding:'utf8',cwd:dir});
27
+ }
28
+
29
+ test('review-dispatch-limits.mjs imports with only itself copied',t=>{
30
+ const run=importFromCopy(t,LIMITS,[LIMITS]);assert.equal(run.status,0,run.stderr);
31
+ });
32
+ test('operator-guidance.mjs imports with only itself and review-dispatch-limits.mjs copied',t=>{
33
+ const run=importFromCopy(t,GUIDANCE,[GUIDANCE,LIMITS]);assert.equal(run.status,0,run.stderr);
34
+ });
35
+ test('operator-guidance.mjs imports from exactly the partial runtime cm-check-drive.test.mjs copies',t=>{
36
+ const run=importFromCopy(t,GUIDANCE,CHECK_DRIVE_COPIED_FILES);assert.equal(run.status,0,run.stderr);
37
+ });
38
+
39
+ // Negative controls: each added import reaches a file the partial copy does not have, so the real
40
+ // resolver must fail. They run against the copy, never the repository file.
41
+ const REACH=[
42
+ ['compact import{...}from with an alias',"\nimport{readRunnerHistory as probe}from './durable-runner-state.mjs';\n"],
43
+ ['multi-line import',"\nimport {\n readRunnerHistory,\n runnerStatus,\n} from './durable-runner-state.mjs';\n"],
44
+ ['import sharing a line with other code',"\nconst unrelated=1;import x from './task-runner.mjs';\n"],
45
+ ['export ... from',"\nexport {readRunnerHistory} from './durable-runner-state.mjs';\n"],
46
+ ['top-level dynamic import',"\nawait import('./durable-runner-state.mjs');\n"],
47
+ ];
48
+ for(const [name,append] of REACH)
49
+ test(`guard fails when operator-guidance.mjs gains a ${name}`,t=>{
50
+ const run=importFromCopy(t,GUIDANCE,CHECK_DRIVE_COPIED_FILES,append);
51
+ assert.notEqual(run.status,0,'the import must not resolve in the partial runtime');
52
+ assert.match(run.stderr,/ERR_MODULE_NOT_FOUND/);
53
+ });
54
+ test('guard fails when operator-guidance.mjs gains an import of a file only the wider cm-check copy has',t=>{
55
+ const run=importFromCopy(t,GUIDANCE,[GUIDANCE,LIMITS],"\nimport x from './effect-contract.mjs'\n");
56
+ assert.notEqual(run.status,0);assert.match(run.stderr,/ERR_MODULE_NOT_FOUND/);
57
+ });
@@ -82,13 +82,38 @@ test('batch guidance matches its narrower control surface and never advertises s
82
82
  assert.equal(wrapped.pendingAction,blocked.pendingAction);assert.equal(wrapped.guidance.recoveryOperation,'advance');
83
83
  assert.match(guidanceText(wrapped),/原批次入口/);assert.doesNotMatch(guidanceText(wrapped),/--mode/);
84
84
  assert.match(guidanceText(batchMemberResult(member('blocked','completion_checks_changed','complete'))),/成员宿主继续完成复核/);
85
- for(const [state,code,action] of [['unknown','execution_error','abandon_effect'],
86
- ['unknown','execution_error','abandon_review'],['blocked','bootstrap_review_mismatch','bootstrap_review_recover']]){
87
- const output=batchMemberResult(member(state,code,action));
88
- assert.equal(output.guidance.recoveryOperation,null);assert.doesNotMatch(guidanceText(output),/--allow-/);
89
- assert.match(guidanceText(output),/批次入口不支持/);
85
+ // Q24: the batch entry forwards these to the stopped member, so guidance names the batch grant and operation.
86
+ for(const [state,code,action,flag] of [['unknown','execution_error','abandon_effect','--allow-abandon-effect'],
87
+ ['unknown','execution_error','abandon_review','--allow-abandon-review'],['blocked','bootstrap_review_mismatch','bootstrap_review_recover','--allow-bootstrap-review-recovery'],
88
+ ['blocked','develop_answer_missing','develop_redo','--allow-develop-redo']]){
89
+ const output=batchMemberResult(member(state,code,action),{taskKey:'1.work/T-002'});
90
+ assert.equal(output.guidance.recoveryOperation,action);assert.equal(output.guidance.authorizationGranted,false);
91
+ assert(guidanceText(output).includes(`${flag} 1.work/T-002`),guidanceText(output));
92
+ assert.match(guidanceText(output),new RegExp(`批次操作 ${action}`));assert.doesNotMatch(guidanceText(output),/--mode/);
90
93
  }
91
94
  const rebound=batchMemberResult(member('blocked','spec_drift','spec_rebind'));
92
95
  assert.equal(rebound.pendingAction,'none');assert.match(rebound.guidance.nextStep,/不能换绑/);
93
96
  assert.equal(rebound.guidance.recoveryOperation,null);
94
97
  });
98
+
99
+ test('V5 review redispatch limit and unprovable review ends name the supersede exit, never a retry',()=>{
100
+ const identity={repositoryId:'r',runId:'run',taskId:'T-001',attempt:1};
101
+ const limit=operatorGuidance({workflow:'cm-ai',identity,state:'blocked',code:'review_redispatch_limit',pendingAction:'none'});
102
+ assert.equal(limit.recoveryOperation,null);assert.match(limit.nextStep,/supersede-reviewed-evidence/);assert.match(limit.summary,/2 次/);
103
+ for(const refusal of ['review_process_unverified','review_observation_invalid','review_boundary_unverified','review_abandon_budget_exhausted']){
104
+ const g=operatorGuidance({workflow:'cm-ai',identity,state:'unknown',code:'transport_incomplete',pendingAction:'reconcile',reviewAbandonRefusal:refusal});
105
+ assert.equal(g.recoveryOperation,null);assert.match(g.nextStep,/supersede-reviewed-evidence/);assert.equal(g.authorizationGranted,false);
106
+ }
107
+ });
108
+
109
+ test('Q06/Q07/Q15 a stopped QA call and a blocked documentation check name their operator exits',()=>{
110
+ const unknown=explain('fixture_completed','qa_execution_unknown','reconcile');
111
+ assert.match(unknown.nextStep,/--rerun-unknown-qa/);assert.match(unknown.nextStep,/设备已空闲/);assert.equal(unknown.authorizationGranted,false);
112
+ const docs=explain('fixture_completed','documentation_sync_blocked','none');
113
+ assert.match(docs.nextStep,/finish/);assert.equal(docs.recoveryOperation,null);
114
+ });
115
+
116
+ test('V5 the second no-result redispatch asks for the operator stop confirmation, never a plain advance',()=>{
117
+ const g=explain('blocked','review_transport_timeout','abandon_review',{reviewRedispatchStopRequired:true});
118
+ assert.equal(g.recoveryOperation,'abandon_review');assert.match(g.nextStep,/确认原审查进程/);assert.equal(g.authorizationGranted,false);
119
+ });
@@ -180,15 +180,19 @@ test('a stranded T-006 journal replays as blocked/protected_scope and its record
180
180
  assert.deepEqual(fs.readFileSync(f.statePath),legacyBytes);
181
181
  });
182
182
 
183
- test('the same unknown developer shape without a protected scope is still unknown',async t=>{
183
+ test('the same unknown developer shape without a protected scope is not protected_scope (pinned root: develop_dispatch_failed)',async t=>{
184
184
  const f=await runnerFixture(t,['code.js']);
185
185
  f.setDeveloper(()=>{throw new Error('adapter failure');});
186
186
  const result=await f.make().executeEffect(f.develop());
187
- assert.equal(result.state,'unknown');assert.equal(result.code,'execution_error');assert.equal(f.developerCalls(),1);
187
+ assert.equal(result.state,'blocked');assert.equal(result.code,'develop_dispatch_failed');assert.equal(f.developerCalls(),1);
188
188
  // The genuine pre-gate shape has the same call fields the T-006 rewrite uses.
189
189
  assert.deepEqual(Object.keys(result.calls[0]),['invocationId','contextId','provider','requestedModel','effectiveModel',
190
190
  'channel','started','terminal','requestDigest','resultDigest']);
191
191
  assert.equal(result.calls[0].terminal,'unknown');assert.equal(result.calls[0].resultDigest,null);
192
192
  const resumed=f.reopen();
193
- assert.equal(resumed.status().state,'unknown');assert.equal(resumed.status().code,'execution_error');
193
+ // The journal keeps unknown/execution_error; with the code root still at the
194
+ // round start, status offers the plain pre-dispatch redo (answer gaps, P1-3).
195
+ const history=readRunnerHistory(f.records(),f.records()[0].payload.config,3);
196
+ assert.deepEqual([history.state.state,history.state.code],['unknown','execution_error']);
197
+ assert.deepEqual([resumed.status().state,resumed.status().code],['blocked','develop_dispatch_failed']);
194
198
  });
@@ -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
+ });
@@ -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});
@@ -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,7 +100,7 @@ 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=[]}={})=>{
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);
@@ -105,7 +108,7 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0}={}){
105
108
  owner=createQaFixOwnerHost({parent,hostContextId:live,parentHostContextId:execution.configuration.hostContextId,
106
109
  reopenParent:()=>openControlRun(definition,'resume',execution),allowStart,
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
  }
@@ -247,7 +250,9 @@ test('QA-fix child abandons a lost local diagnosis only with its dedicated CLI f
247
250
  const request={...f.bound('fix_action'),fixOperation:'abandon_step',reason:'Child diagnosis response lost'};
248
251
  const before=fs.readFileSync(f.statePath);
249
252
  const denied=await cli(f,A,request);
250
- assert.match(denied.stderr,/fix_abandon_unavailable/);
253
+ assert.equal(denied.code,0,denied.stderr);
254
+ assert.deepEqual([denied.result?.outcome,denied.result?.code],['rejected','qa_fix_action_authorization_required'],JSON.stringify(denied.result));
255
+ assert.match(denied.result.reason,/--allow-qa-fix-abandon(/);
251
256
  assert.deepEqual(fs.readFileSync(f.statePath),before);
252
257
  const allowed=await cli(f,A,request,{flags:['--allow-qa-fix-abandon']});
253
258
  assert.equal(allowed.code,0,allowed.stderr);
@@ -266,11 +271,15 @@ test('#15 a QA-fix child cause review without a result is abandoned once through
266
271
  assert.equal(reviewed.fixStage,'unknown');assert.equal(reviewed.actionResult.reviewAbandonable,'cause_review');
267
272
  const request={...f.bound('fix_action'),fixOperation:'abandon_review',reason:'Child cause reviewer confirmed stopped'};
268
273
  const before=fs.readFileSync(f.statePath);
269
- await assert.rejects(owner.handle(request),{code:'fix_review_abandon_authorization_required'});
274
+ const refused=await owner.handle(request);
275
+ assert.deepEqual([refused.outcome,refused.code],['rejected','qa_fix_action_authorization_required']);
276
+ assert.match(refused.reason,/--allow-qa-fix-abandon-review/);
277
+ assert.equal((await owner.handle(f.request('status'))).state,'fixture_completed');
270
278
  assert.deepEqual(fs.readFileSync(f.statePath),before);
271
279
  f.close();
272
280
  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);
281
+ assert.equal(local.result?.code,'qa_fix_action_authorization_required',JSON.stringify(local.result));
282
+ assert.match(local.result.reason,/--allow-qa-fix-abandon-review/);assert.deepEqual(fs.readFileSync(f.statePath),before);
274
283
  const allowed=await cli(f,A,request,{flags:['--allow-qa-fix-abandon-review']});
275
284
  assert.equal(allowed.code,0,allowed.stderr);assert.equal(allowed.result?.fixStage,'cause_review_required');
276
285
  assert(f.records().some(row=>row.id==='fix-cause-abandoned'));
@@ -278,3 +287,61 @@ test('#15 a QA-fix child cause review without a result is abandoned once through
278
287
  assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');
279
288
  assert.equal(f.records().find(row=>row.id==='fix-cause-retry-started').payload.providerThreadId,'synthetic-child-review');
280
289
  });
290
+
291
+ // Q23/F08: a rejected child cause review reaches rediagnosis_required. Before this
292
+ // the parent fix_action refused rediagnose, so the only exit was closing the parent
293
+ // and reopening the child with cm-fix-host. Now the parent host forwards it to the
294
+ // same cm-fix dispatcher under --allow-qa-fix-rediagnosis, and the child continues.
295
+ test('Q23 a QA-fix child rediagnoses through the parent host fix_action, then its round-2 cause review proceeds',async t=>{
296
+ const f=await fixture(t,{rejectedCauseReviews:1});
297
+ let owner=await f.open(A);
298
+ assert.equal((await owner.handle(f.bound('fix_advance'))).fixStage,'cause_review_required');
299
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'rediagnosis_required');
300
+ f.close();
301
+ const request={...f.bound('fix_action'),fixOperation:'rediagnose',reason:'根因审查要求补充跨层证据'};
302
+ const before=fs.readFileSync(f.statePath);
303
+ // Without the parent flag: an explicit refusal naming it, nothing written, parent reopened.
304
+ const denied=await cli(f,A,request);
305
+ assert.equal(denied.code,0,denied.stderr);
306
+ assert.deepEqual([denied.result?.outcome,denied.result?.code],['rejected','qa_fix_action_authorization_required'],JSON.stringify(denied.result));
307
+ assert.match(denied.result.reason,/--allow-qa-fix-rediagnosis/);assert.equal(denied.result.guidance.authorizationGranted,false);
308
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
309
+ // A missing reason is still the original cm-fix refusal, reported with its code.
310
+ const reasonless=await cli(f,A,{...request,reason:'第一行\n第二行'},{flags:['--allow-qa-fix-rediagnosis']});
311
+ assert.deepEqual([reasonless.result?.outcome,reasonless.result?.code],['rejected','fix_rediagnosis_reason_invalid'],JSON.stringify(reasonless.result));
312
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
313
+ const revised={...diagnosis,rootCause:'Wrong constant; revised after review',crossLayer:false};
314
+ const allowed=await cli(f,A,request,{flags:['--allow-qa-fix-rediagnosis'],diagnosed:revised});
315
+ assert.equal(allowed.code,0,allowed.stderr);
316
+ assert.equal(allowed.result?.fixStage,'cause_review_required',JSON.stringify(allowed.result));
317
+ assert.deepEqual(f.records().slice(0,JSON.parse(before).records.length),JSON.parse(before).records,'journal is append-only');
318
+ assert(f.records().some(row=>row.id==='fix-rediagnosis-intent'));
319
+ assert.equal(f.records().find(row=>row.id==='fix-rediagnosis-result').payload.rootCause,revised.rootCause);
320
+ // The batch continues: the second, independent cause review approves and publishes cause-r2.
321
+ owner=await f.open(A);
322
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');
323
+ assert(fs.readdirSync(path.join(path.dirname(f.childDir),'..')).some(name=>/-cause-r2\.md$/.test(name)));
324
+ });
325
+
326
+ // Q23/F25: recover_final_review and rerun_blocked_step reach the same dispatcher;
327
+ // a stage that does not qualify is the original cm-fix refusal, not host_request_failed.
328
+ test('Q23 recover_final_review and rerun_blocked_step through fix_action report the original cm-fix refusal codes',async t=>{
329
+ const f=await fixture(t);
330
+ let owner=await f.open(A,{extraPermissions:['--allow-final-review-recovery','--allow-rerun-blocked-step']});
331
+ assert.equal((await owner.handle(f.bound('fix_advance'))).fixStage,'cause_review_required');
332
+ const before=fs.readFileSync(f.statePath);
333
+ const recovery=await owner.handle({...f.bound('fix_action'),fixOperation:'recover_final_review',invocationId:'final-review-invocation',
334
+ reviewPackageDigest:'a'.repeat(64),previousInvocationStopped:true,reason:'旧审查进程已退出'});
335
+ assert.deepEqual([recovery.outcome,recovery.code],['rejected','fix_review_recovery_unavailable'],JSON.stringify(recovery));
336
+ const rerun=await owner.handle({...f.bound('fix_action'),fixOperation:'rerun_blocked_step',reason:'环境已修好'});
337
+ assert.deepEqual([rerun.outcome,rerun.code],['rejected','fix_blocked_rerun_unavailable'],JSON.stringify(rerun));
338
+ assert.equal((await owner.handle(f.request('status'))).state,'fixture_completed');
339
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
340
+ f.close();owner=await f.open(A);
341
+ const missing=await owner.handle({...f.bound('fix_action'),fixOperation:'recover_final_review',invocationId:'final-review-invocation',
342
+ reviewPackageDigest:'a'.repeat(64),previousInvocationStopped:true,reason:'旧审查进程已退出'});
343
+ assert.deepEqual([missing.code,missing.fixOperation],['qa_fix_action_authorization_required','recover_final_review']);
344
+ assert.match(missing.reason,/--allow-qa-fix-final-review-recovery/);
345
+ const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
346
+ assert.equal(classifyDriveResult('cm-ai',{result:missing}),'stuck');
347
+ });
@@ -250,19 +250,21 @@ test('#13 a host-declared BLOCKED simulator case re-runs on unchanged code with
250
250
  assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['BLOCKED','PASS']);
251
251
  });
252
252
 
253
- test('#13 an unavailable QA command (killed, no exit code) re-runs; the round budget still caps at three',POSIX,async t=>{
253
+ // Q14: rounds ended by a host or environment gap (here a killed command) do not
254
+ // count toward the three-round budget, but at most two are given back per run.
255
+ test('#13 an unavailable QA command (killed, no exit code) re-runs; host-caused rounds give back at most two',POSIX,async t=>{
254
256
  const f=fixture(t),workflow=f.workflow('workflow',probeQa());
255
257
  f.environment('killed');
256
258
  const first=done(await launch(f,{mode:'create',workflow}));
257
259
  assert.equal(first.code,'qa_result_blocked',JSON.stringify(first));
258
- for(let round=2;round<=3;round++){
260
+ for(let round=2;round<=5;round++){
259
261
  const again=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
260
262
  assert.equal(again.code,'qa_result_blocked',JSON.stringify(again));
261
263
  }
262
264
  const exhausted=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
263
265
  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']]);
266
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2,3,4,5]);
267
+ assert.deepEqual(testRuns(f,'superseded').map(row=>row.blocked_cases),[['probe'],['probe'],['probe'],['probe']]);
266
268
  });
267
269
 
268
270
  test('#13 the environment recovers: an unavailable command reaches run_done on the same approved code',POSIX,async t=>{
@@ -404,16 +406,18 @@ test('#7 decision chain: one linked supersession of a timeout decision, read by
404
406
  });
405
407
 
406
408
  // 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.
409
+ // complete and no report. Here the probe command passes and TC-001 gets no session
410
+ // answer within qa.timeoutMs. Q07: the session may still drive the device, so the
411
+ // host stops the call (qa_device_unverified) and never dispatches TC-002.
409
412
  async function timedOutCall(t){
410
413
  const f=fixture(t,{browser:2}),workflow=f.workflow('workflow',probeQa({environment:simulator,timeoutMs:1500}));
411
414
  const browserQa=['--browser-qa','available'];
412
415
  const aborted=await launch(f,{mode:'create',workflow,extra:browserQa,
413
416
  answers:{qa_browser:row=>row.payload.case.id==='TC-001'?'IGNORE':'KILL'}});
414
- assert.notEqual(aborted.code,0);
417
+ assert.equal(aborted.asked.filter(kind=>kind==='qa_browser').length,1);
418
+ assert.match(JSON.stringify(aborted),/qa_device_unverified/);
415
419
  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']]);
420
+ assert.deepEqual(recorded,[['start',undefined],['case_start','TC-001'],['case_blocked','TC-001']]);
417
421
  assert.equal(testRuns(f,'case_blocked')[0].host_request_timeout,true);
418
422
  return {f,workflow,browserQa};
419
423
  }
@@ -445,7 +449,46 @@ test('#26c --rerun-unknown-qa supersedes a call stopped as a whole whose only no
445
449
  assert.equal(done(await launch(f,{workflow,extra:browserQa})).state,'run_done');
446
450
  });
447
451
 
448
- test('#26c a session-declared BLOCKED, a FAIL or an unattested older timeout row still refuses --rerun-unknown-qa',POSIX,async t=>{
452
+ // Q06/Q11: the call stopped as a whole after the session itself declared a case
453
+ // BLOCKED (or the host judged an evidence gap). That is a host or answer problem,
454
+ // not a product verdict: --rerun-unknown-qa supersedes it with host_blocked_cases
455
+ // and the next round does not count toward the three-round budget (Q14).
456
+ test('#26c a stopped call with a session-declared BLOCKED is superseded and rerun',POSIX,async t=>{
457
+ const {f,workflow,browserQa}=await timedOutCall(t);
458
+ const original=fs.readFileSync(f.log,'utf8');
459
+ fs.writeFileSync(f.log,original.trim().split('\n').map(line=>{const row=JSON.parse(line);
460
+ return JSON.stringify(row.event==='test_run'&&row.phase==='case_blocked'
461
+ ?{...row,host_declared_blocked:true,host_request_timeout:false,answered_verdict:'BLOCKED'}:row);}).join('\n')+'\n');
462
+ const unknown=done(await launch(f,{workflow,extra:browserQa}));
463
+ assert.equal(unknown.code,'qa_execution_unknown');
464
+ const rerun=done(await launch(f,{workflow,extra:[...browserQa,'--rerun-unknown-qa'],answers:{qa_browser:pass(f)}}));
465
+ assert.equal(rerun.state,'run_done',JSON.stringify(rerun));
466
+ const [superseded]=testRuns(f,'superseded');
467
+ assert.equal(superseded.reason,'host_request_timeout');
468
+ assert.deepEqual([superseded.timed_out_cases,superseded.host_blocked_cases,superseded.partial_pass_cases],[[],['TC-001'],[]]);
469
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2]);
470
+ });
471
+
472
+ // The approved contract, not the row, decides [需确认]: an unresolved expectation
473
+ // refuses even when the row claims a host-judged cleanup gap.
474
+ test('#26c the approved contract refuses an unresolved [需确认] case before host-fault eligibility',POSIX,async t=>{
475
+ const {f}=await timedOutCall(t);
476
+ const {inspectCmAiQaRecovery}=await import('../runtime/js/cm-ai/cm-ai-qa-log.mjs');
477
+ const original=fs.readFileSync(f.log,'utf8');
478
+ fs.writeFileSync(f.log,original.trim().split('\n').map(line=>{const row=JSON.parse(line);
479
+ return JSON.stringify(row.event==='test_run'&&row.phase==='case_blocked'
480
+ ?{...row,host_request_timeout:false,blocked_reason:'cleanup',answered_verdict:'PASS'}:row);}).join('\n')+'\n');
481
+ const start=testRuns(f,'start')[0];
482
+ const binding={specsDir:f.specsDir,feature:start.feature,packageDigest:start.package_digest,
483
+ identity:{repositoryId:start.repository_id,runId:start.run_id,taskId:start.task,attempt:1}};
484
+ const recovery=inspectCmAiQaRecovery(binding,{timedOut:true,requestTimeoutMs:1500});
485
+ assert.deepEqual([recovery.timedOutCases,recovery.hostBlockedCases],[[],['TC-001']]);
486
+ const source=path.join(f.specsDir,start.feature,'test-cases.json'),contract=JSON.parse(fs.readFileSync(source,'utf8'));
487
+ contract.cases.find(item=>item.id==='TC-001').expected=['[需确认] synthetic expectation'];fs.writeFileSync(source,JSON.stringify(contract));
488
+ assert.throws(()=>inspectCmAiQaRecovery(binding,{timedOut:true,requestTimeoutMs:1500}),{code:'qa_execution_unknown'});
489
+ });
490
+
491
+ test('#26c an undistinguished BLOCKED, a FAIL or an unattested older timeout row still refuses --rerun-unknown-qa',POSIX,async t=>{
449
492
  const {f,workflow,browserQa}=await timedOutCall(t);
450
493
  const original=fs.readFileSync(f.log,'utf8');
451
494
  const variant=edit=>original.trim().split('\n').map(line=>{const row=JSON.parse(line);
@@ -454,8 +497,11 @@ test('#26c a session-declared BLOCKED, a FAIL or an unattested older timeout row
454
497
  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
498
  const attest=['--qa-environment-failure','session gave no TC-001 answer before the deadline'];
456
499
  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
500
  ['other BLOCKED',row=>({...row,host_request_timeout:false}),'qa_execution_unknown',attest],
501
+ ['unresolved expectation',row=>({...row,host_request_timeout:false,blocked_reason:'needs_confirmation'}),'qa_execution_unknown',attest],
502
+ // A browser FAIL the host downgraded for its evidence stays a product verdict.
503
+ ['downgraded FAIL',row=>({...row,host_request_timeout:false,blocked_reason:'evidence',answered_verdict:'FAIL'}),'qa_execution_unknown',attest],
504
+ ['host-judged without the session verdict',row=>({...row,host_request_timeout:false,blocked_reason:'cleanup'}),'qa_execution_unknown',attest],
459
505
  ['FAIL',row=>({...row,phase:'case_complete',result:'FAIL',host_request_timeout:undefined}),'qa_execution_unknown',attest],
460
506
  ['older row, window not elapsed',legacy(0),'qa_execution_unknown',attest],
461
507
  // An older host also wrote this row for a PASS answered near the deadline but