@aibyzero/cm-workflow 0.16.5 → 0.16.7

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 (202) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +19 -1
  4. package/README.md +17 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +28 -7
  17. package/docs/js-workflow-control.md +96 -6
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/untested-branches.md +27 -4
  21. package/docs/user-guide.md +23 -8
  22. package/install-codex.sh +28 -11
  23. package/package.json +1 -1
  24. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  25. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  26. package/runtime/js/cm-ai/cm-ai-admission.mjs +34 -10
  27. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  28. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
  29. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
  30. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  31. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  32. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  33. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  34. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  35. package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
  36. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  37. package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
  38. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  39. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  40. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  41. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  42. package/runtime/js/cm-ai/external-models.mjs +52 -0
  43. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  44. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  45. package/runtime/js/cm-ai/host-check.mjs +30 -4
  46. package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
  47. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  48. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  49. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +54 -8
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  52. package/runtime/js/cm-ai/host-session.mjs +1 -1
  53. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  54. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  55. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  56. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  57. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  58. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  59. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  60. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  61. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  62. package/runtime/js/cm-ai/operator-guidance.mjs +89 -0
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  64. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  65. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  66. package/runtime/js/cm-ai/review-package.mjs +11 -0
  67. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  68. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  69. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  70. package/runtime/js/cm-ai/task-runner.mjs +176 -25
  71. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  72. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  73. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  74. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  75. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  76. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  77. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  78. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  79. package/runtime/js/cm-fix/execution.mjs +183 -40
  80. package/runtime/js/cm-fix/final-review.mjs +18 -10
  81. package/runtime/js/cm-fix/finish.mjs +2 -19
  82. package/runtime/js/cm-fix/host-review.mjs +25 -6
  83. package/runtime/js/cm-fix/host.mjs +4 -1
  84. package/runtime/js/cm-fix/layout.mjs +1 -1
  85. package/runtime/js/cm-fix/log-events.mjs +29 -0
  86. package/runtime/js/cm-fix/metrics.mjs +3 -2
  87. package/runtime/js/cm-fix/progress.mjs +4 -0
  88. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  89. package/runtime/js/cm-prd/analysis.mjs +5 -2
  90. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  91. package/runtime/js/cm-prd/review-host.mjs +2 -1
  92. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  93. package/runtime/js/cm-prd/review-time.mjs +29 -0
  94. package/runtime/js/cm-prd/session.mjs +53 -6
  95. package/runtime/js/cm-security/finalize.mjs +32 -0
  96. package/runtime/js/cm-test/recovery.mjs +4 -4
  97. package/runtime/review.md +5 -0
  98. package/runtime/task-gates.md +6 -0
  99. package/runtime/workflow-config.md +10 -1
  100. package/scripts/cm-ai-admission.mjs +14 -3
  101. package/scripts/cm-ai-batch-drive.mjs +52 -23
  102. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  103. package/scripts/cm-ai-batch-host.mjs +44 -16
  104. package/scripts/cm-ai-batch-run.mjs +77 -29
  105. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  106. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  107. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  108. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  109. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  110. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  111. package/scripts/cm-ai-drive.mjs +73 -28
  112. package/scripts/cm-ai-drive.test.mjs +119 -1
  113. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  114. package/scripts/cm-ai-host.mjs +79 -27
  115. package/scripts/cm-ai-host.test.mjs +88 -0
  116. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  117. package/scripts/cm-ai-progress.test.mjs +521 -0
  118. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  119. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  120. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  121. package/scripts/cm-ai-run.mjs +94 -19
  122. package/scripts/cm-ai-run.test.mjs +2 -1
  123. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  124. package/scripts/cm-check-drive.test.mjs +1 -0
  125. package/scripts/cm-check-runtime.sh +11 -0
  126. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  127. package/scripts/cm-claude-probe.test.mjs +1 -1
  128. package/scripts/cm-codex-plugin-metadata.py +83 -0
  129. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  130. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  131. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  132. package/scripts/cm-efficiency-offline.mjs +35 -0
  133. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  134. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  135. package/scripts/cm-efficiency-response.test.mjs +117 -0
  136. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  137. package/scripts/cm-external-batch-host.test.mjs +157 -0
  138. package/scripts/cm-external-fix-host.test.mjs +281 -0
  139. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  140. package/scripts/cm-external-group-models.test.mjs +60 -0
  141. package/scripts/cm-external-model-host.test.mjs +180 -0
  142. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  143. package/scripts/cm-external-models.test.mjs +89 -0
  144. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  145. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  146. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  147. package/scripts/cm-fix-drive.mjs +28 -13
  148. package/scripts/cm-fix-final-review.test.mjs +11 -6
  149. package/scripts/cm-fix-host.mjs +17 -10
  150. package/scripts/cm-fix-large-log.test.mjs +113 -0
  151. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  152. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  153. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  154. package/scripts/cm-host-qa-executor.test.mjs +329 -3
  155. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  156. package/scripts/cm-live-evidence.test.mjs +64 -0
  157. package/scripts/cm-log-event.mjs +34 -7
  158. package/scripts/cm-log-event.py +15 -0
  159. package/scripts/cm-model-setup.mjs +79 -0
  160. package/scripts/cm-prd-drive.mjs +32 -11
  161. package/scripts/cm-prd-drive.test.mjs +15 -0
  162. package/scripts/cm-prd-host.mjs +26 -6
  163. package/scripts/cm-prd-host.test.mjs +4 -0
  164. package/scripts/cm-prd-review-host.test.mjs +17 -0
  165. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  166. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  167. package/scripts/cm-release-smoke.sh +5 -1
  168. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  169. package/scripts/cm-runtime-i18n.mjs +15 -4
  170. package/scripts/cm-runtime-install.mjs +8 -4
  171. package/scripts/cm-runtime.mjs +116 -23
  172. package/scripts/cm-runtime.test.mjs +121 -12
  173. package/scripts/cm-security.test.mjs +32 -0
  174. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  175. package/scripts/cm-task-gate.mjs +146 -10
  176. package/scripts/cm-task-gate.py +1 -0
  177. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  178. package/scripts/cm-test-drive.mjs +10 -4
  179. package/scripts/cm-test-drive.test.mjs +14 -1
  180. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  181. package/scripts/cm-usage-report.py +22 -3
  182. package/scripts/cm-workflow-config.mjs +10 -1
  183. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  184. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  185. package/scripts/fixtures/process-cleanup.mjs +3 -1
  186. package/scripts/test-cm-native-usage.py +62 -0
  187. package/scripts/test-external-model-setup.py +91 -0
  188. package/scripts/test-model-configuration-write.py +201 -0
  189. package/scripts/test-npm-install.py +10 -1
  190. package/skills/cm-ai/SKILL.md +2 -2
  191. package/skills/cm-ai/references/N1-init.md +1 -1
  192. package/skills/cm-ai/references/N8-finish.md +5 -0
  193. package/skills/cm-ai/references/js-host.md +16 -7
  194. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  195. package/skills/cm-fix/SKILL.md +1 -1
  196. package/skills/cm-fix/references/js-host.md +30 -2
  197. package/skills/cm-prd/SKILL.md +5 -4
  198. package/skills/cm-prd/references/spec-self-check.md +3 -1
  199. package/skills/cm-runtime/SKILL.md +29 -6
  200. package/skills/cm-security/SKILL.md +4 -2
  201. package/skills/cm-security/references/scan-contract.md +1 -0
  202. package/templates/cm-workflow.yml +1 -1
@@ -0,0 +1,170 @@
1
+ import {EXECUTION_POLICY_V1} from '../runtime/js/cm-ai/execution-policy.mjs';
2
+ import {expandReviewData} from '../runtime/js/cm-ai/review-presentation.mjs';
3
+ import test,{after} from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {spawn} from 'node:child_process';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {openControlRun} from './cm-ai-run.mjs';
12
+ import {createConversationExecution} from './cm-ai-host.mjs';
13
+ import {createQaFixOwnerHost} from '../runtime/js/cm-ai/host-qa-fix-owner.mjs';
14
+ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
15
+ import {qaFixIdentity} from '../runtime/js/cm-fix/qa-source.mjs';
16
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
17
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
18
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
19
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
20
+
21
+ // Real parent/child stores and grants; synthetic provider results. No native
22
+ // Codex sandbox, network, install or user's runtime configuration is needed.
23
+ const home=fs.mkdtempSync(path.join(os.tmpdir(),'qa-fix-session-home-'));
24
+ process.env.CM_WORKFLOW_HOME=path.join(home,'user');
25
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(home,'logs');
26
+ after(()=>fs.rmSync(home,{recursive:true,force:true}));
27
+ const A='session-A',B='session-B',C='session-C';
28
+ const prepare=async()=>({files:[],contextDigest:digest([]),application:{contextDigest:digest([]),
29
+ status:'no_relevant_lesson',summary:'Synthetic fixture'}});
30
+ const diagnosis={status:'diagnosed',rootCause:'Wrong constant across layers',affectedPaths:['value.mjs'],
31
+ affectedModules:['value'],plan:'Set value to 2 after review',crossLayer:true};
32
+ function events(onEvent,thread){
33
+ for(const event of [{event:'thread.started',provider_thread:thread},{event:'turn.started',item_type:null},
34
+ {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},
35
+ {event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
36
+ }
37
+ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0,external=false,lateCause=false,optimized=false}={}){
38
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'qa-fix-session-')));
39
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.value';
40
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
41
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=0;');
42
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'Value must be 2.');
43
+ fs.writeFileSync(path.join(codeProject,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
44
+ fs.writeFileSync(path.join(codeProject,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
45
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
46
+ for(const name of ['requirements','design'])fs.writeFileSync(path.join(specsDir,feature,`${name}.md`),'# Fixture');
47
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement value\n');
48
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
49
+ const identity={repositoryId:'fixture',runId:'qa-parent',taskId:'T-001',attempt:1};
50
+ const definition={version:1,specsDir,codeProject,feature,identity,scope:['value.mjs'],requirements:['requirements.md']};
51
+ const review={model:'fixture',disabledSkills:[],preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
52
+ config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture',disabledSkills:[],promptTransport:'stdin'})}};
53
+ const workflow={documentationPaths:[],applicableAgentFiles:[],qa:{commands:[{id:'value',command:[process.execPath,'red.mjs'],caseIds:[]}],
54
+ environment:{kind:'web',carrier:'browser',target:'synthetic-local',scope:'local'}}};
55
+ const bridge={async call(kind){
56
+ assert.equal(kind,'develop');fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=1;');
57
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
58
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
59
+ }};
60
+ const executionFor=live=>{
61
+ const execution=createConversationExecution(definition,live,bridge,review,1,workflow,true,'codex',
62
+ live===A?{}:{originalHostContextId:A});
63
+ execution.check=createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]});
64
+ execution.reviewers[0].run=async(request,{onEvent})=>{
65
+ events(onEvent,'synthetic-parent-review');
66
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
67
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};
68
+ };
69
+ execution.qaDecisionProvider={...execution.qaDecisionProvider,decide:async binding=>({decisionId:'qa-parent',identity:binding.identity,
70
+ packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-08T01:00:00Z'})};
71
+ execution.qaExecutor={...execution.qaExecutor,run:async()=>{
72
+ const report=path.join(specsDir,'.reviews','qa-failure.md');fs.writeFileSync(report,'Synthetic QA FAIL: value must be 2.');
73
+ return {result:'FAIL',passed:0,failed:1,blocked:0,report};
74
+ }};
75
+ return execution;
76
+ };
77
+ let parent=null,owner=null;
78
+ t.after(()=>{owner?.close();parent?.close();fs.rmSync(root,{recursive:true,force:true});});
79
+ const request=operation=>({version:1,requestId:operation,operation,identity});
80
+ parent=await openControlRun(definition,'create',executionFor(A));
81
+ const failed=await parent.host.handle(request('advance'));
82
+ assert.equal(failed.code,'qa_failed',JSON.stringify(failed));parent.close();parent=null;
83
+ const qaSource={feature,identity,packageDigest:failed.packageDigest,testRunId:failed.fixHandoff.source.testRunId,
84
+ handoffDigest:failed.fixHandoff.handoffDigest};
85
+ const permissions=['--allow-cause-review'];
86
+ let causeReviews=0;
87
+ const models={schemaVersion:1,providers:{codex:{model:'fixture',effort:'low'}}};
88
+ const childReview=external?{...review,...(lateCause?{timeoutMs:20}:{}),effort:'low',preflight:{...review.preflight,config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture',effort:'low'})}}:review;
89
+ const reviewHost=live=>createFixReviewHost({codeProject,hostContextId:live,review:childReview,permissions,...(optimized?{executionPolicy:EXECUTION_POLICY_V1,specsDir}:{}),...(external?{externalModels:models}:{}),workerFactory:()=>async({prompt},{onEvent,signal,onTerminal})=>{
90
+ const parsed=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]),data=parsed.presentation?expandReviewData(parsed):parsed;
91
+ if(lateCause){causeReviews++;onEvent({event:'thread.started',provider_thread:'synthetic-child-review'});onEvent({event:'turn.started',item_type:null});
92
+ return new Promise(resolve=>signal.addEventListener('abort',()=>setTimeout(()=>{
93
+ for(const event of [{event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},{event:'process_closed',exit_code:null,signal:'SIGTERM',timed_out:false}])onEvent(event);
94
+ onTerminal({status:'succeeded',value:{verdict:'approved',packageDigest:data.reviewPackage.packageDigest,examinedPaths:['value.mjs'],findings:[],summary:'Original QA child review'}});resolve({status:'cancelled',code:'cancelled'});
95
+ },5),{once:true}));
96
+ }
97
+ if(++causeReviews<=lostCauseReviews){onEvent({event:'thread.started',provider_thread:`lost-child-review-${causeReviews}`});
98
+ throw Error('Synthetic lost cause review');}
99
+ events(onEvent,'synthetic-child-review');
100
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:data.reviewPackage.packageDigest,
101
+ examinedPaths:['value.mjs'],findings:[],summary:'Synthetic cause review'}};
102
+ }});
103
+ const configuration={...(optimized?{executionPolicy:EXECUTION_POLICY_V1}:{}),...(external?{externalModels:models}:{}),hostContextId:childHost,defect:'Value must be 2',qaSource,
104
+ causeReview:{...reviewHost(A).reviewer,...(causeContext?{contextId:causeContext}:{})},
105
+ reproduction:{cwd:codeProject,command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000}};
106
+ const fix={specsRoot:specsDir,identity:qaFixIdentity(qaSource),configuration};
107
+ const childDir=path.join(specsDir,'.reviews','.execution',fix.identity.runId),statePath=path.join(childDir,'state.json');
108
+ const bound=operation=>({...request(operation),packageDigest:failed.packageDigest,testRunId:qaSource.testRunId});
109
+ const close=()=>{owner?.close();owner=null;};
110
+ const open=async(live,{allowStart=true,template=false,allowAbandon=false,lostDiagnosis=false}={})=>{
111
+ close();const execution=executionFor(live);assert.equal(execution.configuration.hostContextId,A);
112
+ parent=await openControlRun(definition,'resume',execution);
113
+ const rh=reviewHost(live);
114
+ const {qaSource:ignored,...templateConfiguration}=configuration;
115
+ owner=createQaFixOwnerHost({parent,...(optimized?{executionPolicy:EXECUTION_POLICY_V1}:{}),...(external?{externalModels:models}:{}),hostContextId:live,parentHostContextId:execution.configuration.hostContextId,
116
+ reopenParent:()=>openControlRun(definition,'resume',execution),allowStart,
117
+ ...(template?{template:{specsRoot:specsDir,feature,identity,configuration:templateConfiguration}}:{fix}),
118
+ fixPermissions:allowAbandon?[...permissions,'--allow-abandon']:permissions,
119
+ fixAuthorities:{authority:rh.authority,finalAuthority:rh.finalAuthority},
120
+ fixExecution:{...rh.execution,prepare,bridge:{async call(kind){assert.equal(kind,'fix_diagnose');
121
+ if(lostDiagnosis)throw Error('Synthetic lost diagnosis');return diagnosis;}}}});
122
+ parent=null;return owner;
123
+ };
124
+ const records=()=>JSON.parse(fs.readFileSync(statePath)).records;
125
+ const bin=path.join(root,'bin');fs.mkdirSync(bin);
126
+ const fake=path.join(bin,'codex');fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),fake);fs.chmodSync(fake,0o700);
127
+ for(const [name,value] of Object.entries({run:definition,review,workflow,fix}))fs.writeFileSync(path.join(root,`${name}.json`),JSON.stringify(value));
128
+ return {causeReviews:()=>causeReviews,models,open,close,bound,fix,childDir,statePath,records,reviewHost,root,bin,request};
129
+ }
130
+
131
+
132
+ test('QA child inherits one frozen pair, reopens original parent and preserves child snapshot across sessions',async t=>{
133
+ const f=await fixture(t,{external:true});let owner=await f.open(A,{template:true});
134
+ assert.equal((await owner.handle(f.bound('fix_advance'))).fixStage,'cause_review_required');
135
+ assert.deepEqual(f.records()[0].payload.configuration.externalModels,f.models);
136
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');
137
+ f.close();const before=f.records();owner=await f.open(B);
138
+ assert.equal((await owner.handle(f.bound('fix_status'))).fixStage,'red_test_required');assert.deepEqual(f.records(),before);
139
+ f.close();f.fix.configuration.externalModels={schemaVersion:1,providers:{codex:{model:'other',effort:'high'}}};
140
+ await assert.rejects(f.open(C),{code:'external_model_pair_conflict'});
141
+ });
142
+ test('QA child refuses retrofitting legacy definition with new provider defaults',async t=>{
143
+ const f=await fixture(t,{external:true});delete f.fix.configuration.externalModels;
144
+ await assert.rejects(f.open(A),{code:'external_model_legacy_child_inheritance_forbidden'});
145
+ assert(!fs.existsSync(f.statePath));
146
+ });
147
+
148
+ test('QA fix_action reconciles original late child invocation across parent reopen with zero provider authority',async t=>{
149
+ const f=await fixture(t,{external:true,lateCause:true});let owner=await f.open(A,{template:true});
150
+ await owner.handle(f.bound('fix_advance'));
151
+ const unknown=await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'});assert.equal(unknown.fixStage,'unknown',JSON.stringify(unknown));
152
+ const invocationId=f.records().find(r=>r.id==='fix-cause-registered').payload.request.invocationId;
153
+ assert.equal(f.causeReviews(),1);f.close();owner=await f.open(B);
154
+ const resolved=await owner.handle({...f.bound('fix_action'),fixOperation:'reconcile_review',invocationId});
155
+ assert.equal(resolved.fixStage,'cause_review_evidence_required',JSON.stringify(resolved));assert.equal(f.causeReviews(),1);
156
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');assert.equal(f.causeReviews(),1);
157
+ });
158
+
159
+ test('QA optimization child inherits frozen policy and resumes original child without dispatch',async t=>{
160
+ const f=await fixture(t,{optimized:true});let owner=await f.open(A,{template:true});
161
+ assert.equal((await owner.handle(f.bound('fix_advance'))).fixStage,'cause_review_required');
162
+ assert.deepEqual(f.records()[0].payload.configuration.executionPolicy,EXECUTION_POLICY_V1);
163
+ assert.equal((await owner.handle({...f.bound('fix_action'),fixOperation:'cause_review'})).fixStage,'red_test_required');
164
+ f.close();const before=f.records();owner=await f.open(B);
165
+ assert.equal((await owner.handle(f.bound('fix_status'))).fixStage,'red_test_required');assert.deepEqual(f.records(),before);assert.equal(f.causeReviews(),1);
166
+ });
167
+ test('QA optimization refuses retrofitting a legacy child before opening a store',async t=>{
168
+ const f=await fixture(t,{optimized:true});delete f.fix.configuration.executionPolicy;
169
+ await assert.rejects(f.open(A),{code:'execution_policy_legacy_child_inheritance_forbidden'});assert(!fs.existsSync(f.statePath));
170
+ });
@@ -0,0 +1,314 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn,spawnSync} from 'node:child_process';
7
+ import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
8
+ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
9
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
10
+ import {readRunnerHistory,runnerStatus,completedEffectCount} from '../runtime/js/cm-ai/durable-runner-state.mjs';
11
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
12
+ import {createCmAiConversationEntry} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
13
+ import {abandonReviewPlanError,buildCmAiDriveRequest,buildCmAiDriveHostArgs} from './cm-ai-drive.mjs';
14
+ import {recordReviewAbandonment} from '../runtime/js/cm-ai/review-abandon-log.mjs';
15
+ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
16
+ import {PassThrough} from 'node:stream';
17
+ import {codexWorker} from '../runtime/js/cm-ai/worker-codex.mjs';
18
+ import {claudeWorker,claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
19
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
20
+ import {createCodexReviewRun} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
21
+ import {createClaudeReviewRun} from '../runtime/js/cm-ai/claude-review-adapter.mjs';
22
+
23
+
24
+
25
+
26
+
27
+ const checks=[{id:'check',command:['synthetic'],outcome:'passed',exitCode:0,evidence:'fixture'}];
28
+ const grantFor=(request,authorizationAt,change=grant=>grant)=>{
29
+ const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.invocationId}`,adapterId:`${request.provider}-review-adapter`,
30
+ invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
31
+ reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
32
+ hostContextId:'actual-main',decisionId:'decision-1',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
33
+ change(body);return {...body,grantDigest:digest(body)};
34
+ };
35
+ const events=(onEvent,thread='actual-review')=>{
36
+ onEvent({event:'thread.started',provider_thread:thread});
37
+ onEvent({event:'turn.started',item_type:null});
38
+ onEvent({event:'item.completed',item_type:'agent_message'});
39
+ onEvent({event:'turn.completed',item_type:null});
40
+ onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
41
+ };
42
+
43
+ async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='codex'}={}) {
44
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-v3-')));
45
+ const root=path.join(temp,'code'),specsRoot=path.join(temp,'specs'),reviewsDir=path.join(specsRoot,'.reviews');
46
+ fs.mkdirSync(root);fs.mkdirSync(reviewsDir,{recursive:true});
47
+ const tasksPath=path.join(specsRoot,'tasks.md');fs.writeFileSync(tasksPath,'- [ ] T-001: fixture\n');
48
+ fs.writeFileSync(path.join(root,'code.js'),'old\n');fs.writeFileSync(path.join(root,'requirements.md'),'fixture\n');
49
+ const identity={repositoryId:'fixture',runId:'review-v3',taskId:'T-001',attempt:1};
50
+ const owner={tasksPath,feature:'feature',specsRoot,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
51
+ fingerprints:{workflow:digest('review-v3'),config:digest('fixture'),inputs:digest('original')},create:true};
52
+ let dispatches=0,lateEvent=null,store=openTaskExecutionStore(owner);
53
+ const defaultRun=(request,{onEvent})=>{events(onEvent);
54
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
55
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};};
56
+ const options={externalModels:{schemaVersion:1,providers:{[provider]:{model:'fixture',effort:provider==='codex'?'high':null}}},root,identity,scope:['code.js'],requirements:['requirements.md'],excludedContexts:['main'],timeoutMs,
57
+ developer:{provider,requestedModel:'fixture',contextId:'developer-logical',run:request=>{
58
+ // Attempt 2 must answer attempt 1's findings; identical bytes are refused.
59
+ fs.writeFileSync(path.join(root,'code.js'),request.identity.attempt===1?'new\n':'new 2\n');return {version:1,invocationId:request.invocationId,
60
+ contextId:request.contextId,provider:request.provider,effectiveModel:'fixture',status:'succeeded',accepted:true,
61
+ result:{outcome:'implemented'}};}},
62
+ reviewers:[{id:'reviewer',adapterId:`${provider}-review-adapter`,provider,requestedModel:'fixture',allowed:true,
63
+ available:true,contexts:['review-logical-1','review-logical-2'],run:(request,control)=>{
64
+ dispatches++;lateEvent=control.onEvent;return (reviewRun??defaultRun)(request,control);
65
+ }}],check:()=>checks,
66
+ taskCompletion:{reviewsDir,handoffs:[path.join(reviewsDir,'a1.json'),path.join(reviewsDir,'a2.json')]},
67
+ reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
68
+ authorize:authorize??((request,{authorizationAt})=>grantFor(request,authorizationAt))}};
69
+ const make=mode=>{
70
+ const old=Date.now,values=times?[...times]:null;if(values)Date.now=()=>values.length>1?values.shift():values[0];
71
+ try{return createTaskRunner({...options,persistence:{store,mode,version:3}});}finally{Date.now=old;}
72
+ };
73
+ const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
74
+ const resumePrefix=(type,last=false)=>{
75
+ const current=store.snapshot(),at=last?current.records.findLastIndex(record=>record.payload.type===type)
76
+ :current.records.findIndex(record=>record.payload.type===type);assert(at>=0);store.close();
77
+ const statePath=path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json');
78
+ const body={version:current.version,identity:current.identity,fingerprints:current.fingerprints,records:current.records.slice(0,at+1)};
79
+ fs.writeFileSync(statePath,JSON.stringify({...body,revision:digest(body)})+'\n',{mode:0o600});
80
+ store=openTaskExecutionStore({...owner,create:false});return make('resume');
81
+ };
82
+ const effect=(kind,attempt=1)=>({version:1,id:`${kind}-${attempt}`,identity:{...identity,attempt},kind});
83
+ try{return await fn({root,tasksPath,options,effect,make:()=>make('create'),reopen,resumePrefix,getStore:()=>store,
84
+ dispatches:()=>dispatches,lateEvent:()=>lateEvent});}
85
+ finally{store.close();fs.rmSync(temp,{recursive:true,force:true});}
86
+ }
87
+
88
+ const retryEffect=(f,attempt=1)=>({...f.effect('review',attempt),id:`review-${attempt}-retry-1`});
89
+
90
+ const lateReceiptRun=({failed=false,change=()=>{},duplicate=false}={})=>(request,{onEvent,onReconciliation,signal})=>{
91
+ const captured=[];
92
+ const emit=event=>{captured.push(event);return onEvent(event);};
93
+ emit({event:'thread.started',provider_thread:`thread-${request.invocationId}`});
94
+ emit({event:'turn.started',item_type:null});
95
+ return new Promise(resolve=>signal.addEventListener('abort',()=>setTimeout(()=>{
96
+ if(failed)emit({event:'turn.failed',item_type:null});
97
+ else {emit({event:'item.completed',item_type:'agent_message'});emit({event:'turn.completed',item_type:null});}
98
+ emit({event:'process_closed',exit_code:null,signal:'SIGTERM',timed_out:false});
99
+ const receipt={cleanup:'owned_process_group_closed',events:captured,result:failed?{status:'failed',code:'provider_failed'}:
100
+ {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
101
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Original late result'}}};
102
+ change(receipt);onReconciliation(receipt);if(duplicate)onReconciliation(receipt);
103
+ resolve({status:'cancelled',code:'cancelled'});
104
+ },5),{once:true}));
105
+ };
106
+
107
+ for(const provider of ['codex','claude'])test(`${provider} late terminal receipt survives restart and reconciles once with zero redispatch`,()=>fixture(async f=>{
108
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
109
+ const end=await runner.executeEffect(f.effect('review'));assert.equal(end.state,'unknown');
110
+ assert.equal(end.reviewReconciliation.available,true);
111
+ const original=f.getStore().snapshot(),invocationId=end.reviewReconciliation.invocationId;
112
+ assert.equal(original.records.at(-1).payload.type,'review-invocation-receipt');
113
+ const resumed=f.reopen();assert.equal(resumed.status().reviewReconciliation.available,true);
114
+ assert.equal(resumed.reconcileReview({invocationId:'wrong-call'}).code,'review_reconciliation_binding');
115
+ assert.deepEqual(f.getStore().snapshot(),original);
116
+ const results=await Promise.all([1,2,3].map(()=>Promise.resolve().then(()=>resumed.reconcileReview({invocationId}))));
117
+ for(const result of results)assert.equal(result.state,'approved',JSON.stringify(result));
118
+ const saved=f.getStore().snapshot();assert.deepEqual(saved.records.slice(0,original.records.length),original.records);
119
+ assert.equal(saved.records.filter(row=>row.payload.type==='review-invocation-reconciled').length,1);
120
+ assert.equal(f.dispatches(),1);assert.equal(results[0].calls.at(-1).effectiveModel,'unknown');
121
+ assert.deepEqual(f.reopen().status(),results[0]);
122
+ // This minimal fixture deliberately has no completion handoff. Accepting a
123
+ // provider result must not bypass that existing completion gate.
124
+ const completed=await f.reopen().executeEffect(f.effect('complete'));
125
+ assert.notEqual(completed.outcome,'rejected');assert.notEqual(completed.state,'fixture_completed');
126
+ assert.match(fs.readFileSync(f.tasksPath,'utf8'),/\[ \]/);
127
+ assert.equal(f.dispatches(),1);
128
+ },{timeoutMs:20,provider,reviewRun:lateReceiptRun({duplicate:true})}));
129
+
130
+ test('reconciled provider failure spends the original one-retry budget and requires a fresh grant',()=>fixture(async f=>{
131
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
132
+ const first=await runner.executeEffect(f.effect('review'));
133
+ const after=runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
134
+ assert.equal(after.state,'pending_review');assert.equal(after.code,'review_provider_failed');assert.equal(f.dispatches(),1);
135
+ const second=await runner.executeEffect(retryEffect(f));assert.equal(second.state,'unknown');
136
+ const final=runner.reconcileReview({invocationId:second.reviewReconciliation.invocationId});
137
+ assert.equal(final.state,'blocked');assert.equal(final.code,'review_provider_failed');assert.equal(f.dispatches(),2);
138
+ assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,second.reviewInvocation.registration.grant.grantDigest);
139
+ assert.equal((await runner.executeEffect({...retryEffect(f),id:'third-review'})).code,'stage_mismatch');
140
+ assert.equal(f.dispatches(),2);assert.deepEqual(f.reopen().status(),final);
141
+ },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true})}));
142
+
143
+ test('replay rejects receipt or reconciliation bindings even when an attacker recomputes the journal hash chain',()=>fixture(async f=>{
144
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
145
+ const end=await runner.executeEffect(f.effect('review'));
146
+ runner.reconcileReview({invocationId:end.reviewReconciliation.invocationId});
147
+ const original=f.getStore().snapshot().records;
148
+ for(const [type,key,value] of [
149
+ ['review-invocation-receipt','invocationId','other-call'],['review-invocation-receipt','effectId','review-2'],
150
+ ['review-invocation-receipt','registeredDigest',digest('other-grant')],
151
+ ['review-invocation-receipt','startedDigest',digest('other-thread')],
152
+ ['review-invocation-receipt','resultDigest',digest('other-result')],
153
+ ['review-invocation-reconciled','receiptDigest',digest('other-receipt')],
154
+ ['review-invocation-reconciled','invocationId','other-call'],
155
+ ]){
156
+ const rows=structuredClone(original);rows.find(row=>row.payload.type===type).payload[key]=value;
157
+ let previousDigest=null;for(const row of rows){row.previousDigest=previousDigest;const {digest:old,...body}=row;row.digest=digest(body);previousDigest=row.digest;}
158
+ assert.throws(()=>readRunnerHistory(rows,rows[0].payload.config,3),`${type}/${key}`);
159
+ }
160
+ assert.deepEqual(f.getStore().snapshot().records,original);assert.equal(f.dispatches(),1);
161
+ },{timeoutMs:20,reviewRun:lateReceiptRun()}));
162
+
163
+ test('reconciliation is not dispatch approval and the original grant cannot authorize another invocation',()=>{
164
+ let originalGrant;
165
+ return fixture(async f=>{
166
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
167
+ const first=await runner.executeEffect(f.effect('review'));
168
+ runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
169
+ assert.equal((await runner.executeEffect(retryEffect(f))).code,'authorization_invalid');
170
+ assert.equal(f.dispatches(),1);
171
+ },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true}),authorize:(request,{authorizationAt})=>originalGrant??=grantFor(request,authorizationAt)});
172
+ });
173
+
174
+ for(const [name,change] of [
175
+ ['only local exit',r=>{r.events=r.events.filter(e=>!['item.completed','turn.completed'].includes(e.event));r.result={status:'failed',code:'incomplete_result'};}],
176
+ ['wrong provider thread',r=>{r.events[0].provider_thread='other-provider-call';}],
177
+ ['wrong package',r=>{r.result.value.packageDigest=digest('another-package');}],
178
+ ['descendant cleanup uncertain',r=>{r.cleanup='unknown';}],
179
+ ])test(`reconciliation refuses ${name} without changing the original unknown`,()=>fixture(async f=>{
180
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
181
+ const end=await runner.executeEffect(f.effect('review'));assert.equal(end.state,'unknown');assert.equal(end.reviewReconciliation.available,false);
182
+ const before=f.getStore().snapshot();
183
+ assert.equal(runner.reconcileReview({invocationId:end.reviewReconciliation.invocationId}).code,'review_reconciliation_evidence_required');
184
+ assert.deepEqual(f.getStore().snapshot(),before);assert.equal(f.dispatches(),1);
185
+ assert.equal(f.reopen().status().reviewReconciliation.available,false);
186
+ },{timeoutMs:20,reviewRun:lateReceiptRun({change})}));
187
+
188
+
189
+ test('driver request reaches the real JSONL transport and reconciles without review permission',()=>fixture(async f=>{
190
+ const original=f.make();await original.executeEffect(f.effect('develop'));
191
+ const end=await original.executeEffect(f.effect('review')),runner=f.reopen();
192
+ const host=createCmAiConversationEntry({specsDir:path.dirname(f.tasksPath),codeProject:f.root,
193
+ feature:'feature',identity:f.options.identity,runner});
194
+ const input=new PassThrough(),output=new PassThrough();let printed='';output.on('data',chunk=>{printed+=chunk;});
195
+ const serving=serveCmAiHost({host,input,output});
196
+ const request={...buildCmAiDriveRequest('reconcile_review',{invocationId:end.reviewReconciliation.invocationId},
197
+ {identity:f.options.identity}),operation:'reconcile_review',requestId:'reconcile-original'};
198
+ input.end(JSON.stringify(request)+'\n');await serving;
199
+ const response=printed.trim().split('\n').map(line=>JSON.parse(line)).find(row=>row.requestId==='reconcile-original');
200
+ assert.equal(response.result.outcome,'reconciled',printed);assert.equal(response.result.state,'approved');
201
+ assert.equal(f.dispatches(),1);
202
+ },{timeoutMs:20,reviewRun:lateReceiptRun()}));
203
+
204
+ for(const provider of ['codex','claude'])for(const failed of [false,true])
205
+ test(`${provider} actual fake CLI captures a late ${failed?'failure':'result'} through its trusted worker`,()=>fixture(async f=>{
206
+ const script=path.join(path.dirname(f.root),'late-provider.mjs');
207
+ fs.writeFileSync(script,`let prompt='';for await(const chunk of process.stdin)prompt+=chunk;
208
+ const marker='<cm-review-data-json>\\n',data=JSON.parse(prompt.slice(prompt.indexOf(marker)+marker.length));
209
+ const provider=${JSON.stringify(provider)},failed=${failed},thread='original-'+process.pid;
210
+ const out=value=>process.stdout.write(JSON.stringify(value)+'\\n');
211
+ process.on('SIGTERM',()=>{
212
+ const value={verdict:'approved',packageDigest:data.reviewPackage.packageDigest,examinedPaths:data.examinedPaths,findings:[],summary:'Late original CLI'};
213
+ if(provider==='codex'){
214
+ if(failed)out({type:'turn.failed'});
215
+ else {out({type:'item.completed',item:{type:'agent_message',text:JSON.stringify(value)}});out({type:'turn.completed'});}
216
+ }else if(failed)out({type:'result',subtype:'error_during_execution',is_error:true,num_turns:1,session_id:thread});
217
+ else {out({type:'assistant',session_id:thread,parent_tool_use_id:null,message:{role:'assistant',content:[{type:'text',text:'done'}]}});
218
+ out({type:'result',subtype:'success',is_error:false,num_turns:1,session_id:thread,structured_output:value});}
219
+ setTimeout(()=>process.exit(failed?1:0),5);
220
+ });
221
+ if(provider==='codex'){out({type:'thread.started',thread_id:thread});out({type:'turn.started'});}
222
+ else out({type:'system',subtype:'init',session_id:thread});
223
+ setInterval(()=>{},1000);
224
+ `);
225
+ let spawns=0;
226
+ f.options.reviewInvocation.timeoutMs=300;
227
+ f.options.reviewers[0].run=(request,control)=>{
228
+ const options={cwd:f.root,model:'fixture',effort:f.options.externalModels.providers[provider].effort,promptTransport:'stdin'};
229
+ const preflight=provider==='codex'?{passed:true,cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint(options)}:
230
+ {passed:true,provider:'claude',prompt_transport:'stdin',config_fingerprint:claudeReviewFingerprint(options)};
231
+ const worker=(provider==='codex'?codexWorker:claudeWorker)({...options,preflight,timeoutMs:5000,schemaPath:'synthetic.schema.json',
232
+ spawnProcess:(_cli,_args,opts)=>{spawns++;return spawn(process.execPath,[script],opts);}});
233
+ return (provider==='codex'?createCodexReviewRun:createClaudeReviewRun)(worker)(request,control);
234
+ };
235
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
236
+ const first=await runner.executeEffect(f.effect('review'));
237
+ assert.equal(first.state,'unknown');assert.equal(first.reviewReconciliation.available,true,JSON.stringify(first));
238
+ const resumed=f.reopen(),end=resumed.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
239
+ assert.equal(end.state,failed?'pending_review':'approved',JSON.stringify(end));assert.equal(spawns,1);
240
+ if(failed){
241
+ const retry=await resumed.executeEffect(retryEffect(f));assert.equal(retry.state,'unknown');
242
+ const exhausted=resumed.reconcileReview({invocationId:retry.reviewReconciliation.invocationId});
243
+ assert.equal(exhausted.state,'blocked');assert.equal(spawns,2);
244
+ assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,retry.reviewInvocation.registration.grant.grantDigest);
245
+ }
246
+ },{provider,timeoutMs:2000}));
247
+
248
+ test('bounded cleanup receipts arriving after the former 1750ms window are retained',()=>fixture(async f=>{
249
+ f.options.reviewInvocation.timeoutMs=20;
250
+ const original=f.options.reviewers[0].run;
251
+ f.options.reviewers[0].run=(request,control)=>original(request,{...control,signal:control.signal,
252
+ onReconciliation:value=>control.onReconciliation(value)});
253
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
254
+ const end=await runner.executeEffect(f.effect('review'));
255
+ assert.equal(end.reviewReconciliation.available,true);
256
+ assert.equal(f.reopen().reconcileReview({invocationId:end.reviewReconciliation.invocationId}).state,'approved');
257
+ assert.equal(f.dispatches(),1);
258
+ },{timeoutMs:3000,reviewRun:(request,control)=>{
259
+ const delay=new AbortController();control.signal.addEventListener('abort',()=>setTimeout(()=>delay.abort(),1850),{once:true});
260
+ return lateReceiptRun()(request,{...control,signal:delay.signal});
261
+ }}));
262
+
263
+ test('conflicting terminal receipts cannot replace the original unknown',()=>fixture(async f=>{
264
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
265
+ const end=await runner.executeEffect(f.effect('review'));
266
+ assert.equal(end.reviewReconciliation.available,false);assert.equal(f.dispatches(),1);
267
+ assert(!f.getStore().snapshot().records.some(row=>row.payload.type==='review-invocation-receipt'));
268
+ },{timeoutMs:20,reviewRun:(request,control)=>lateReceiptRun()(request,{...control,onReconciliation:value=>{
269
+ control.onReconciliation(value);const changed=structuredClone(value);changed.result.value.summary='Conflicting result';
270
+ control.onReconciliation(changed);
271
+ }})}));
272
+
273
+ for(const violation of ['wrong_session','tool','unknown_event','extra_terminal'])
274
+ test(`Claude actual fake CLI with ${violation} after an API error cannot issue a trusted receipt`,()=>fixture(async f=>{
275
+ const script=path.join(path.dirname(f.root),'invalid-late-provider.mjs');
276
+ fs.writeFileSync(script,`for await(const chunk of process.stdin){};
277
+ const out=value=>process.stdout.write(JSON.stringify(value)+'\\n');
278
+ const session_id='original-thread',violation=${JSON.stringify(violation)};
279
+ const terminal={type:'result',subtype:'error_during_execution',is_error:true,num_turns:1,session_id};
280
+ process.once('SIGTERM',()=>{
281
+ out({type:'assistant',session_id,parent_tool_use_id:null,error:'server_error',message:{role:'assistant',content:[{type:'text',text:'synthetic error'}]}});
282
+ if(violation==='wrong_session')out({...terminal,session_id:'another-provider-thread'});
283
+ if(violation==='tool')out({type:'assistant',session_id,parent_tool_use_id:null,message:{role:'assistant',content:[{type:'tool_use',id:'tool-1',name:'Shell'}]}});
284
+ if(violation==='unknown_event')out({type:'unexpected_event',session_id});
285
+ out(terminal);if(violation==='extra_terminal')out(terminal);
286
+ setTimeout(()=>process.exit(1),5);
287
+ });
288
+ out({type:'system',subtype:'init',session_id});setInterval(()=>{},1000);
289
+ `);
290
+ let spawns=0;f.options.reviewInvocation.timeoutMs=300;
291
+ f.options.reviewers[0].run=(request,control)=>{
292
+ const opts={cwd:f.root,model:'fixture'};
293
+ const worker=claudeWorker({...opts,timeoutMs:5000,preflight:{passed:true,provider:'claude',prompt_transport:'stdin',
294
+ config_fingerprint:claudeReviewFingerprint(opts)},spawnProcess:(_cli,_args,options)=>{spawns++;return spawn(process.execPath,[script],options);}});
295
+ return createClaudeReviewRun(worker)(request,control);
296
+ };
297
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
298
+ const end=await runner.executeEffect(f.effect('review'));assert.equal(end.state,'unknown');assert.equal(end.reviewReconciliation.available,false);
299
+ const original=f.getStore().snapshot();assert.equal(runner.reconcileReview({invocationId:end.reviewReconciliation.invocationId}).code,'review_reconciliation_evidence_required');
300
+ assert.deepEqual(f.getStore().snapshot(),original);assert.equal(spawns,1);
301
+ },{provider:'claude',timeoutMs:2000}));
302
+
303
+
304
+ test('Claude actual ordinary failure has trusted terminal and reconciles without redispatch',()=>fixture(async f=>{
305
+ const script=path.join(path.dirname(f.root),'ordinary-failure.mjs');
306
+ fs.writeFileSync(script,`for await(const chunk of process.stdin){};const session_id='original-thread';for(const e of [{type:'system',subtype:'init',session_id},{type:'result',subtype:'error_during_execution',is_error:true,num_turns:0,session_id}])console.log(JSON.stringify(e));`);
307
+ let spawns=0;f.options.reviewers[0].run=(request,control)=>{
308
+ const opts={cwd:f.root,model:'fixture',effort:null};
309
+ return createClaudeReviewRun(claudeWorker({...opts,timeoutMs:2000,preflight:{passed:true,provider:'claude',prompt_transport:'stdin',config_fingerprint:claudeReviewFingerprint(opts)},spawnProcess:(_cli,_args,options)=>{spawns++;return spawn(process.execPath,[script],options);}}))(request,control);
310
+ };
311
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));const end=await runner.executeEffect(f.effect('review'));
312
+ assert.equal(end.state,'unknown');assert.equal(end.reviewReconciliation.available,true,JSON.stringify(end));
313
+ assert.equal(f.reopen().reconcileReview({invocationId:end.reviewReconciliation.invocationId}).state,'pending_review');assert.equal(spawns,1);
314
+ },{provider:'claude',timeoutMs:2000}));
@@ -28,7 +28,8 @@
28
28
  //
29
29
  // answers/ 里按反问种类放文件,一种一个:
30
30
  // learning.json {status, summary} 恢复时若存档里已有记录会自动复用
31
- // diagnosis.json 诊断结论对象
31
+ // diagnosis.json 首次诊断结论对象
32
+ // diagnosis-rediagnosis.json 显式原运行重新诊断的新结论,不能复用首次文件
32
33
  // retrospective.json {status, candidates, reason}
33
34
  // test-edits.json {"仓库内路径": "本目录下的内容文件"};修订轮用 test-edits-a2.json
34
35
  // repair-edits.json 同上;修订轮用 repair-edits-a2.json
@@ -47,7 +48,7 @@ const HOST=path.join(here,'cm-fix-host.mjs');
47
48
  // design_change_required uses red_test (or test_author_required/author_tests).
48
49
  // escalation_required uses publish_dossier/finish: neither requests answers.
49
50
  const ASKS={
50
- advance:['learning','diagnosis'],
51
+ advance:['learning','diagnosis'],rediagnose:['learning','diagnosis'],
51
52
  author_tests:['learning','test-edits'],
52
53
  repair:['learning','repair-edits'],
53
54
  retrospective:['learning','retrospective'],
@@ -57,19 +58,29 @@ const ASKS={
57
58
  const READ_ONLY=new Set(['status','final_review_package','completion_evidence','cause_review_package']);
58
59
  const KNOWN=new Set([...Object.keys(ASKS),...READ_ONLY,'cancel','handoff','publish_review','check_n5',
59
60
  'publish_dossier','learning_writeback','walkthrough','finish','final_review','cause_review',
60
- 'recover_final_review','abandon_step','abandon_review','resume','revision_test_check']);
61
+ 'reconcile_review','recover_final_review','abandon_step','abandon_review','resume','revision_test_check']);
61
62
 
62
63
  function loadPlan(){
63
64
  const {operation,plan,base}=loadPlanFile({name:'cm-fix-drive.mjs',known:KNOWN});
64
65
  const abandoning=['abandon_step','abandon_review'].includes(operation);
65
- requireFields(plan,['config','cwd','mode','hostContext','permissions',...(abandoning?[]:['answers'])]);
66
+ requireFields(plan,['config','cwd','mode','hostContext','permissions',...(abandoning||operation==='reconcile_review'?[]:['answers'])]);
66
67
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
67
- if(!Array.isArray(plan.permissions)||plan.permissions.some(p=>!/^--allow-[a-z-]+$/.test(p)))
68
- stop(2,'permissions 必须是 --allow-xxx 形式的数组,原样传给宿主');
68
+ if(!Array.isArray(plan.permissions))stop(2,'permissions must be an array');
69
+ for(let i=0;i<plan.permissions.length;i++){
70
+ const flag=plan.permissions[i];
71
+ if(flag==='--external-models-config'){
72
+ if(typeof plan.permissions[i+1]!=='string')stop(2,'external model configuration path required');
73
+ plan.permissions[++i]=path.resolve(base,plan.permissions[i]);
74
+ }else if(!['--execution-optimizations','--external-models'].includes(flag)&&!/^--allow-[a-z-]+$/.test(flag))stop(2,'invalid permissions');
75
+ }
76
+ if(operation==='reconcile_review'&&(plan.mode!=='resume'||typeof plan.invocationId!=='string'||!plan.invocationId))stop(2,'reconcile_review requires resume and original invocationId');
69
77
  const abandonFlag=operation==='abandon_review'?'--allow-abandon-review':'--allow-abandon';
70
78
  if(abandoning&&(!plan.permissions.includes(abandonFlag)||typeof plan.reason!=='string'
71
79
  ||!plan.reason.trim().length||Buffer.byteLength(plan.reason,'utf8')>1000||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))
72
80
  stop(2,`${operation} 需要 PLAN.reason(单行,最多 1000 字节)和 ${abandonFlag}`);
81
+ if(operation==='rediagnose'&&(plan.mode!=='resume'||!plan.permissions.includes('--allow-rediagnosis')
82
+ ||typeof plan.reason!=='string'||!plan.reason.trim()||Buffer.byteLength(plan.reason,'utf8')>1000
83
+ ||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))stop(2,'rediagnose 需要 mode:resume、--allow-rediagnosis 和单行 reason');
73
84
  if(plan.originalHostContext&&plan.mode!=='resume')stop(2,'originalHostContext 只在 resume 时有意义');
74
85
  if(Object.hasOwn(plan,'inputLimit')&&!(Number.isSafeInteger(plan.inputLimit)&&plan.inputLimit>=65536&&plan.inputLimit<=4194304))
75
86
  stop(2,'inputLimit 需要 65536–4194304 的整数(字节)');
@@ -84,8 +95,12 @@ function recordedLearning(config,cwd){
84
95
  const archive=config.specsRoot??path.join(cwd,'docs','fixes');
85
96
  const state=path.join(archive,'.reviews','.execution',config.identity.runId,'state.json');
86
97
  const stored=readJson(state,'存档');
87
- const record=stored?.records?.find(row=>row.kind==='result'&&/^fix-learning-/.test(row.id));
88
- return record?.payload?.application??null;
98
+ let current=null;
99
+ for(const row of stored?.records??[]){
100
+ if(row.kind==='result'&&/^fix-learning-[1-9]\d*-[0-9a-f]{64}$/.test(row.id))current=row.payload;
101
+ else if(row.kind==='intent'&&row.id==='fix-rediagnosis-intent')current=row.payload.learning;
102
+ }
103
+ return current?.application??null;
89
104
  }
90
105
  function answerRound(config,operation,cwd){
91
106
  if(!['repair','author_tests'].includes(operation))return 1;
@@ -108,7 +123,7 @@ function roundAnswerName(root,kind,round){
108
123
  return `${kind}-a${round}.json`;
109
124
  }
110
125
 
111
- function preflight({operation,plan,paths}){
126
+ export function preflight({operation,plan,paths}){
112
127
  const config=readJson(paths.config,'宿主配置');
113
128
  if(config===undefined)stop(2,`宿主配置不存在: ${paths.config}`);
114
129
  if(path.resolve(plan.cwd)!==path.resolve(config.reproduction?.cwd??''))
@@ -119,11 +134,11 @@ function preflight({operation,plan,paths}){
119
134
  return value;};
120
135
  const answers=preflightAnswers(ASKS[operation]??[],kind=>{
121
136
  if(kind==='learning'){
122
- const recorded=plan.mode==='resume'?recordedLearning(config,plan.cwd):null;
137
+ const recorded=plan.mode==='resume'&&operation!=='rediagnose'?recordedLearning(config,plan.cwd):null;
123
138
  if(recorded){stderr(`恢复:复用存档里已记的学习记录(${recorded.status})`);return recorded;}
124
139
  return need('学习记录','learning.json');
125
140
  }
126
- if(kind==='diagnosis')return need('诊断','diagnosis.json');
141
+ if(kind==='diagnosis')return need('诊断',operation==='rediagnose'?'diagnosis-rediagnosis.json':'diagnosis.json');
127
142
  if(kind==='retrospective')return need('复盘','retrospective.json');
128
143
  const file=roundAnswerName(paths.answers,kind,round);
129
144
  const map=need(kind==='test-edits'?'测试内容':'修复内容',file);
@@ -192,9 +207,9 @@ function main(){
192
207
  const {answers,round}=preflight(loaded);
193
208
  const {operation,plan,paths}=loaded;
194
209
  driveHost({host:HOST,args:hostArgs(loaded).slice(1),cwd:path.resolve(plan.cwd),operation,
195
- request:{...(['abandon_step','abandon_review'].includes(operation)?{reason:plan.reason}:{}),
210
+ request:{...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),...(['abandon_step','abandon_review','rediagnose'].includes(operation)?{reason:plan.reason}:{}),
196
211
  ...(operation==='prepare_revision'&&Object.hasOwn(plan,'revisionTests')?{tests:plan.revisionTests}:{})},
197
212
  answers,paths:{...paths,round},answerFor});
198
213
  }
199
214
 
200
- main();
215
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))main();