@aibyzero/cm-workflow 0.13.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +28 -2
  4. package/VERSION +1 -1
  5. package/docs/installation.md +18 -3
  6. package/docs/js-workflow-control.md +2 -0
  7. package/docs/user-guide.md +16 -0
  8. package/install.ps1 +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +1 -0
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -22
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +4 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +40 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +103 -23
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -4
  16. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +5 -2
  17. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  18. package/runtime/js/cm-ai/developer-adapter.mjs +17 -5
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +7 -2
  20. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  21. package/runtime/js/cm-ai/execution-store.mjs +25 -5
  22. package/runtime/js/cm-ai/host-check.mjs +20 -1
  23. package/runtime/js/cm-ai/host-conversation-execution.mjs +5 -4
  24. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +43 -21
  26. package/runtime/js/cm-ai/host-qa-policy.mjs +3 -1
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +41 -3
  28. package/runtime/js/cm-ai/task-runner.mjs +1 -0
  29. package/runtime/js/cm-ai/worker-claude-developer.mjs +2 -1
  30. package/runtime/js/cm-fix/cause-package.mjs +3 -1
  31. package/runtime/js/cm-fix/dossier.mjs +7 -2
  32. package/runtime/js/cm-fix/reproduce.mjs +26 -5
  33. package/runtime/js/cm-init/draft-generation.mjs +3 -2
  34. package/runtime/js/cm-init/draft-inspection.mjs +17 -3
  35. package/runtime/js/cm-init/review-evidence.mjs +1 -1
  36. package/runtime/js/cm-prd/summary.mjs +6 -8
  37. package/runtime/js/cm-security/finalize.mjs +164 -0
  38. package/runtime/js/specs-status.mjs +66 -0
  39. package/scripts/cm-ai-admission.mjs +46 -7
  40. package/scripts/cm-ai-admission.test.mjs +50 -0
  41. package/scripts/cm-ai-batch-host.mjs +72 -10
  42. package/scripts/cm-ai-batch-host.test.mjs +128 -4
  43. package/scripts/cm-ai-batch-run.mjs +351 -17
  44. package/scripts/cm-ai-batch-run.test.mjs +190 -13
  45. package/scripts/cm-ai-bootstrap.test.mjs +10 -3
  46. package/scripts/cm-ai-host.mjs +38 -21
  47. package/scripts/cm-ai-host.test.mjs +75 -5
  48. package/scripts/cm-ai-multi-root.test.mjs +7 -1
  49. package/scripts/cm-ai-nested-execution.test.mjs +8 -2
  50. package/scripts/cm-ai-run.mjs +25 -15
  51. package/scripts/cm-ai-run.test.mjs +48 -0
  52. package/scripts/cm-blocked-reason.test.mjs +104 -0
  53. package/scripts/cm-capability-gate.test.mjs +179 -0
  54. package/scripts/cm-check-host.test.mjs +7 -1
  55. package/scripts/cm-codex-developer-adapter.test.mjs +70 -0
  56. package/scripts/cm-fix-cause-package.test.mjs +18 -1
  57. package/scripts/cm-fix-execution.test.mjs +31 -0
  58. package/scripts/cm-fix-host-review.test.mjs +9 -2
  59. package/scripts/cm-fix-host.test.mjs +2 -1
  60. package/scripts/cm-fix-observation-dossier.test.mjs +2 -0
  61. package/scripts/cm-fix-qa-source.test.mjs +1 -3
  62. package/scripts/cm-fix-reproduce.test.mjs +53 -2
  63. package/scripts/cm-fix-review-recovery.test.mjs +4 -3
  64. package/scripts/cm-host-check.test.mjs +22 -0
  65. package/scripts/cm-host-qa-executor.test.mjs +302 -3
  66. package/scripts/cm-host-qa-policy.test.mjs +34 -0
  67. package/scripts/cm-init-draft-generation.test.mjs +24 -3
  68. package/scripts/cm-init-draft-inspection.test.mjs +80 -0
  69. package/scripts/cm-init-host.mjs +2 -2
  70. package/scripts/cm-init-host.test.mjs +3 -1
  71. package/scripts/cm-init-session.test.mjs +37 -0
  72. package/scripts/cm-log-event.mjs +28 -7
  73. package/scripts/cm-prd-completion.test.mjs +7 -1
  74. package/scripts/cm-prd-design-phase.test.mjs +2 -1
  75. package/scripts/cm-prd-host.test.mjs +3 -2
  76. package/scripts/cm-prd-session-recovery.test.mjs +5 -4
  77. package/scripts/cm-runtime-i18n.mjs +32 -0
  78. package/scripts/cm-runtime-install.mjs +49 -23
  79. package/scripts/cm-runtime.mjs +45 -17
  80. package/scripts/cm-runtime.test.mjs +101 -0
  81. package/scripts/cm-security.mjs +12 -4
  82. package/scripts/cm-security.test.mjs +109 -0
  83. package/scripts/cm-specs-status.test.mjs +130 -0
  84. package/scripts/cm-workflow-config.mjs +4 -0
  85. package/scripts/test-shell-compat.sh +0 -0
  86. package/skills/cm-ai/references/N1-init.md +20 -15
  87. package/skills/cm-ai/references/N6-qa-eval.md +9 -4
  88. package/skills/cm-ai/references/js-host.md +10 -0
  89. package/skills/cm-fix/SKILL.md +5 -4
  90. package/skills/cm-fix/references/js-host.md +13 -0
  91. package/skills/cm-idea/SKILL.md +2 -0
  92. package/skills/cm-init/references/runtime-declaration.md +2 -0
  93. package/skills/cm-prd/SKILL.md +9 -8
  94. package/skills/cm-prd/references/spec-self-check.md +1 -0
  95. package/skills/cm-runtime/SKILL.md +23 -2
  96. package/skills/cm-security/SKILL.md +11 -6
  97. package/skills/cm-security/references/scan-contract.md +45 -1
@@ -3,8 +3,10 @@ import test from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {createParallelMemberQaDecisionProvider} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
6
8
  import path from 'node:path';
7
- import {createCmAiBatch} from './cm-ai-batch-run.mjs';
9
+ import {createCmAiBatch,taskCommitArgs} from './cm-ai-batch-run.mjs';
8
10
  import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
9
11
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
10
12
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
@@ -12,27 +14,99 @@ import {createHostQaDecisionProvider} from '../runtime/js/cm-ai/host-qa-policy.m
12
14
  import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
13
15
 
14
16
  for(const mode of ['continuous','qa-resume','failed-qa','cancel','learning','policy','executor'])
15
- test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async()=>{
17
+ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,()=>batchFixture(mode));
18
+
19
+ for(const mode of ['parallel','parallel-retry','parallel-conflict','parallel-resume'])
20
+ test(`parallel batch runs real isolated members: ${mode}`,()=>batchFixture(mode));
21
+
22
+ test('ready member merges before blocked member preserves reason in log and WIP and falls back only once',async()=>{
23
+ for(const withReason of [true,false])await batchFixture('parallel-recovery',{terminalAgain:true,withReason});
24
+ });
25
+ test('serial fallback resumes from log and automatically commits its completed task',async()=>{
26
+ for(const options of [{crashAt:'cleanup'},{crashAt:'serial'},
27
+ {blockedIds:['T-001']},{blockedIds:['T-001','T-002']}])await batchFixture('parallel-recovery',options);
28
+ });
29
+ test('final serial task commits durably and commit information survives resume',()=>batchFixture('final-commit'));
30
+ test('dirty batch entry lists files and creates no member worktrees',()=>batchFixture('parallel-dirty'));
31
+
32
+ test('task commit subjects are single-line and bounded while bodies preserve descriptions',()=>{
33
+ const cases=[
34
+ ['简短任务','T-001: 简短任务'],
35
+ ['完成 `接口` **实现** ~15min;保留后续。\n完整正文','T-001: 完成 `接口` **实现**'],
36
+ ['首句。后续 ~20min','T-001: 首句'],
37
+ ['首行\n第二行 ~10min','T-001: 首行'],
38
+ ['~20min 开头估算','T-001: 开头估算'],
39
+ ['~20min','T-001: T-001'],
40
+ ['ASCII task ~5min','T-001: ASCII task'],
41
+ ['x'.repeat(65),'T-001: '+'x'.repeat(65)],
42
+ ['x'.repeat(66),'T-001: '+'x'.repeat(63)+'…'],
43
+ ['中文任务'.repeat(30)+' ~25min',null],
44
+ ['A'.repeat(100)+' ~30min',null],
45
+ ];
46
+ for(const [description,expected] of cases){
47
+ const args=taskCommitArgs('T-001',description);
48
+ assert.equal(args.length,4);assert.equal(args[0],'-m');assert.equal(args[2],'-m');
49
+ assert.doesNotMatch(args[1],/[\r\n\u2028\u2029]/u);
50
+ assert(Array.from(args[1]).reduce((sum,char)=>sum+(char.codePointAt(0)<=127?1:2),0)<=72);
51
+ assert.doesNotMatch(args[1],/~\d+min/u);assert.equal(args[3],description);
52
+ if(expected!==null)assert.equal(args[1],expected);else assert(args[1].endsWith('…'));
53
+ assert.deepEqual(taskCommitArgs('T-001',description,'failed'),['-m','WIP T-001: blocked (failed)','-m',description]);
54
+ }
55
+ });
56
+
57
+ async function batchFixture(mode,options={}){
58
+ const parallel=mode.startsWith('parallel');
59
+ const recovery=mode==='parallel-recovery',blockedIds=options.blockedIds??['T-002'];
16
60
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-batch-')));
17
61
  try{
18
62
  const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.work';
19
63
  fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
20
64
  for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
21
- fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n');
65
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n'+(parallel?'- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n':''));
22
66
  fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
23
67
  fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
68
+ const git=(cwd,args)=>{const result=spawnSync('git',['-C',cwd,...args],{encoding:'utf8'});assert.equal(result.status,0,result.stderr);return result.stdout.trim();};
69
+ {git(codeProject,['init','-b','main']);git(codeProject,['config','user.name','Fixture']);git(codeProject,['config','user.email','fixture@example.invalid']);
70
+ fs.writeFileSync(path.join(codeProject,'file0.js'),'base\n');git(codeProject,['add','-A']);git(codeProject,['commit','-m','fixture baseline']);}
24
71
  const config={version:1,repositoryId:'batch-fixture',batchId:'batch-fixture',specsDir,codeProject,
25
- tasks:['T-001','T-002'].map((taskId,index)=>({feature,taskId,scope:[`file${index}.js`],requirements:['requirements.md']}))};
26
- const calls=[],qaCalls=[],assessments=[];let qaReady=mode!=='qa-resume',started;
72
+ ...(parallel?{parallel:[[`${feature}/T-001`,`${feature}/T-002`]]}:{}),
73
+ tasks:(parallel?['T-001','T-002','T-003']:['T-001','T-002']).map((taskId,index)=>({feature,taskId,scope:[`file${index}.js`],requirements:['requirements.md']}))};
74
+ const calls=[],qaCalls=[],assessments=[],blockedEvidence=[];let qaReady=mode!=='qa-resume',started;
27
75
  const began=new Promise(resolve=>{started=resolve;});
28
- const executionFor=async definition=>({configuration:{kind:'batch-fixture-v1'},timeoutMs:3000,
76
+ let conflictHead=null,interrupted=false;
77
+ const executionFor=async(definition,{parallelMember=false}={})=>({configuration:{kind:'batch-fixture-v1',...(parallelMember?{parallelMember:true}:{})},timeoutMs:3000,
29
78
  excludedContexts:['host'],hostDecision:{status:'approved'},applicableAgentFiles:[],
30
79
  developer:{provider:'codex',requestedModel:'fixture',contextId:'author',run:createCodexDeveloperRun({requestedModel:'fixture',
31
80
  worker:async({prompt},{signal})=>{
32
81
  const material=JSON.parse(prompt.split('<cm-developer-data-json>\n')[1]).specification;
33
82
  assert.equal(material.task.id,definition.identity.taskId);
34
83
  assert.deepEqual(material.sources,buildManifest(specsDir));
35
- calls.push(definition.identity.taskId);fs.writeFileSync(path.join(codeProject,definition.scope[0]),'implemented\n');
84
+ if(recovery&&!parallelMember&&blockedIds.includes(definition.identity.taskId)){
85
+ const key=`${feature}/${definition.identity.taskId}`;
86
+ assert.equal(definition.codeProject,codeProject);
87
+ assert.equal(definition.identity.runId,`task-${digest({batchId:config.batchId,task:key,generation:2}).slice(0,48)}`);
88
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
89
+ const blocked=rows.find(row=>row.phase==='batch_member_blocked'&&row.from_key===key);
90
+ const expectedReason=options.withReason?'Expected stub throws; waiting for peer':'failed';
91
+ assert(blocked);assert.equal(blocked.generation,2);assert.equal(blocked.code,'failed');
92
+ assert(!fs.existsSync(blocked.worktree));
93
+ assert.match(git(codeProject,['log','-1','--format=%s',blocked.branch]),/^WIP .*: blocked \(failed\)$/);
94
+ blockedEvidence.push({reason:blocked.reason,body:git(codeProject,['log','-1','--format=%b',blocked.branch]),
95
+ expectedReason,description:definition.identity.taskId==='T-001'?'first':'second'});
96
+ assert.equal(git(codeProject,['show',`${blocked.branch}:${definition.scope[0]}`]),'implemented');
97
+ for(const id of ['T-001','T-002'].filter(id=>!blockedIds.includes(id))){
98
+ const merged=rows.find(row=>row.phase==='batch_handoff'&&row.from_key===`${feature}/${id}`);
99
+ assert(merged);assert(rows.indexOf(merged)<rows.indexOf(blocked));
100
+ assert.equal(fs.readFileSync(path.join(codeProject,config.tasks.find(task=>task.taskId===id).scope[0]),'utf8'),'implemented\n');
101
+ }
102
+ }
103
+ calls.push(definition.identity.taskId);fs.writeFileSync(path.join(definition.codeProject,definition.scope[0]),'implemented\n');
104
+ if(recovery&&blockedIds.includes(definition.identity.taskId)&&(parallelMember||options.terminalAgain))
105
+ return {status:'succeeded',value:{outcome:'blocked',...(options.withReason?{reason:'Expected stub throws; waiting for peer'}:{})}};
106
+ if(parallel&&definition.identity.taskId==='T-002')await new Promise(resolve=>setTimeout(resolve,50));
107
+ if(mode==='parallel-conflict'&&definition.identity.taskId==='T-002'){
108
+ fs.writeFileSync(path.join(codeProject,'file0.js'),'main conflict\n');git(codeProject,['add','file0.js']);git(codeProject,['commit','-m','concurrent main change']);conflictHead=git(codeProject,['rev-parse','HEAD']);
109
+ }
36
110
  if(mode==='cancel'){started();await new Promise(resolve=>signal.addEventListener('abort',resolve,{once:true}));}
37
111
  const application={status:'no_relevant_lesson',note:null};
38
112
  let retrospective={status:'no_new_lesson',candidates:[],reason:null};
@@ -57,8 +131,9 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
57
131
  for(const event of [{event:'thread.started',provider_thread:`review-${request.identity.taskId}`},
58
132
  {event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
59
133
  {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
60
- return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
61
- examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic independent review'}};
134
+ const retry=mode==='parallel-retry'&&request.identity.taskId==='T-001'&&request.identity.attempt===1;
135
+ return {status:'succeeded',value:{verdict:retry?'changes_requested':'approved',packageDigest:request.payload.reviewPackage.packageDigest,
136
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:retry?[{id:'F1',severity:'P2',path:'file0.js',message:'Synthetic repair',evidence:'First implementation'}]:[],summary:'Synthetic independent review'}};
62
137
  }}],
63
138
  reviewInvocation:{developerThreadId:'author',excludedThreadIds:['host'],authorize:(request,{authorizationAt})=>{
64
139
  const body={version:1,kind:'cm-review-dispatch-grant',grantId:'grant',adapterId:'codex-review-adapter',
@@ -67,7 +142,7 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
67
142
  decisionId:'decision',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
68
143
  return {...body,grantDigest:digest(body)};
69
144
  }},
70
- qaDecisionProvider:mode==='policy'?createHostQaDecisionProvider({timeoutMs:1000,assess:async binding=>{
145
+ qaDecisionProvider:parallelMember?createParallelMemberQaDecisionProvider():mode==='policy'?createHostQaDecisionProvider({timeoutMs:1000,assess:async binding=>{
71
146
  assessments.push(binding.identity.taskId);
72
147
  return {scores:{scope:1,risk:1,accumulation:1,boundary:1},
73
148
  changes:{api:binding.identity.taskId==='T-001',migration:false,authentication:false,authorization:false,payment:false}};
@@ -93,6 +168,31 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
93
168
  packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,status:'completed',reason:'Synthetic docs',at:'2026-09-08T01:00:00Z'})},
94
169
  });
95
170
  const open=()=>createCmAiBatch({configuration:config,executionFor,logHome:path.join(root,'logs')});
171
+ if(mode==='parallel-dirty'){
172
+ fs.writeFileSync(path.join(codeProject,'dirty.txt'),'user-owned\n');
173
+ const result=await open().handle({operation:'advance',requestId:'dirty'});
174
+ assert.equal(result.code,'batch_main_dirty');assert.match(result.reason,/dirty\.txt/);assert.deepEqual(result.files,['?? dirty.txt']);
175
+ assert.deepEqual(calls,[]);assert(!fs.existsSync(path.join(root,'.cm-worktrees')));
176
+ assert(!fs.existsSync(path.join(specsDir,'运行日志.jsonl')));
177
+ assert.equal(git(codeProject,['status','--porcelain']),'?? dirty.txt');return;
178
+ }
179
+ const originalRead=fs.readFileSync,originalExists=fs.existsSync;
180
+ if(recovery&&options.crashAt)fs.existsSync=function(file,...args){
181
+ if(!interrupted&&(options.crashAt==='serial'?String(file).endsWith('state.json'):String(file).endsWith('T-002'))){
182
+ const logfile=path.join(specsDir,'运行日志.jsonl');
183
+ if(originalExists(logfile)&&originalRead(logfile,'utf8').split('\n').filter(Boolean).map(JSON.parse).some(row=>row.phase==='batch_member_blocked')){
184
+ interrupted=true;throw Object.assign(new Error('simulated interrupt'),{code:'simulated_interrupt'});
185
+ }
186
+ }return originalExists.call(fs,file,...args);
187
+ };
188
+ if(mode==='parallel-resume'||mode==='final-commit')fs.existsSync=function(file,...args){
189
+ if(!interrupted&&String(file).endsWith('state.json')){
190
+ const logfile=path.join(specsDir,'运行日志.jsonl');
191
+ if(originalExists(logfile)&&originalRead(logfile,'utf8').split('\n').filter(Boolean).map(JSON.parse).some(row=>row.phase==='batch_handoff')){
192
+ interrupted=true;throw Object.assign(new Error('simulated interrupt'),{code:'simulated_interrupt'});
193
+ }
194
+ }return originalExists.call(fs,file,...args);
195
+ };
96
196
  const batch=open(),pending=batch.handle({operation:'advance',requestId:'advance-1'});
97
197
  if(mode==='cancel'){
98
198
  await began;await batch.handle({operation:'cancel',requestId:'cancel'});
@@ -100,7 +200,51 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
100
200
  assert.equal((await open().handle({operation:'advance',requestId:'resume'})).code,'cancelled');
101
201
  assert.deepEqual(calls,['T-001']);return;
102
202
  }
103
- let result=await pending;
203
+ let result;
204
+ try{result=await pending;}catch(error){if(!(mode==='parallel-resume'||mode==='final-commit'||recovery&&options.crashAt)||error.code!=='simulated_interrupt')throw error;}finally{fs.existsSync=originalExists;}
205
+ if(mode==='final-commit'){
206
+ assert(interrupted);
207
+ const logfile=path.join(specsDir,'运行日志.jsonl');
208
+ const rows=fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse);
209
+ const commit=rows.find(row=>row.phase==='batch_task_committed');assert(commit);
210
+ // Restore the crash prefix before handoff; the next task has not started.
211
+ fs.writeFileSync(logfile,rows.filter(row=>row.phase!=='batch_handoff').map(row=>JSON.stringify(row)+'\n').join(''));
212
+ result=await open().handle({operation:'advance',requestId:'resume-commit-prefix'});
213
+ const recovered=fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse);
214
+ assert.equal(recovered.find(row=>row.phase==='batch_handoff').task_commit,commit.task_commit);
215
+ }
216
+ if(recovery&&options.crashAt){assert(interrupted);result=await open().handle({operation:'advance',requestId:'resume-recovery'});}
217
+ if(recovery){
218
+ // Assert outside the worker: worker exceptions intentionally become unknown terminals.
219
+ assert(blockedEvidence.length>0);
220
+ for(const evidence of blockedEvidence){
221
+ assert.equal(evidence.reason,evidence.expectedReason);
222
+ assert.equal(evidence.body,evidence.description+'\n\n'+evidence.expectedReason);
223
+ }
224
+ assert.equal(result.code,options.terminalAgain?'failed':'run_done',JSON.stringify(result));
225
+ const before=[...calls];
226
+ const resumed=await open().handle({operation:'advance',requestId:'resume-recovery-done'});
227
+ assert.equal(resumed.code,result.code);assert.deepEqual(calls,before);
228
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
229
+ assert.equal(rows.filter(row=>row.phase==='batch_member_blocked').length,blockedIds.length);
230
+ for(const id of blockedIds){
231
+ assert.equal(calls.filter(task=>task===id).length,2);
232
+ const key=`${feature}/${id}`,row=rows.find(row=>row.phase==='batch_handoff'&&row.from_key===key);
233
+ if(options.terminalAgain){assert.equal(row,undefined);continue;}
234
+ assert.match(row.task_commit,/^[a-f0-9]{40}$/);
235
+ assert.equal(git(codeProject,['show',`${row.task_commit}:${config.tasks.find(task=>task.taskId===id).scope[0]}`]),'implemented');
236
+ assert.equal(git(codeProject,['show','-s','--format=%s',row.task_commit]),`${id}: ${id==='T-001'?'first':'second'}`);
237
+ const runId=`task-${digest({batchId:config.batchId,task:key,generation:2}).slice(0,48)}`;
238
+ const state=JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','.execution',runId,'state.json'),'utf8'));
239
+ assert.equal(state.revision,row.checkpoint);
240
+ }
241
+ return;
242
+ }
243
+ if(mode==='parallel-resume'){assert(interrupted);const before=[...calls];result=await open().handle({operation:'advance',requestId:'resume-parallel'});assert.deepEqual(calls.slice(0,before.length),before);}
244
+ if(mode==='parallel-conflict'){
245
+ assert.equal(result.code,'merge_conflict',JSON.stringify(result));assert.equal(git(codeProject,['rev-parse','HEAD']),conflictHead);
246
+ for(const task of ['T-001','T-002'])assert(fs.existsSync(path.join(root,'.cm-worktrees',config.batchId.slice(0,8),task)));return;
247
+ }
104
248
  if(mode==='qa-resume'){
105
249
  assert.equal(result.code,'qa_decision_required');assert.deepEqual(calls,['T-001']);
106
250
  assert(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8').includes('[x] T-001'));
@@ -110,14 +254,47 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
110
254
  qaReady=true;result=await open().handle({operation:'advance',requestId:'advance-2'});
111
255
  }
112
256
  assert.equal(result.code,mode==='failed-qa'?'qa_failed':'run_done',JSON.stringify(result));
113
- assert.deepEqual(calls,mode==='failed-qa'?['T-001']:['T-001','T-002']);
257
+ assert.deepEqual(calls,parallel?(mode==='parallel-retry'?['T-001','T-002','T-001','T-003']:['T-001','T-002','T-003']):mode==='failed-qa'?['T-001']:['T-001','T-002']);
258
+ if(parallel){
259
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
260
+ const ready=rows.filter(row=>row.phase==='batch_member_ready'),handoffs=rows.filter(row=>row.phase==='batch_handoff');
261
+ assert.equal(ready.length,2);assert.equal(handoffs.length,2);assert.deepEqual(handoffs.map(row=>row.from_key),ready.map(row=>row.from_key));
262
+ assert(handoffs.every(row=>/^[a-f0-9]{40}$/.test(row.merge_commit)&&row.post_merge_check==='skipped'));
263
+ assert.equal(rows.filter(row=>row.event==='qa'&&row.reason==='parallel_member_deferred'&&row.status==='skipped').length,2);
264
+ assert.deepEqual(qaCalls,['T-003']);
265
+ assert(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8').includes('[x] T-003'));
266
+ assert.equal(git(codeProject,['branch','--show-current']),'main');
267
+ }
114
268
  if(mode==='learning'){
115
269
  const handoff=JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','work-T-002-a1-handoff.json'),'utf8'));
116
270
  assert(handoff.evidence.some(item=>typeof item==='string'&&item.includes('"status":"applied"')));
117
271
  }
272
+ if(mode==='final-commit'){
273
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
274
+ const commits=rows.filter(row=>row.phase==='batch_task_committed');
275
+ assert.deepEqual(commits.map(row=>row.from_key),[`${feature}/T-001`,`${feature}/T-002`]);
276
+ assert(rows.indexOf(commits[0])<rows.findIndex(row=>row.phase==='batch_handoff'));
277
+ assert.equal(result.task_commit,commits[1].task_commit);
278
+ assert.equal(result.task_commit,git(codeProject,['rev-parse','HEAD']));
279
+ assert.equal(git(codeProject,['show','-s','--format=%s',result.task_commit]),'T-002: second');
280
+ assert.equal(git(codeProject,['show','-s','--format=%b',result.task_commit]),'second');
281
+ assert.equal(git(codeProject,['show',`${result.task_commit}:file1.js`]),'implemented');
282
+ assert.equal(git(codeProject,['status','--porcelain']),'');
283
+ const resumedFinal=await open().handle({operation:'advance',requestId:'resume-final-commit'});
284
+ assert.equal(resumedFinal.code,result.code);assert.equal(resumedFinal.task_commit,result.task_commit);
285
+ assert.equal(fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n')
286
+ .map(JSON.parse).filter(row=>row.phase==='batch_task_committed').length,2);
287
+
288
+ }
118
289
  const before=[...calls],qaBefore=[...qaCalls];
119
290
  const resumed=await open().handle({operation:'advance',requestId:'resume'});
120
291
  assert.equal(resumed.code,result.code);assert.deepEqual(calls,before);assert.deepEqual(qaCalls,qaBefore);
292
+ if(mode==='final-commit'){
293
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
294
+ const commit=rows.find(row=>row.phase==='batch_task_committed');
295
+ assert.equal(rows.find(row=>row.phase==='batch_handoff').task_commit,commit.task_commit);
296
+ assert.equal(git(codeProject,['status','--porcelain']),'');
297
+ }
121
298
  if(mode==='executor'){
122
299
  assert.deepEqual(qaCalls,['T-002']);
123
300
  const reports=fs.readdirSync(path.join(specsDir,'.reviews')).filter(name=>name.endsWith('-execution.md'));
@@ -131,4 +308,4 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
131
308
  assert(log.some(row=>row.event==='qa'&&row.task==='T-002'&&row.reason==='feature_complete'));
132
309
  }
133
310
  }finally{fs.rmSync(root,{recursive:true,force:true});}
134
- });
311
+ }
@@ -1,5 +1,5 @@
1
1
  import {buildManifest} from './cm-spec-manifest.mjs';
2
- import test from 'node:test';
2
+ import test,{after} from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
@@ -16,6 +16,13 @@ import {inspectCmAiContextRefresh,inspectCmAiTaskLearningInput} from '../runtime
16
16
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
17
17
  import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
18
18
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
19
+ const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
20
+
21
+ // Keep runtime declarations and log mirrors independent of the invoking user's home.
22
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-bootstrap-home-'));
23
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
24
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
25
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
19
26
 
20
27
  const workflowRoot=fileURLToPath(new URL('..',import.meta.url)).replace(/\/$/,'');
21
28
  const selection={versionControl:'none',modules:['frontend'],analysis:'Approved synthetic JavaScript project'};
@@ -124,7 +131,7 @@ function runCli(f,config,mode,operation){
124
131
  const args=[...config.args];args[4]=mode;
125
132
  const child=spawn(process.execPath,[config.cli,...args],{env:config.env,stdio:['pipe','pipe','pipe']});
126
133
  let buffer='',stderr='',sessionId;const calls=[];let result;
127
- const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error('bootstrap CLI timeout: '+stderr));},15000);
134
+ const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error('bootstrap CLI timeout: '+stderr));},Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
128
135
  const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
129
136
  child.stderr.on('data',chunk=>{stderr+=chunk;});child.once('error',reject);
130
137
  child.stdout.on('data',chunk=>{
@@ -182,7 +189,7 @@ test('empty T001 then protected current-host CLI rules task, actual QA and N7 us
182
189
  assert.match(fs.readFileSync(path.join(f.specsDir,'0.bootstrap','tasks.md'),'utf8'),/\[x\] T-002/);
183
190
  });
184
191
 
185
- test('bootstrap denies missing authority before intent and a newly authorized launch can continue',{timeout:15000},async t=>{
192
+ test('bootstrap denies missing authority before intent and a newly authorized launch can continue',{timeout:FIXTURE_TIMEOUT_MS},async t=>{
186
193
  const f=fixture(t);
187
194
  let run=open(f,'T-001');await run.effect('develop');await run.effect('review');await run.effect('complete');run.close();
188
195
  run=open(f,'T-002','create',{allowWrite:false});
@@ -13,7 +13,7 @@ import {createFixLearningPreparation} from '../runtime/js/cm-fix/learning.mjs';
13
13
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
14
14
  import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
15
15
  import {loadConfig,declaredRuntimes,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
16
- import {readHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
16
+ import {readHostWorkflowConfiguration,featureHasBrowserCases,readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
17
17
  import {digest,json,need,shape} from '../runtime/js/cm-ai/effect-contract.mjs';
18
18
  export {executionFor as createConversationExecution,reviewConfiguration as readConversationReviewConfiguration};
19
19
  export {conversationProtection} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
@@ -29,7 +29,7 @@ const fixLocalPermissions=new Map(['red-test','baseline','regression','learning-
29
29
  'test-author','repair','cause-review','final-review']
30
30
  .map(name=>[`--allow-qa-fix-${name}`,`--allow-${name}`]));
31
31
 
32
- const usage='cm-ai-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-development [--runtime codex|claude] [--failover] [--review-config PATH] [--allow-review-attempt 1|2] [--workflow-config PATH] [--allow-qa]\ncm-ai-host.mjs preflight --config PATH --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
32
+ const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development [--runtime codex|claude] [--failover] [--review-config PATH] [--allow-review-attempt 1|2] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
33
33
 
34
34
  function reviewConfiguration(file){
35
35
  const info=fs.lstatSync(file);
@@ -43,6 +43,24 @@ function reviewConfiguration(file){
43
43
  return json({...config,disabledSkills});
44
44
  }
45
45
 
46
+ // Shared synthetic loopback diagnostic; a receipt never grants Review permission.
47
+ export async function runReviewPreflight(definition,{model,runtime='codex',disabledSkills}={}){
48
+ need(['codex','claude'].includes(runtime),'invalid_runtime');
49
+ if(runtime==='claude'){
50
+ const {previewClaudeTools}=await import('../runtime/js/cm-ai/claude-tool-preview.mjs');
51
+ const config=await previewClaudeTools({cwd:definition.codeProject,model});
52
+ return config;
53
+ }
54
+ const {previewIsolated,previewTools}=await import('../runtime/js/cm-ai/tool-preview.mjs');
55
+ const preview=disabledSkills===undefined?previewIsolated:previewTools;
56
+ const receipt=await preview({cwd:definition.codeProject,model,allowCodeProject:true,promptTransport:'stdin',
57
+ ...(disabledSkills===undefined?{}:{disabledSkills})});
58
+ // No raw startup diagnostics, headers, prompt or discovered content.
59
+ return {model,disabledSkills:receipt.disabledSkillFolders,preflight:{passed:receipt.passed,
60
+ cli_model:receipt.cli_model,config_fingerprint:receipt.config_fingerprint,prompt_transport:receipt.prompt_transport,
61
+ real_model_requests:receipt.real_model_requests,listener_closed:receipt.listener_closed}};
62
+ }
63
+
46
64
  async function protectedExecutionFor(definition,hostContextId,extra,review,mode,workflow,bridge,bootstrap=null){
47
65
  const runtime=extra.get('--runtime')??'codex';
48
66
  const selected=resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime);
@@ -102,6 +120,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
102
120
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Approved 0.bootstrap only: --bootstrap-config PATH {selection:null for scaffold, or original cm-init selection for rules} and --allow-bootstrap-write. Original scope must include fixed instruction targets; they are host-written inside the original task effect, checked/reviewed and reloaded. No Git/install/network grant. Optional codeProjects selects disjoint real roots below codeProject; prefix scope/requirements and use protected current-session checks with a declared codeProject per command.\n');
103
121
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session mode (Codex or Claude; also batch): --protected-conversation-config PATH with {checkCommands,timeoutMs}; timeoutMs bounds both check commands and the reviewer process. A review transport timeout with no result can resume once per attempt with fresh review authorization; a result-bearing timeout still requires reconciliation. No extra model call. The current host returns scoped UTF-8 edits; native Codex sandbox applies them and runs the declared checks. Original author runtime, per-attempt Review and QA permissions remain required. Do not combine with --protected-config. Same original 64KiB transport limit; unavailable/binary changes stop, never switch to direct writes.\n');
104
122
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected single-task CLI mode: add --protected-config PATH --allow-provider-development-attempt 1|2 and --review-config PATH. Protected config is {model,checkCommands,timeoutMs}; roots and host identity come from the original run definition and launch. This explicitly permits one task attempt of real developer execution and its declared native-sandbox checks; --allow-development alone does not. Review separately requires --allow-review-attempt 1|2. Diagnostics are required but are not review authorization. Optional original --workflow-config PATH and --allow-qa connect protected QA commands and documentation within the same developer invocation before Review; host semantic/browser/inspection requests retain their original contracts, not arbitrary writes. Default current-session mode is unchanged. Protected parent mode selects coder/reviewer CLIs from the project declaration; Claude returns protected-text-v1 proposals for host validation and sandbox application; original QA-fix options require child configuration.protectSpecs=true and all original child action permissions. Protected fix writes use text proposals, not direct host edits. The original QA/documentation/finalizer gates remain required. No installation or Git authority.\n');
123
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--browser-qa is required when the approved contract for this feature contains blocking browser cases or policy-enabled browser cases and QA is enabled, and must not be given otherwise. It is a declaration by the launching session, not a probe: the host cannot verify that this session can drive a browser. The gate applies to create and resume alike, so every launch must assert it again; the assertion is not persisted, because a stored assertion would only repeat the claim made by whichever session wrote it. unavailable refuses to start; either launch from a browser-capable session or remove browser cases from the approved contract.\n');
105
124
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--auto-qa-fix optionally connects parent advance -> fix_run -> re-QA. Requires --qa-fix-template-config, --allow-qa-fix-start, original action permissions and project policies.auto_fix=auto. Explicit/never policies stop. Unknown, blocked or incomplete repair stops; status/cancel remain available and no fourth QA round is dispatched.\n');
106
125
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--qa-fix-template-config PATH is an alternative to --qa-fix-owner-config. Supply {specsRoot, feature, identity: parent identity, configuration: original fix configuration without qaSource}. Each fix request binds it to the latest completed QA failure; identity/digests are generated, commands/scope/permissions are not. Existing child configuration remains immutable.\n');
107
126
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('fix_run continuously executes normal stages of the fixed QA child using the same binding as fix_advance. Requires --allow-qa-fix-start and every original per-action permission/configuration. Stops on unknown, blocked, observation, revision-required or unchanged state. It does not auto-switch child configuration or run parent QA.\n');
@@ -112,6 +131,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
112
131
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('New cm-ai runs carry approved specification data in developer requests and review packages: task/verification, all AC lines, design (64 KiB UTF-8 maximum, truncated:true above it), task-related test cases and manifest hashes. Sources must match .cm-specs-status.specFiles or spec_drift blocks. requirements may be [] or additional code-project files; specs never become writable scope. Legacy runs/packages retain their original representation. Dogfood: separate specs/code roots previously left developers and reviewers without task/interface contracts.\n');
113
132
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Completed fixture_completed runs originally without QA may explicitly attach N6 once on --mode resume with --workflow-config (non-null qa) and --allow-qa. Original definition, scope, requirements, identity and non-workflow configuration must match. The immutable qa-attached journal record binds the full resumed config fingerprint; later resumes require that same configuration and fresh --allow-qa. qa still requests qa_assess; no automatic decision or repeated development/Review. Dogfood: missing workflow at create previously stranded mandatory feature QA.\n');
114
133
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated.\n');
134
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-blocked-qa requires --mode resume, the original --workflow-config and fresh --allow-qa. Only the latest completed BLOCKED invocation with zero failures and exclusively host/environment evidence gaps can be superseded: browser evidenceProblem, failed cleanup, environment mismatch or host timeout; logic INSUFFICIENT_EVIDENCE. Commands BLOCKED and source drift are excluded. A new testRunId reruns every case at qaRound+1 (maximum 3); superseded and start link previous_test_run_id. The flag is consumed once, never persisted; no development/Review/task replay or new QA decision. Do not combine with --rerun-unknown-qa.\n');
115
135
  if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\n');return 0;}
116
136
  let run,bridge;
117
137
  try{
@@ -121,26 +141,16 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
121
141
  need(argv.length===5||argv[5]==='--runtime','invalid_arguments');
122
142
  need(['codex','claude'].includes(runtime),'invalid_runtime');
123
143
  const definition=readRunDefinition(argv[2]);
124
- if(runtime==='claude'){
125
- const {previewClaudeTools}=await import('../runtime/js/cm-ai/claude-tool-preview.mjs');
126
- const config=await previewClaudeTools({cwd:definition.codeProject,model:argv[4]});
127
- output.write(JSON.stringify(config)+'\n');return config.preflight.passed?0:1;
128
- }
129
- const {previewIsolated}=await import('../runtime/js/cm-ai/tool-preview.mjs');
130
- const receipt=await previewIsolated({cwd:definition.codeProject,model:argv[4],allowCodeProject:true,promptTransport:'stdin'});
131
- // No raw startup diagnostics, headers, prompt or discovered content.
132
- output.write(JSON.stringify({model:argv[4],disabledSkills:receipt.disabledSkillFolders,preflight:{passed:receipt.passed,
133
- cli_model:receipt.cli_model,config_fingerprint:receipt.config_fingerprint,prompt_transport:receipt.prompt_transport,
134
- real_model_requests:receipt.real_model_requests,listener_closed:receipt.listener_closed}})+'\n');
135
- return receipt.passed?0:1;
144
+ const config=await runReviewPreflight(definition,{model:argv[4],runtime});
145
+ output.write(JSON.stringify(config)+'\n');return config.preflight.passed?0:1;
136
146
  }
137
147
  need(argv.length>=8&&argv[0]==='serve'&&argv[1]==='--config'&&argv[3]==='--mode'
138
148
  &&argv[5]==='--host-context'&&argv[7]==='--allow-development','host_launch_authorization_required');
139
149
  const extra=new Map();
140
150
  for(let index=8;index<argv.length;index++){
141
151
  const name=argv[index];need(!extra.has(name),'invalid_arguments');
142
- need(['--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--workflow-config','--allow-qa','--rerun-unknown-qa','--runtime','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments');
143
- if(['--allow-bootstrap-write','--allow-qa','--rerun-unknown-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
152
+ need(['--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments');
153
+ if(['--allow-bootstrap-write','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
144
154
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(name,argv[++index]);}
145
155
  }
146
156
  const review=extra.has('--review-config')?reviewConfiguration(extra.get('--review-config')):null;
@@ -148,7 +158,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
148
158
  let allowedAttempt=null;
149
159
  if(extra.has('--allow-review-attempt')){need(['1','2'].includes(extra.get('--allow-review-attempt')),'invalid_arguments');allowedAttempt=Number(extra.get('--allow-review-attempt'));}
150
160
  need(!extra.has('--allow-qa')||workflow?.qa!=null,'invalid_arguments');
151
- need(!extra.has('--rerun-unknown-qa')||(argv[4]==='resume'&&extra.has('--allow-qa')),'qa_recovery_authorization_required');
161
+ need(!(extra.has('--rerun-unknown-qa')&&extra.has('--rerun-blocked-qa')),'qa_recovery_authorization_required');
162
+ need(!(extra.has('--rerun-unknown-qa')||extra.has('--rerun-blocked-qa'))||(argv[4]==='resume'&&extra.has('--allow-qa')),'qa_recovery_authorization_required');
152
163
  const hasFix=extra.has('--qa-fix-owner-config')||extra.has('--qa-fix-template-config');
153
164
  need(!(extra.has('--qa-fix-owner-config')&&extra.has('--qa-fix-template-config')),'invalid_fix_config');
154
165
  need(!extra.has('--allow-qa-fix-start')||hasFix,'qa_fix_source_required');
@@ -162,7 +173,12 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
162
173
  need(!extra.has('--allow-bootstrap-write')||bootstrap!==null,'bootstrap_configuration_required');
163
174
  // Checked before the definition is read so the conflict is reported on its own.
164
175
  need(!(extra.has('--failover')&&extra.has('--protected-config')),'failover_unsupported_in_protected_mode');
165
- const definition=readRunDefinition(argv[2]);bridge=createHostToolBridge();
176
+ const definition=readRunDefinition(argv[2]);
177
+ // Launch-time capability assertion. See host-workflow-capabilities: this is a
178
+ // fresh declaration, not a probe the host performs.
179
+ readBrowserCapability(extra.get('--browser-qa'),
180
+ workflow?.qa!=null&&featureHasBrowserCases(definition.specsDir,definition.feature,definition.codeProject));
181
+ bridge=createHostToolBridge();
166
182
  // Startup-only role failover. The project's runtimes.available declaration is
167
183
  // primary: it fixes which runtimes may be chosen and, via roles.coder, the
168
184
  // requested start runtime. The CLI probe only confirms reachability. It never
@@ -193,7 +209,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
193
209
  if(argv[4]==='resume'&&extra.has('--protected-config')&&canResumeLegacyProtected(definition,runtime)){
194
210
  try{
195
211
  execution=await legacyProtectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap);
196
- run=await openControlRun(definition,argv[4],execution,{rerunUnknownQa:extra.has('--rerun-unknown-qa')});
212
+ run=await openControlRun(definition,argv[4],execution,{rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa')});
197
213
  error.write('cm-ai-host: resumed original Codex protected execution after exact fingerprint validation.\n');
198
214
  }catch(cause){
199
215
  if(!['fingerprint_mismatch','tool_preflight_missing'].includes(cause.code))throw cause;
@@ -205,7 +221,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
205
221
  ?await protectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap)
206
222
  :executionFor(definition,argv[6],bridge,review,allowedAttempt,workflow,extra.has('--allow-qa'),runtime,
207
223
  {...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
208
- run=await openControlRun(definition,argv[4],execution,{rerunUnknownQa:extra.has('--rerun-unknown-qa')});
224
+ run=await openControlRun(definition,argv[4],execution,{rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa')});
209
225
  }
210
226
  if(run.blocked){output.write(JSON.stringify({outcome:'blocked',admission:run.blocked})+'\n');return 1;}
211
227
  if(hasFix){
@@ -237,7 +253,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
237
253
  finally{if(rawMode)input.setRawMode(false);}
238
254
  return 0;
239
255
  }catch(cause){
240
- const code=typeof cause?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(cause.code)?cause.code:'host_launch_failed';
256
+ const code=typeof cause?.code==='string'&&(/^[a-z][a-z0-9_]{0,63}$/.test(cause.code)
257
+ ||cause.code.startsWith('invalid_config: '))?cause.code:'host_launch_failed';
241
258
  error.write(JSON.stringify({error:{code}})+'\n');return 1;
242
259
  }finally{bridge?.close();run?.close();}
243
260
  }
@@ -1,5 +1,5 @@
1
1
  import {buildManifest} from './cm-spec-manifest.mjs';
2
- import test from 'node:test';
2
+ import test,{after} from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
@@ -10,6 +10,12 @@ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
10
10
  import {createConversationExecution} from './cm-ai-host.mjs';
11
11
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
12
12
 
13
+ // Keep runtime declarations and log mirrors independent of the invoking user's home.
14
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-host-home-'));
15
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
16
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
17
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
18
+
13
19
  const cli=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
14
20
  const identity={repositoryId:'host-fixture',runId:'host-fixture-run',taskId:'T-001',attempt:1};
15
21
  const request=(operation,requestId=operation)=>({version:1,operation,requestId,identity});
@@ -30,7 +36,7 @@ function runCli(f,mode,action='create'){
30
36
  const args=[...f.args];args[4]=action;
31
37
  const child=spawn(process.execPath,[cli,...args],{stdio:['pipe','pipe','pipe'],env:f.env??process.env});
32
38
  let buffer='',stderr='',closed=false,sessionId;const rows=[],calls=[];
33
- const timer=setTimeout(()=>{child.kill('SIGTERM');reject(new Error('host fixture timed out'));},15000);
39
+ const timer=setTimeout(()=>{child.kill('SIGTERM');reject(new Error('host fixture timed out'));},Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
34
40
  child.stderr.on('data',chunk=>{stderr+=chunk;});
35
41
  child.once('error',reject);
36
42
  const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
@@ -54,7 +60,7 @@ function runCli(f,mode,action='create'){
54
60
  assert.deepEqual(row.payload.request.payload.scope,JSON.parse(fs.readFileSync(f.config)).scope);
55
61
  }
56
62
  if(action!=='create')assert((f.develop&&row.kind==='develop')||(mode==='authorized-review'&&['check','qa_assess','documentation_inspect'].includes(row.kind))
57
- ||(f.workflow&&row.kind==='documentation_inspect'),'resume must not resend development');
63
+ ||(f.workflow&&row.kind==='documentation_inspect')||(f.qaBrowser&&row.kind==='qa_browser'),'resume must not resend development');
58
64
  if(mode==='disconnect'){child.stdin.end();continue;}
59
65
  if(mode==='cancel'){send(request('status'));send(request('cancel'));continue;}
60
66
  if(f.fix&&row.kind==='fix_learning'){
@@ -98,6 +104,8 @@ function runCli(f,mode,action='create'){
98
104
  assert(f.workflow);assert.equal(row.payload.pending,0);
99
105
  send(response(row,{scores:{scope:1,risk:1,accumulation:1,boundary:1},
100
106
  changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}}));
107
+ }else if(row.kind==='qa_browser'&&f.qaBrowser){
108
+ send(response(row,f.qaBrowser(row.payload)));
101
109
  }else if(row.kind==='documentation_inspect'){
102
110
  assert(f.workflow);assert(fs.readFileSync(path.join(f.codeProject,'README.md'),'utf8').includes(f.fix?'43':'42'));
103
111
  const {syncId,identity,packageDigest,contextDigest}=row.payload;
@@ -866,7 +874,7 @@ test('protected proposal cannot write after specification drifts during develope
866
874
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
867
875
  });
868
876
 
869
- test('unknown QA rerun requires resume and separate QA permission before opening the owner',()=>{
877
+ for(const flag of ['--rerun-unknown-qa','--rerun-blocked-qa'])test(`${flag} requires resume and separate QA permission before opening the owner`,()=>{
870
878
  const f=fixture();
871
879
  try{
872
880
  const workflow=path.join(f.root,'workflow.json');
@@ -874,10 +882,72 @@ test('unknown QA rerun requires resume and separate QA permission before opening
874
882
  environment:{kind:'web',carrier:'browser',target:'http://127.0.0.1',scope:'local'}}}));
875
883
  for(const mode of ['create','resume']){
876
884
  const args=[...f.args];args[4]=mode;
877
- const result=spawnSync(process.execPath,[cli,...args,'--workflow-config',workflow,'--rerun-unknown-qa',
885
+ const result=spawnSync(process.execPath,[cli,...args,'--workflow-config',workflow,flag,
878
886
  ...(mode==='create'?['--allow-qa']:[])],{encoding:'utf8',timeout:3000});
879
887
  assert.equal(result.status,1);assert.match(result.stderr,/qa_recovery_authorization_required/);
880
888
  assert(!fs.existsSync(path.join(f.specsDir,'.reviews')));
881
889
  }
882
890
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
883
891
  });
892
+
893
+ test('step31 CLI resumes completed evidence BLOCKED QA and reaches the original finalizer',async()=>{
894
+ const f=fixture();f.workflow=true;
895
+ try{
896
+ const definition=JSON.parse(fs.readFileSync(f.config));definition.scope.push('README.md');
897
+ fs.writeFileSync(f.config,JSON.stringify(definition));
898
+ fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Fixture value 42\n');
899
+ fs.writeFileSync(path.join(f.specsDir,'1.work','requirements.md'),'- [AC-001]: fixture\n');
900
+ fs.writeFileSync(path.join(f.specsDir,'1.work','test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',
901
+ cases:[{id:'TC-001',kind:'browser',blocking:true,origin:'user',acIds:['AC-001'],taskIds:['T-001'],
902
+ title:'Synthetic browser',preconditions:[],steps:['Observe fixture'],expected:['Fixture works'],cleanup:[]}]}));
903
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
904
+ const bin=path.join(f.root,'bin');fs.mkdirSync(bin);
905
+ const fake=path.join(bin,'codex');fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),fake);fs.chmodSync(fake,0o700);
906
+ f.env={...process.env,PATH:bin+path.delimiter+process.env.PATH};
907
+ const preview=spawnSync(process.execPath,[cli,'preflight','--config',f.config,'--review-model','fixture'],{encoding:'utf8',env:f.env,timeout:5000});
908
+ assert.equal(preview.status,0,preview.stderr);
909
+ const review=path.join(f.root,'review.json');fs.writeFileSync(review,preview.stdout);
910
+ const workflow=path.join(f.root,'workflow.json');
911
+ fs.writeFileSync(workflow,JSON.stringify({documentationPaths:['README.md'],applicableAgentFiles:[],qa:{
912
+ commands:[{id:'value-check',command:[process.execPath,'-e',"import('./target.mjs').then(m=>{if(m.value!==42)process.exit(1)})"],caseIds:[]}],
913
+ environment:{kind:'web',carrier:'browser',target:'http://127.0.0.1',scope:'local'}}}));
914
+ f.args.push('--review-config',review,'--allow-review-attempt','1','--workflow-config',workflow,'--allow-qa','--browser-qa','available');
915
+ let corrected=false;
916
+ f.qaBrowser=payload=>{
917
+ const file=path.join(f.specsDir,'.reviews','browser-evidence.txt');fs.writeFileSync(file,'Synthetic observed browser evidence');
918
+ return {verdict:'PASS',evidence:corrected?[file]:[file,'docs/browser-qa.md(T-001)'],environment:payload.environment,cleanup:'completed'};
919
+ };
920
+ const first=await runCli(f,'normal');assert.equal(first.code,0,first.stderr);
921
+ assert.equal(first.rows.find(row=>row.requestId==='advance').result.code,'qa_result_blocked');
922
+ const tasks=fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'));
923
+ const checkpoint=fs.readFileSync(path.join(f.specsDir,'.reviews','.execution',identity.runId,'state.json'));
924
+ const status=JSON.parse(fs.readFileSync(path.join(f.specsDir,'.cm-status.json')));assert.equal(status.state,'qa_blocked');
925
+ corrected=true;
926
+ const without=await runCli(f,'normal','resume');assert.equal(without.code,0,without.stderr);assert.deepEqual(without.calls,[]);
927
+ const unchanged=without.rows.find(row=>row.requestId==='advance').result;
928
+ assert.equal(unchanged.pendingAction,'none');assert.equal(unchanged.code,'qa_result_blocked');
929
+ f.args.push('--rerun-blocked-qa');
930
+ const resumed=await runCli(f,'normal','resume');assert.equal(resumed.code,0,resumed.stderr);
931
+ assert.deepEqual(resumed.calls,['qa_browser','documentation_inspect']);
932
+ assert.equal(resumed.rows.find(row=>row.requestId==='advance').result.state,'run_done');
933
+ f.args.pop();
934
+ const again=await runCli(f,'normal','resume');assert.equal(again.code,0,again.stderr);
935
+ assert.deepEqual(again.calls,['documentation_inspect']);
936
+ const rows=fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
937
+ const qa=rows.filter(row=>row.event==='test_run');
938
+ const starts=qa.filter(row=>row.phase==='start');assert.deepEqual(starts.map(row=>row.attempt),[1,2]);
939
+ assert.equal(starts[1].previous_test_run_id,starts[0].operation_id);
940
+ const superseded=qa.find(row=>row.phase==='superseded');assert.deepEqual(superseded.blocked_cases,['TC-001']);
941
+ assert.equal(superseded.reason,'host_evidence_problem');
942
+ assert.deepEqual(qa.filter(row=>row.phase==='complete').map(row=>row.result),['BLOCKED','PASS']);
943
+ assert.equal(rows.filter(row=>row.event==='qa').length,1);
944
+ assert.deepEqual(fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md')),tasks);
945
+ assert.deepEqual(fs.readFileSync(path.join(f.specsDir,'.reviews','.execution',identity.runId,'state.json')),checkpoint);
946
+ if(process.env.CM_STEP31_REPRO==='1'){
947
+ console.log('STEP31 without flag',JSON.stringify(unchanged));
948
+ console.log('STEP31 initial status mirror',JSON.stringify(status));
949
+ for(const row of qa.filter(row=>['start','superseded','complete'].includes(row.phase)))console.log(JSON.stringify(row));
950
+ console.log('STEP31 resumed',JSON.stringify(resumed.rows.find(row=>row.requestId==='advance').result));
951
+ }
952
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
953
+ });