@aibyzero/cm-workflow 0.16.7 → 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 (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. 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
+ });
@@ -5,6 +5,7 @@ import assert from 'node:assert/strict';
5
5
  import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
+ import {fileURLToPath,pathToFileURL} from 'node:url';
8
9
  import {buildManifest} from './cm-spec-manifest.mjs';
9
10
  import {openControlRun} from './cm-ai-run.mjs';
10
11
  import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
@@ -48,7 +49,7 @@ function project(){
48
49
  const state={browserUp:false,documentation:0,reviews:new Map()};
49
50
  const logHome=path.join(specsDir,'.reviews','host-log-mirror');
50
51
  const environment={kind:'web',carrier:'browser',target:'fixture',scope:'local'};
51
- const execution=(feature,{write,retrospective=noLesson,verdict=()=>'approved',decision=null})=>({
52
+ const execution=(feature,{write,retrospective=noLesson,verdict=()=>'approved',decision=null,browser=null,createExecutor=createHostQaExecutor})=>({
52
53
  configuration:{kind:'synthetic-host-v1',hostContextId:'control',workflow:{qa:{commands:[],environment},documentationPaths:[],applicableAgentFiles:[]}},
53
54
  timeoutMs:5000,excludedContexts:['control'],
54
55
  developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{
@@ -75,12 +76,12 @@ function project(){
75
76
  status:'completed',reason:'Documentation checked',at:'2026-09-28T00:00:00Z'};}},
76
77
  qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,identity:binding.identity,
77
78
  packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T00:00:00Z',...decision})},
78
- qaExecutor:createHostQaExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
79
+ qaExecutor:createExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
79
80
  commands:[{id:'unit',command:[process.execPath,'--check','a.mjs'],caseIds:[]}],environment,timeoutMs:60000,logHome,
80
- browser:async browserRequest=>{
81
+ browser:browser??(async browserRequest=>{
81
82
  if(!state.browserUp)return {verdict:'BLOCKED',evidence:[],environment:browserRequest.environment,cleanup:'failed'};
82
83
  const shot=path.join(specsDir,'.reviews','tc-001.txt');fs.writeFileSync(shot,'observed');
83
- return {verdict:'PASS',evidence:[shot],environment:browserRequest.environment,cleanup:'not_needed'};}})});
84
+ return {verdict:'PASS',evidence:[shot],environment:browserRequest.environment,cleanup:'not_needed'};})})});
84
85
  const definition=(feature,taskId,scope)=>({version:1,specsDir,codeProject,feature,
85
86
  identity:{repositoryId:'gate-fixture',runId:`run-${taskId}`,taskId,attempt:1},scope,requirements:['requirements.md']});
86
87
  const advance=async(def,exec,mode,options)=>{
@@ -137,6 +138,72 @@ test('#17 an earlier feature whose QA is BLOCKED keeps the project from run_done
137
138
  assert.equal(status(p).state,'run_done');
138
139
  });
139
140
 
141
+ // The executor as released before dropped-task cases were left out: the current
142
+ // module with that one rule neutralized, imported from a temporary copy.
143
+ async function releasedQaExecutor(){
144
+ const source=fileURLToPath(new URL('../runtime/js/cm-ai/host-qa-executor.mjs',import.meta.url));
145
+ const rule='const dropped=new Set(context.dropped);',text=fs.readFileSync(source,'utf8');
146
+ assert.equal(text.split(rule).length,2,'the dropped-task rule is where this fixture expects it');
147
+ const base=pathToFileURL(path.dirname(source)+path.sep).href;
148
+ const released=text.replace(rule,'const dropped=new Set();')
149
+ .replace(/'\.\.\/\.\.\/\.\.\//g,`'${new URL('../../../',base).href}`).replace(/from '\.\//g,`from '${base}`);
150
+ const file=path.join(fs.mkdtempSync(path.join(isolated,'released-')),'host-qa-executor.mjs');fs.writeFileSync(file,released);
151
+ return (await import(pathToFileURL(file).href)).createHostQaExecutor;
152
+ }
153
+
154
+ // 2026-10-08 aihot: 5.author-column's feature-completion QA (run author-column-T-010) asked the
155
+ // session about cases bound only to [DROPPED] tasks; they stayed BLOCKED and the project gate then
156
+ // held api-native-reading-T-008's finish. Recovery: --rerun-blocked-qa on the original run, then resume.
157
+ test('#17 an earlier BLOCKED round over dropped-task cases is recovered on its original run; the later run then finishes',async()=>{
158
+ const p=project();
159
+ const feature=path.join(p.specsDir,'1.work'),log=path.join(p.specsDir,'运行日志.jsonl');
160
+ const rows=()=>fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
161
+ const contract=JSON.parse(fs.readFileSync(path.join(feature,'test-cases.json')));
162
+ // TC-001 is the live task's case; TC-002 (non-blocking browser) and TC-003 (blocking logic) are bound only to dropped T-001.
163
+ contract.cases.push({...contract.cases[0],id:'TC-002',blocking:false,taskIds:['T-001']},
164
+ {...contract.cases[0],id:'TC-003',kind:'logic',taskIds:['T-001']});
165
+ fs.writeFileSync(path.join(feature,'test-cases.json'),JSON.stringify(contract));
166
+ fs.writeFileSync(path.join(feature,'tasks.md'),'- [ ] ~~T-001: column work~~ `[DROPPED v2: 数据源未定,暂缓]`\n- [ ] T-002: fixture\n');
167
+ p.reapprove();
168
+ const asked=[];
169
+ const firstExecution=createExecutor=>p.execution('1.work',{createExecutor,
170
+ write:()=>fs.writeFileSync(path.join(p.codeProject,'a.mjs'),'export const a=1;\n'),
171
+ browser:async request=>{
172
+ asked.push(request.case.id);
173
+ // The feature is hidden: the session can only answer BLOCKED for the dropped task's case.
174
+ if(request.case.id!=='TC-001')return {verdict:'BLOCKED',evidence:[],environment:request.environment,cleanup:'not_needed'};
175
+ const shot=path.join(p.specsDir,'.reviews',`${request.case.id}-${asked.length}.txt`);fs.writeFileSync(shot,'observed');
176
+ return {verdict:'PASS',evidence:[shot],environment:request.environment,cleanup:'not_needed'};}});
177
+ const blocked=await p.advance(p.first,firstExecution(await releasedQaExecutor()),'create');
178
+ assert.equal(blocked.code,'qa_result_blocked',JSON.stringify(blocked));assert.deepEqual(asked,['TC-001','TC-002']);
179
+ const oldComplete=rows().find(row=>row.phase==='complete'&&row.run_id==='run-T-002');
180
+ assert.deepEqual([oldComplete.result,oldComplete.case_count,oldComplete.passed,oldComplete.blocked],['BLOCKED',4,2,2]);
181
+ // The recorded round is not reinterpreted: the project gate still reads it as BLOCKED.
182
+ const last=p.definition('2.next','T-003',['b.mjs']);
183
+ const lastExecution=()=>p.execution('2.next',{write:()=>fs.writeFileSync(path.join(p.codeProject,'b.mjs'),'export const b=1;\n')});
184
+ const refused=await p.advance(last,lastExecution(),'create');
185
+ assert.equal(refused.code,'project_qa_not_passed',JSON.stringify(refused));
186
+ assert.deepEqual(refused.outstandingQa,[{feature:'1.work',runId:'run-T-002',taskId:'T-002',attempt:1,status:'qa_blocked'}]);
187
+ const history=fs.readFileSync(log,'utf8'),oldReport=fs.readFileSync(oldComplete.report);
188
+ // Its BLOCKED cases (a session BLOCKED answer, a logic case without a host) are rerun-eligible.
189
+ const recovered=await p.advance(p.first,firstExecution(),'resume',{rerunBlockedQa:true});
190
+ assert.equal(recovered.code,'run_done',JSON.stringify(recovered));
191
+ assert.deepEqual(asked,['TC-001','TC-002','TC-001'],'the dropped task case is never asked again');
192
+ assert(fs.readFileSync(log,'utf8').startsWith(history));assert.deepEqual(fs.readFileSync(oldComplete.report),oldReport);
193
+ const superseded=rows().find(row=>row.phase==='superseded');
194
+ assert.equal(superseded.previous_test_run_id,oldComplete.operation_id);assert.deepEqual(superseded.blocked_cases,['TC-002','TC-003']);
195
+ const start=rows().filter(row=>row.phase==='start'&&row.run_id==='run-T-002').at(-1);
196
+ assert.equal(start.attempt,2);assert.equal(start.previous_test_run_id,oldComplete.operation_id);
197
+ assert.deepEqual(start.dropped_task_cases,[{id:'TC-002',taskIds:['T-001']},{id:'TC-003',taskIds:['T-001']}]);
198
+ const complete=rows().filter(row=>row.phase==='complete'&&row.run_id==='run-T-002').at(-1);
199
+ assert.deepEqual([complete.result,complete.case_count,complete.passed],['PASS',2,2]);
200
+ const notApplicable=fs.readFileSync(complete.report,'utf8').split(/^## /m).find(part=>part.startsWith('not_applicable\n'));
201
+ assert.deepEqual(JSON.parse(notApplicable.slice('not_applicable\n'.length)).map(item=>[item.id,item.verdict,item.reason]),
202
+ [['TC-002','NOT_APPLICABLE','bound only to dropped tasks: T-001'],['TC-003','NOT_APPLICABLE','bound only to dropped tasks: T-001']]);
203
+ const finished=await p.advance(last,lastExecution(),'resume');
204
+ assert.equal(finished.code,'run_done',JSON.stringify(finished));assert.equal(status(p).state,'run_done');
205
+ });
206
+
140
207
  test('#18 unreviewed tampering with the earlier task file still requires correction review and names the file',async()=>{
141
208
  const p=project();
142
209
  await p.advance(p.first,p.firstExecution(),'create');
@@ -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
+ });