@aibyzero/cm-workflow 0.16.4 → 0.16.5

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 (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -0,0 +1,400 @@
1
+ // QA re-run and timeout recovery through the real single-task host CLI.
2
+ // Fake codex reviewer and synthetic session answers only: no model, network,
3
+ // simulator or browser is used. Every log home is a temporary directory.
4
+ import test,{after} from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import {spawn,spawnSync} from 'node:child_process';
10
+ import {fileURLToPath} from 'node:url';
11
+ import {buildManifest} from './cm-spec-manifest.mjs';
12
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
13
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
14
+ import {findCmAiQaDecision,inspectCmAiQaResult,recordCmAiQaDecision,recordCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
15
+ import {readHostQaFixHandoff} from '../runtime/js/cm-ai/host-qa-fix.mjs';
16
+ import {inspectFixQaSource,qaFixIdentity} from '../runtime/js/cm-fix/qa-source.mjs';
17
+
18
+ const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-qa-rerun-home-'));
19
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
20
+ process.env.CM_WORKFLOW_HOME=path.join(home,'user');process.env.CM_WORKFLOW_LOG_HOME=path.join(home,'logs');
21
+ after(()=>{
22
+ for(const [key,value] of Object.entries(saved))if(value===undefined)delete process.env[key];else process.env[key]=value;
23
+ fs.rmSync(home,{recursive:true,force:true});
24
+ });
25
+ const cli=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
26
+ // The host CLI scenarios run real QA commands (host-check needs POSIX process
27
+ // groups and refuses win32) and POSIX fixtures (fake codex, sh shim).
28
+ const POSIX={skip:process.platform==='win32'?'host-check QA commands and the fixtures need POSIX':false};
29
+ const identity={repositoryId:'qa-rerun-fixture',runId:'qa-rerun-run',taskId:'T-001',attempt:1};
30
+ const simulator={kind:'app',carrier:'ios-simulator',target:'Fixture-iPhone',scope:'local'};
31
+ const service={kind:'service',carrier:'cli',target:'node',scope:'local'};
32
+ const lowRisk={scores:{scope:1,risk:1,accumulation:1,boundary:1},
33
+ changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
34
+
35
+ // The QA command stands in for xcodebuild/simulator scripts. It reads a mode
36
+ // file outside both roots, so switching the "environment" never touches the
37
+ // reviewed code or the specs.
38
+ const PROBE=`import fs from 'node:fs';
39
+ const mode=fs.readFileSync(new URL('../environment-mode',import.meta.url),'utf8').trim();
40
+ if(mode==='killed')process.kill(process.pid,'SIGKILL');
41
+ if(mode==='exit65')process.exit(65);
42
+ if(mode!=='ready')process.exit(1);
43
+ `;
44
+
45
+ function fixture(t,{browser=false}={}){
46
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-qa-rerun-')));
47
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
48
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
49
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
50
+ fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'# Fixture\n\n- [AC-001] tab bar shows four tabs\n');
51
+ fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Fixture\n');
52
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
53
+ if(browser)fs.writeFileSync(path.join(specsDir,feature,'test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases:[
54
+ {id:'TC-001',origin:'generated',kind:'browser',blocking:true,acIds:['AC-001'],taskIds:['T-001'],title:'four tabs',
55
+ preconditions:['UI test'],steps:['launch on simulator'],expected:['four tabs visible'],cleanup:[]}]}));
56
+ const manifest=buildManifest(specsDir);
57
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:manifest,
58
+ ...(browser?{testCases:manifest.filter(item=>item.path.endsWith('/test-cases.json'))}:{})}));
59
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
60
+ fs.writeFileSync(path.join(codeProject,'probe.mjs'),PROBE);
61
+ const definition={version:1,codeProject,specsDir,feature,identity,scope:['target.mjs'],requirements:['requirements.md']};
62
+ const config=path.join(root,'run.json');fs.writeFileSync(config,JSON.stringify(definition));
63
+ const bin=path.join(root,'bin');fs.mkdirSync(bin);
64
+ const fake=path.join(bin,'codex');
65
+ fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),fake);fs.chmodSync(fake,0o700);
66
+ const review={model:'fixture',disabledSkills:[],preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
67
+ config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture',disabledSkills:[],promptTransport:'stdin'})}};
68
+ const reviewFile=path.join(root,'review.json');fs.writeFileSync(reviewFile,JSON.stringify(review));
69
+ const log=path.join(specsDir,'运行日志.jsonl');
70
+ const f={root,codeProject,specsDir,feature,definition,config,reviewFile,log,
71
+ env:{...process.env,PATH:bin+path.delimiter+process.env.PATH,
72
+ CM_WORKFLOW_HOME:path.join(root,'user'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')},
73
+ environment:mode=>fs.writeFileSync(path.join(root,'environment-mode'),mode+'\n'),
74
+ rows:()=>fs.existsSync(log)?fs.readFileSync(log,'utf8').trim().split('\n').filter(Boolean).map(JSON.parse):[],
75
+ journal:()=>JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','.execution',identity.runId,'state.json'))),
76
+ workflow:(name,qa)=>{const file=path.join(root,`${name}.json`);
77
+ fs.writeFileSync(file,JSON.stringify({qa,documentationPaths:[],applicableAgentFiles:[]}));return file;}};
78
+ f.environment('ready');
79
+ return f;
80
+ }
81
+ const qaRows=f=>f.rows().filter(row=>row.event==='qa'&&row.node==='N6');
82
+ const testRuns=(f,phase)=>f.rows().filter(row=>row.event==='test_run'&&(phase===undefined||row.phase===phase));
83
+ const probeQa=(extra={})=>({commands:[{id:'probe',command:[process.execPath,'probe.mjs'],caseIds:[]}],environment:service,...extra});
84
+
85
+ function defaultAnswer(f,row){
86
+ if(row.kind==='develop'){
87
+ fs.writeFileSync(path.join(f.codeProject,'target.mjs'),'export const value = 1;\n');
88
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
89
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
90
+ }
91
+ if(row.kind==='check')return [{id:'syntax',command:[process.execPath,'--check','target.mjs'],outcome:'passed',exitCode:0,
92
+ evidence:'Synthetic node --check'}];
93
+ if(row.kind==='qa_assess')return lowRisk;
94
+ if(row.kind==='documentation_inspect')return {syncId:row.payload.syncId,identity:row.payload.identity,
95
+ packageDigest:row.payload.packageDigest,contextDigest:row.payload.contextDigest,status:'completed',
96
+ reason:'No documentation path configured',at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
97
+ throw Error(`unexpected host request ${row.kind}`);
98
+ }
99
+
100
+ // A python3 shim that refuses only the N6 test_run/start append, so the real host
101
+ // leaves exactly the durable prefix a crash right before that append leaves.
102
+ // POSIX only: callers are skipped on win32 before this runs.
103
+ function failingStartShim(f){
104
+ const lookup=spawnSync('/bin/sh',['-c','command -v python3'],{encoding:'utf8'});
105
+ assert.equal(lookup.status,0,'python3 must be on PATH for the interruption fixture');
106
+ const dir=path.join(f.root,'shim');fs.mkdirSync(dir,{recursive:true});
107
+ fs.writeFileSync(path.join(dir,'python3'),
108
+ `#!/bin/sh\ncase " $* " in *" --event test_run --phase start "*) exit 3;; esac\nexec ${JSON.stringify(lookup.stdout.trim())} "$@"\n`,{mode:0o700});
109
+ return dir;
110
+ }
111
+
112
+ // answers[kind] may be a value, a function(row) or 'IGNORE' (never answered).
113
+ function launch(f,{mode='resume',operation='advance',workflow=null,extra=[],answers={},review=true,pathPrefix=null}={}){
114
+ return new Promise((resolve,reject)=>{
115
+ const args=['serve','--config',f.config,'--mode',mode,'--host-context','session-A','--allow-development',
116
+ '--review-config',f.reviewFile,...(review?['--allow-review-attempt','1']:[]),
117
+ ...(workflow?['--workflow-config',workflow,'--allow-qa']:[]),...extra];
118
+ const env=pathPrefix?{...f.env,PATH:pathPrefix+path.delimiter+f.env.PATH}:f.env;
119
+ const child=spawn(process.execPath,[cli,...args],{env,stdio:['pipe','pipe','pipe']});
120
+ let buffer='',stderr='',sessionId=null;const rows=[],asked=[];
121
+ const timer=setTimeout(()=>{child.kill('SIGKILL');reject(Error(`host timeout: ${stderr}`));},60000);
122
+ const send=value=>{try{child.stdin.write(JSON.stringify(value)+'\n');}catch{}};
123
+ child.on('error',reject);child.stderr.on('data',chunk=>stderr+=chunk);
124
+ child.stdout.on('data',chunk=>{
125
+ buffer+=chunk;let index;
126
+ while((index=buffer.indexOf('\n'))>=0){
127
+ const line=buffer.slice(0,index);buffer=buffer.slice(index+1);if(!line)continue;
128
+ let row;try{row=JSON.parse(line);}catch{continue;}
129
+ rows.push(row);
130
+ if(row.type==='host_ready'){sessionId=row.sessionId;
131
+ send({version:1,operation,requestId:'request',identity});}
132
+ if(row.type==='host_request'){
133
+ asked.push(row.kind);
134
+ const configured=answers[row.kind];
135
+ if(configured==='IGNORE')continue;
136
+ let result;
137
+ try{result=configured===undefined?defaultAnswer(f,row):typeof configured==='function'?configured(row):configured;}
138
+ catch(error){child.kill('SIGKILL');clearTimeout(timer);reject(error);return;}
139
+ send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
140
+ }
141
+ if(row.requestId==='request'&&(row.result||row.error))send({type:'host_close',sessionId});
142
+ }
143
+ });
144
+ child.once('close',code=>{clearTimeout(timer);
145
+ resolve({code,stderr,asked,result:rows.find(row=>row.requestId==='request')?.result??null});});
146
+ });
147
+ }
148
+ const done=run=>{assert.equal(run.code,0,run.stderr);assert(run.result,run.stderr);return run.result;};
149
+
150
+ test('#7 a qa_assess answer window miss is a retryable rejection, never a durable BLOCKED decision',POSIX,async t=>{
151
+ const f=fixture(t),workflow=f.workflow('workflow',probeQa({timeoutMs:1500}));
152
+ const first=done(await launch(f,{mode:'create',workflow,answers:{qa_assess:'IGNORE'}}));
153
+ assert.equal(first.outcome,'rejected',JSON.stringify(first));assert.equal(first.code,'qa_decision_timeout');
154
+ assert.equal(qaRows(f).length,0,'a transport timeout must not write an N6 decision');
155
+ const status=done(await launch(f,{operation:'status',workflow}));
156
+ assert.equal(status.state,'fixture_completed');assert.equal(status.code,null);
157
+ // The same run, same configuration: the session now answers and N6 continues.
158
+ const resumed=await launch(f,{workflow});
159
+ const result=done(resumed);
160
+ assert.equal(result.state,'run_done',JSON.stringify(result));
161
+ assert.deepEqual(resumed.asked.filter(kind=>kind==='qa_assess'),['qa_assess']);
162
+ assert.deepEqual(qaRows(f).map(row=>[row.status,row.reason]),[['triggered','feature_complete']]);
163
+ assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['PASS']);
164
+ });
165
+
166
+ // Writes exactly the row an older host wrote when qa_assess timed out:
167
+ // same writer, deterministic decision id and no supersession link.
168
+ function legacyTimeoutDecision(f,packageDigest){
169
+ if(qaRows(f).length)return;
170
+ recordCmAiQaDecision({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,packageDigest,
171
+ logHome:path.join(f.specsDir,'.reviews','host-log-mirror'),
172
+ decision:{decisionId:`qa-${digest({identity,packageDigest}).slice(0,48)}`,identity,packageDigest,
173
+ status:'blocked',reason:'host_request_timeout',score:null,at:'2026-09-28T10:48:11Z'}});
174
+ }
175
+
176
+ test('#7 a legacy 阻塞:host_request_timeout decision stays blocked unless --rerun-blocked-qa re-asks qa_assess once',POSIX,async t=>{
177
+ const f=fixture(t),workflow=f.workflow('workflow',probeQa({timeoutMs:1500}));
178
+ done(await launch(f,{mode:'create',workflow,answers:{qa_assess:'IGNORE'}}));
179
+ const status=done(await launch(f,{operation:'status',workflow}));
180
+ legacyTimeoutDecision(f,status.packageDigest);
181
+ const [legacy]=qaRows(f);assert.equal(legacy.status,'blocked');assert.equal(legacy.reason,'host_request_timeout');
182
+ const logBefore=fs.readFileSync(f.log),journalBefore=f.journal();
183
+ // Compatibility: without the explicit flag the recorded decision is replayed as before.
184
+ const plain=await launch(f,{workflow});
185
+ const blocked=done(plain);
186
+ assert.equal(blocked.code,'qa_blocked');assert.equal(blocked.pendingAction,'none');
187
+ assert.equal(blocked.reason,'host_request_timeout');assert.deepEqual(plain.asked,[]);
188
+ assert(fs.readFileSync(f.log).equals(logBefore));assert.deepEqual(f.journal(),journalBefore);
189
+ // Explicit, audited recovery: the recorded decision is superseded, not rewritten.
190
+ const recovery=await launch(f,{workflow,extra:['--rerun-blocked-qa']});
191
+ const recovered=done(recovery);
192
+ assert.equal(recovered.state,'run_done',JSON.stringify(recovered));
193
+ assert.deepEqual(recovery.asked.filter(kind=>kind==='qa_assess'),['qa_assess']);
194
+ assert(fs.readFileSync(f.log).subarray(0,logBefore.length).equals(logBefore),'history bytes are kept');
195
+ const decisions=qaRows(f);
196
+ assert.deepEqual(decisions.map(row=>[row.status,row.reason]),[['blocked','host_request_timeout'],['triggered','feature_complete']]);
197
+ assert.equal(decisions[1].previous_decision_id,legacy.decision_id);assert.notEqual(decisions[1].decision_id,legacy.decision_id);
198
+ assert.deepEqual(testRuns(f,'start').map(row=>[row.attempt,row.qa_decision_id]),[[1,decisions[1].decision_id]]);
199
+ assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['PASS']);
200
+ // Replays read the effective decision; the flag cannot supersede a second time.
201
+ for(const extra of [[],['--rerun-blocked-qa']]){
202
+ const again=await launch(f,{workflow,extra,answers:{qa_assess:()=>assert.fail('qa_assess must not be re-asked')}});
203
+ assert.equal(again.code,0,again.stderr);assert.equal(qaRows(f).length,2);
204
+ }
205
+ assert.deepEqual(f.journal().records.slice(0,journalBefore.records.length),journalBefore.records);
206
+ });
207
+
208
+ test('#7 recovery interrupted after the replacement decision, before QA start, resumes with the same command',POSIX,async t=>{
209
+ const f=fixture(t),workflow=f.workflow('workflow',probeQa({timeoutMs:1500}));
210
+ done(await launch(f,{mode:'create',workflow,answers:{qa_assess:'IGNORE'}}));
211
+ legacyTimeoutDecision(f,done(await launch(f,{operation:'status',workflow})).packageDigest);
212
+ const interrupted=done(await launch(f,{workflow,extra:['--rerun-blocked-qa'],pathPrefix:failingStartShim(f)}));
213
+ assert.equal(interrupted.outcome,'rejected',JSON.stringify(interrupted));assert.equal(interrupted.code,'qa_log_failed');
214
+ const prefix=qaRows(f);
215
+ assert.deepEqual(prefix.map(row=>row.status),['blocked','triggered']);assert.equal(testRuns(f).length,0);
216
+ // The same authorized command finishes the recovery as the ordinary first
217
+ // round; qa_assess is not asked again. Here that round meets a killed command.
218
+ const noAssess={qa_assess:()=>assert.fail('qa_assess must not be re-asked')};
219
+ f.environment('killed');
220
+ const resumed=done(await launch(f,{workflow,extra:['--rerun-blocked-qa'],answers:noAssess}));
221
+ assert.equal(resumed.code,'qa_result_blocked',JSON.stringify(resumed));
222
+ assert.deepEqual(qaRows(f).map(row=>row.decision_id),prefix.map(row=>row.decision_id));
223
+ assert.deepEqual(testRuns(f,'start').map(row=>[row.attempt,row.qa_decision_id,row.previous_test_run_id]),[[1,prefix[1].decision_id,undefined]]);
224
+ // Once a round exists under the replacement, the flag is an ordinary rerun again.
225
+ f.environment('ready');
226
+ const result=done(await launch(f,{workflow,extra:['--rerun-blocked-qa'],answers:noAssess}));
227
+ assert.equal(result.state,'run_done',JSON.stringify(result));
228
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2]);
229
+ assert.deepEqual(testRuns(f,'superseded').map(row=>row.reason),['host_evidence_problem']);
230
+ });
231
+
232
+ test('#13 a host-declared BLOCKED simulator case re-runs on unchanged code with --rerun-blocked-qa',POSIX,async t=>{
233
+ const f=fixture(t,{browser:true}),workflow=f.workflow('workflow',probeQa({environment:simulator}));
234
+ const evidence=path.join(f.specsDir,'.reviews','tc-001.png');
235
+ const down=row=>({verdict:'BLOCKED',evidence:[],environment:row.payload.environment,cleanup:'not_needed'});
236
+ const up=row=>{fs.writeFileSync(evidence,'png');return {verdict:'PASS',evidence:[evidence],environment:row.payload.environment,cleanup:'not_needed'};};
237
+ const first=done(await launch(f,{mode:'create',workflow,extra:['--browser-qa','available'],answers:{qa_browser:down}}));
238
+ assert.equal(first.code,'qa_result_blocked',JSON.stringify(first));
239
+ const rerun=await launch(f,{workflow,extra:['--browser-qa','available','--rerun-blocked-qa'],answers:{qa_browser:up}});
240
+ const result=done(rerun);
241
+ assert.equal(result.state,'run_done',JSON.stringify(result));
242
+ const superseded=testRuns(f,'superseded');
243
+ assert.equal(superseded.length,1);assert.equal(superseded[0].reason,'host_evidence_problem');
244
+ assert.deepEqual(superseded[0].blocked_cases,['TC-001']);
245
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2]);
246
+ assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['BLOCKED','PASS']);
247
+ });
248
+
249
+ test('#13 an unavailable QA command (killed, no exit code) re-runs; the round budget still caps at three',POSIX,async t=>{
250
+ const f=fixture(t),workflow=f.workflow('workflow',probeQa());
251
+ f.environment('killed');
252
+ const first=done(await launch(f,{mode:'create',workflow}));
253
+ assert.equal(first.code,'qa_result_blocked',JSON.stringify(first));
254
+ for(let round=2;round<=3;round++){
255
+ const again=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
256
+ assert.equal(again.code,'qa_result_blocked',JSON.stringify(again));
257
+ }
258
+ const exhausted=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
259
+ assert.equal(exhausted.code,'qa_round_invalid',JSON.stringify(exhausted));
260
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2,3]);
261
+ assert.deepEqual(testRuns(f,'superseded').map(row=>row.blocked_cases),[['probe'],['probe']]);
262
+ });
263
+
264
+ test('#13 the environment recovers: an unavailable command reaches run_done on the same approved code',POSIX,async t=>{
265
+ const f=fixture(t),workflow=f.workflow('workflow',probeQa());
266
+ f.environment('killed');
267
+ assert.equal(done(await launch(f,{mode:'create',workflow})).code,'qa_result_blocked');
268
+ f.environment('ready');
269
+ const result=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
270
+ assert.equal(result.state,'run_done',JSON.stringify(result));
271
+ assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['BLOCKED','PASS']);
272
+ });
273
+
274
+ test('#13 a non-zero QA exit stays a product FAIL; only an explicit, recorded operator declaration re-runs it',POSIX,async t=>{
275
+ const f=fixture(t),workflow=f.workflow('workflow',probeQa());
276
+ f.environment('exit65');
277
+ const first=done(await launch(f,{mode:'create',workflow}));
278
+ assert.equal(first.code,'qa_failed',JSON.stringify(first));
279
+ const logBefore=fs.readFileSync(f.log);
280
+ const refused=done(await launch(f,{workflow,extra:['--rerun-blocked-qa']}));
281
+ assert.equal(refused.code,'qa_rerun_not_blocked_by_evidence');assert(fs.readFileSync(f.log).equals(logBefore));
282
+ const orphan=await launch(f,{workflow,extra:['--qa-environment-failure','simulator runtime was missing']});
283
+ assert.equal(orphan.code,1);assert.match(orphan.stderr,/qa_recovery_authorization_required/);
284
+ // The host refuses the orphan declaration before it even reads the run definition.
285
+ const early=await launch({...f,config:path.join(f.root,'missing-run.json')},{workflow,extra:['--qa-environment-failure','x']});
286
+ assert.equal(early.code,1);assert.match(early.stderr,/qa_recovery_authorization_required/);
287
+ f.environment('ready');
288
+ const declared=done(await launch(f,{workflow,extra:['--rerun-blocked-qa','--qa-environment-failure','simulator runtime was missing']}));
289
+ assert.equal(declared.state,'run_done',JSON.stringify(declared));
290
+ const [superseded]=testRuns(f,'superseded');
291
+ assert.equal(superseded.reason,'declared_environment_failure');
292
+ assert.equal(superseded.environment_failure_reason,'simulator runtime was missing');
293
+ assert.deepEqual(superseded.failed_cases,['probe']);assert.deepEqual(superseded.blocked_cases,[]);
294
+ assert.deepEqual(testRuns(f,'start').map(row=>row.attempt),[1,2]);
295
+ assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['FAIL','PASS']);
296
+ });
297
+
298
+ test('#26 a wrong QA workflow config is revised before any QA round, without consuming a round',POSIX,async t=>{
299
+ const f=fixture(t);
300
+ const wrong=f.workflow('workflow-old',{commands:[{id:'probe',command:[process.execPath,'-e','process.exit(3)'],caseIds:[]}],environment:service});
301
+ const fixed=f.workflow('workflow-new',probeQa());
302
+ const waiting=done(await launch(f,{mode:'create',workflow:wrong,review:false}));
303
+ assert.equal(waiting.state,'awaiting_review',JSON.stringify(waiting));
304
+ const before=f.journal();
305
+ const drift=await launch(f,{workflow:fixed,review:false});
306
+ assert.equal(drift.code,1);assert.match(drift.stderr,/fingerprint_mismatch/);
307
+ const revise=['--revise-qa-config',wrong,'--qa-config-revision-reason','QA 命令写错,运行前修正'];
308
+ const revised=await launch(f,{workflow:fixed,extra:revise});
309
+ const result=done(revised);
310
+ assert.equal(result.state,'run_done',JSON.stringify(result));
311
+ const records=f.journal().records.filter(row=>row.payload.type==='qa-config-revised');
312
+ assert.equal(records.length,1);
313
+ assert.equal(records[0].payload.record.qaRound,0);assert.equal(records[0].payload.record.testRunId,null);
314
+ assert.deepEqual(f.journal().records.slice(0,before.records.length),before.records);
315
+ assert.equal(f.rows().filter(row=>row.event==='decision'&&row.phase==='qa_config_revise').length,1);
316
+ assert.deepEqual(testRuns(f,'start').map(row=>[row.attempt,row.previous_test_run_id]),[[1,undefined]]);
317
+ assert.equal(testRuns(f,'superseded').length,0);
318
+ assert.deepEqual(testRuns(f,'complete').map(row=>row.result),['PASS']);
319
+ // The chain now binds the corrected file; the old one no longer resumes.
320
+ assert.equal((await launch(f,{workflow:fixed,operation:'status'})).code,0);
321
+ const old=await launch(f,{workflow:wrong,operation:'status'});
322
+ assert.equal(old.code,1);assert.match(old.stderr,/fingerprint_mismatch/);
323
+ });
324
+
325
+ test('#7 decision chain: one linked supersession of a timeout decision, read by N6 and cm-fix alike',t=>{
326
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-qa-chain-')));
327
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
328
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),logHome=path.join(root,'logs');
329
+ fs.mkdirSync(path.join(specsDir,'.reviews'),{recursive:true});fs.mkdirSync(codeProject);
330
+ const packageDigest='a'.repeat(64),feature='1.work',binding={specsDir,codeProject,feature,identity,packageDigest,logHome};
331
+ const query={specsDir,feature,identity,packageDigest},log=path.join(specsDir,'运行日志.jsonl');
332
+ const decision=(decisionId,status,reason,at)=>({decisionId,identity,packageDigest,status,reason,score:null,at});
333
+ const legacy=decision('qa-legacy','blocked','host_request_timeout','2026-09-28T10:48:11Z');
334
+ assert.throws(()=>recordCmAiQaDecision({...binding,previousDecisionId:'qa-legacy',
335
+ decision:decision('qa-fresh','triggered','feature_complete','2026-09-28T11:00:00Z')}),{code:'qa_decision_conflict'});
336
+ recordCmAiQaDecision({...binding,decision:legacy});
337
+ const onlyLegacy=fs.readFileSync(log);
338
+ // A link must name a recorded decision, and an identical row is not a supersession of itself.
339
+ assert.throws(()=>recordCmAiQaDecision({...binding,packageDigest:'d'.repeat(64),previousDecisionId:'qa-legacy',
340
+ decision:{...legacy,decisionId:'qa-d',packageDigest:'d'.repeat(64)}}),{code:'qa_decision_conflict'});
341
+ assert.throws(()=>recordCmAiQaDecision({...binding,previousDecisionId:'qa-legacy',decision:legacy}),{code:'qa_decision_conflict'});
342
+ // Only a timeout decision is supersedable, only by a linked distinct decision.
343
+ assert.throws(()=>recordCmAiQaDecision({...binding,previousDecisionId:'qa-legacy',decision:{...legacy,at:'2026-09-28T11:00:00Z'}}),
344
+ {code:'qa_decision_conflict'});
345
+ assert.throws(()=>recordCmAiQaDecision({...binding,previousDecisionId:'qa-other',
346
+ decision:decision('qa-fresh','triggered','feature_complete','2026-09-28T11:00:00Z')}),{code:'qa_decision_conflict'});
347
+ assert.deepEqual(fs.readFileSync(log),onlyLegacy);
348
+ // A decision that is not a timeout block is never superseded, even when named exactly.
349
+ const other={...binding,packageDigest:'b'.repeat(64)},otherDecision={decisionId:'qa-other-package',identity,
350
+ packageDigest:'b'.repeat(64),status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T10:00:00Z'};
351
+ recordCmAiQaDecision({...other,decision:otherDecision});
352
+ const withOther=fs.readFileSync(log);
353
+ assert.throws(()=>recordCmAiQaDecision({...other,previousDecisionId:'qa-other-package',
354
+ decision:{...otherDecision,decisionId:'qa-other-fresh',at:'2026-09-28T11:00:00Z'}}),{code:'qa_decision_conflict'});
355
+ assert.deepEqual(fs.readFileSync(log),withOther);
356
+ // Only once: even a second timeout block (from a custom provider) is final.
357
+ const timeoutTwice={...binding,packageDigest:'c'.repeat(64)},block=(decisionId,at)=>({decisionId,identity,
358
+ packageDigest:'c'.repeat(64),status:'blocked',reason:'host_request_timeout',score:null,at});
359
+ recordCmAiQaDecision({...timeoutTwice,decision:block('qa-c1','2026-09-28T10:00:00Z')});
360
+ recordCmAiQaDecision({...timeoutTwice,previousDecisionId:'qa-c1',decision:block('qa-c2','2026-09-28T10:10:00Z')});
361
+ const twice=fs.readFileSync(log);
362
+ assert.throws(()=>recordCmAiQaDecision({...timeoutTwice,previousDecisionId:'qa-c2',
363
+ decision:{...block('qa-c3','2026-09-28T10:20:00Z'),status:'triggered',reason:'feature_complete'}}),{code:'qa_decision_conflict'});
364
+ assert.deepEqual(fs.readFileSync(log),twice);
365
+ const fresh=decision('qa-fresh','triggered','feature_complete','2026-09-28T11:00:00Z');
366
+ recordCmAiQaDecision({...binding,previousDecisionId:'qa-legacy',decision:fresh});
367
+ recordCmAiQaDecision({...binding,previousDecisionId:'qa-legacy',decision:fresh});
368
+ const chained=fs.readFileSync(log);
369
+ assert.equal(findCmAiQaDecision(query).decisionId,'qa-fresh');
370
+ assert.throws(()=>recordCmAiQaDecision({...binding,previousDecisionId:'qa-fresh',
371
+ decision:{...decision('qa-third','skipped','risk_score_below_threshold','2026-09-28T12:00:00Z'),score:4}}),{code:'qa_decision_conflict'});
372
+ assert.deepEqual(fs.readFileSync(log),chained);
373
+ // The QA round and a cm-fix child bind the effective decision.
374
+ const report=path.join(specsDir,'.reviews','qa-failure.md');fs.writeFileSync(report,'Synthetic QA FAIL');
375
+ const qa={...binding,mode:'commands',caseCount:1,testRunId:'qa-round-1'};
376
+ recordCmAiQaRun({...qa,phase:'start'});
377
+ recordCmAiQaRun({...qa,phase:'complete',result:{result:'FAIL',passed:0,failed:1,blocked:0,report}});
378
+ assert.equal(inspectCmAiQaResult({...query,testRunId:'qa-round-1'}).status,'failed');
379
+ assert.equal(fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse).find(row=>row.phase==='start').qa_decision_id,'qa-fresh');
380
+ const handoff=readHostQaFixHandoff({...query,codeProject,testRunId:'qa-round-1'});
381
+ const qaSource={feature,identity,packageDigest,testRunId:'qa-round-1',handoffDigest:handoff.handoffDigest};
382
+ const configuration={qaSource,reproduction:{cwd:codeProject}};
383
+ assert.equal(inspectFixQaSource({specsRoot:specsDir,identity:qaFixIdentity(qaSource),configuration}).handoffDigest,handoff.handoffDigest);
384
+ // Forged chains fail closed in every reader.
385
+ const rows=fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
386
+ const at=rows.findIndex(row=>row.decision_id==='qa-fresh');
387
+ for(const [label,forge] of [
388
+ ['unlinked',list=>{delete list[at].previous_decision_id;}],
389
+ ['orphan successor',list=>{list.splice(list.findIndex(row=>row.decision_id==='qa-legacy'),1);}],
390
+ ['reused id',list=>{Object.assign(list[at],{decision_id:'qa-legacy'});}],
391
+ ['non-timeout predecessor',list=>{list.find(row=>row.decision_id==='qa-legacy').reason='feature_complete';}],
392
+ ['third decision',list=>{list.splice(at+1,0,{...list[at],decision_id:'qa-third',previous_decision_id:'qa-fresh'});}],
393
+ ]){
394
+ const copy=structuredClone(rows);forge(copy);
395
+ fs.writeFileSync(log,copy.map(row=>JSON.stringify(row)).join('\n')+'\n');
396
+ assert.throws(()=>findCmAiQaDecision(query),{code:'context_not_ready'},label);
397
+ assert.throws(()=>inspectCmAiQaResult({...query,testRunId:'qa-round-1'}),{code:'qa_not_triggered'},label);
398
+ assert.throws(()=>inspectFixQaSource({specsRoot:specsDir,identity:qaFixIdentity(qaSource),configuration}),label);
399
+ }
400
+ });
@@ -0,0 +1,90 @@
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 {buildManifest} from './cm-spec-manifest.mjs';
7
+ import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
8
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
9
+ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
10
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
12
+ import {writeHandoff} from '../experiments/js-orchestration/native-gate-fixture.mjs';
13
+
14
+ const identity={repositoryId:'fixture',runId:'review-drift',taskId:'T-001',attempt:1};
15
+ const terminal=(request,result)=>({version:1,invocationId:request.invocationId,
16
+ contextId:request.contextId,provider:request.provider,effectiveModel:'fixture',
17
+ status:'succeeded',accepted:true,result});
18
+
19
+ for(const [name,change,expected] of [
20
+ ['specification',({design})=>fs.appendFileSync(design,'changed during review\n'),'spec_drift'],
21
+ ['code root',({code})=>fs.writeFileSync(path.join(code,'stray.js'),'changed during review\n'),'review_package_changed'],
22
+ ['specification and code root',({design,code})=>{
23
+ fs.writeFileSync(path.join(code,'stray.js'),'changed during review\n');
24
+ fs.appendFileSync(design,'changed during review\n');
25
+ },'spec_drift'],
26
+ ])test(`review-time ${name} drift reports ${expected}`,async t=>{
27
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-drift-')));
28
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
29
+ const code=path.join(root,'code'),specsRoot=path.join(root,'specs'),feature='1.fixture';
30
+ fs.mkdirSync(code);fs.mkdirSync(path.join(specsRoot,feature),{recursive:true});
31
+ fs.writeFileSync(path.join(code,'code.js'),'old\n');
32
+ fs.writeFileSync(path.join(specsRoot,feature,'requirements.md'),'# Requirements\n- [ ] [AC-001] Fixture\n');
33
+ const design=path.join(specsRoot,feature,'design.md');fs.writeFileSync(design,'# Design\n');
34
+ fs.writeFileSync(path.join(specsRoot,feature,'tasks.md'),'- [ ] T-001: implement fixture\n');
35
+ fs.writeFileSync(path.join(specsRoot,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],
36
+ specFiles:buildManifest(specsRoot)}));
37
+ const reviewsDir=path.join(specsRoot,'.reviews');fs.mkdirSync(reviewsDir);
38
+ const owner={tasksPath:path.join(specsRoot,feature,'tasks.md'),feature,specsRoot,
39
+ identity:{repositoryId:identity.repositoryId,runId:identity.runId},
40
+ fingerprints:{workflow:digest('review-drift'),config:digest('fixture'),inputs:digest('fixture')}};
41
+ let store=openTaskExecutionStore({...owner,create:true});
42
+ t.after(()=>store.close());
43
+ const learningFiles=[],learningDigest=digest({version:1,feature,identity,files:learningFiles});
44
+ const learningInput={version:1,workflow:'cm-ai',phase:'task_learning_input',feature,identity,learningDigest,learningFiles};
45
+ const handoffs=[1,2].map(attempt=>path.join(reviewsDir,
46
+ `${feature}-${identity.taskId}-a${attempt}-handoff.json`));
47
+ let reviews=0;
48
+ const runner=createTaskRunner({root:code,identity,scope:['code.js'],requirements:[],
49
+ specification:{specsRoot,feature},taskLearning:{feature},excludedContexts:['main'],timeoutMs:1000,
50
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:request=>{
51
+ fs.writeFileSync(path.join(code,'code.js'),'new\n');
52
+ writeHandoff(handoffs[0],code,['code.js']);
53
+ return terminal(request,{outcome:'implemented',
54
+ application:createCmAiTaskLearningApplication({feature,identity,learningDigest,status:'no_relevant_lesson',note:null}),
55
+ retrospective:createCmAiTaskLearningRetrospective({feature,identity,learningDigest,
56
+ status:'no_new_lesson',candidates:[],reason:null})});
57
+ }},
58
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
59
+ contexts:['review-one','review-two'],run:request=>{
60
+ reviews++;change({code,design});
61
+ return terminal(request,{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
62
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Fixture review'});
63
+ }}],
64
+ check:()=>[{id:'unit',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}],
65
+ taskCompletion:{reviewsDir,handoffs},
66
+ persistence:{store,mode:'create',version:2}});
67
+ const effect=kind=>({version:1,id:kind,identity,kind,...(kind==='develop'?{learningInput}:{})});
68
+ assert.equal((await runner.executeEffect(effect('develop'))).state,'awaiting_review');
69
+ const result=await runner.executeEffect(effect('review'));
70
+ assert.equal(reviews,1);
71
+ assert.equal(result.state,'blocked');assert.equal(result.code,expected);
72
+ assert.equal(result.receipts.length,expected==='spec_drift'?0:1);
73
+ if(expected==='review_package_changed')assert.equal(result.receipt.result.verdict,'approved');
74
+ store.close();store=openTaskExecutionStore({...owner,create:false});
75
+ const resumed=createTaskRunner({root:code,identity,scope:['code.js'],requirements:[],
76
+ specification:{specsRoot,feature},taskLearning:{feature},excludedContexts:['main'],timeoutMs:1000,
77
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:()=>{throw new Error('must not redevelop');}},
78
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
79
+ contexts:['review-one','review-two'],run:()=>{throw new Error('must not rereview');}}],
80
+ check:()=>[{id:'unit',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}],
81
+ taskCompletion:{reviewsDir,handoffs},persistence:{store,mode:'resume',version:2}});
82
+ assert.equal(resumed.status().code,expected);
83
+ if(expected==='spec_drift'){
84
+ fs.writeFileSync(design,'# Design\n');
85
+ assert.equal(resumed.status().code,'spec_drift');
86
+ }else{
87
+ fs.unlinkSync(path.join(code,'stray.js'));
88
+ assert.equal(resumed.status().state,'approved');
89
+ }
90
+ });