@aibyzero/cm-workflow 0.16.9 → 0.17.1

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 (165) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +18 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +16 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/cm-control-policy-v2.md +331 -0
  9. package/docs/execution-optimizations.md +1 -1
  10. package/docs/external-models.md +3 -3
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/human-correction.md +5 -5
  13. package/docs/installation.md +1 -1
  14. package/docs/js-workflow-control.md +104 -85
  15. package/docs/next-steps.md +11 -0
  16. package/docs/untested-branches.md +2 -3
  17. package/docs/user-guide.md +3 -3
  18. package/package.json +1 -1
  19. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  22. package/runtime/js/cm-ai/control-policy.mjs +112 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  24. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  26. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  27. package/runtime/js/cm-ai/host-check.mjs +3 -1
  28. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  29. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  31. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  32. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  33. package/runtime/js/cm-ai/host-session.mjs +41 -8
  34. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  35. package/runtime/js/cm-ai/host-tool-bridge.mjs +25 -9
  36. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  37. package/runtime/js/cm-ai/host.mjs +1 -2
  38. package/runtime/js/cm-ai/operator-guidance.mjs +57 -54
  39. package/runtime/js/cm-ai/review-package.mjs +16 -4
  40. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  41. package/runtime/js/cm-ai/task-runner.mjs +41 -101
  42. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  43. package/runtime/js/cm-prd/review-host.mjs +1 -1
  44. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  45. package/runtime/js/cm-prd/summary.mjs +27 -12
  46. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  47. package/runtime/js/notify-send.mjs +15 -14
  48. package/runtime/js/notify.mjs +27 -4
  49. package/runtime/js/policy-binding-compat.mjs +2 -1
  50. package/runtime/review.md +61 -7
  51. package/runtime/task-gates.md +107 -9
  52. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  53. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  54. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  55. package/scripts/cm-ai-batch-drive.mjs +50 -31
  56. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  57. package/scripts/cm-ai-batch-host.mjs +39 -20
  58. package/scripts/cm-ai-batch-host.test.mjs +83 -47
  59. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  60. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  61. package/scripts/cm-ai-batch-run.mjs +46 -14
  62. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  63. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  64. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  65. package/scripts/cm-ai-control-policy.test.mjs +192 -0
  66. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  67. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  68. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  69. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  70. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  71. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  72. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +57 -27
  73. package/scripts/cm-ai-drive.mjs +96 -54
  74. package/scripts/cm-ai-drive.test.mjs +46 -87
  75. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  77. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  78. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  79. package/scripts/cm-ai-host-fixture.mjs +47 -16
  80. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  81. package/scripts/cm-ai-host.mjs +103 -93
  82. package/scripts/cm-ai-host.test.mjs +34 -18
  83. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  84. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  85. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  86. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  87. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  88. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  89. package/scripts/cm-ai-progress.test.mjs +10 -8
  90. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  91. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  92. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  93. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  94. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  95. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  96. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  97. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  98. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  99. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  100. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  101. package/scripts/cm-ai-review-timeout.test.mjs +35 -128
  102. package/scripts/cm-ai-run.mjs +78 -24
  103. package/scripts/cm-ai-run.test.mjs +11 -38
  104. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  105. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  106. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  107. package/scripts/cm-ai-supersede.test.mjs +3 -10
  108. package/scripts/cm-blocked-reason.test.mjs +2 -3
  109. package/scripts/cm-capability-gate.test.mjs +33 -1
  110. package/scripts/cm-check-drive-files.mjs +1 -1
  111. package/scripts/cm-check-host.test.mjs +1 -1
  112. package/scripts/cm-check-runtime.sh +1 -1
  113. package/scripts/cm-claude-probe.test.mjs +26 -0
  114. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  115. package/scripts/cm-claude-worker.test.mjs +21 -3
  116. package/scripts/cm-controlled-correction.test.mjs +469 -0
  117. package/scripts/cm-drive-liveness.test.mjs +83 -0
  118. package/scripts/cm-external-batch-host.test.mjs +38 -17
  119. package/scripts/cm-external-model-host.test.mjs +1 -1
  120. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  121. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  122. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  123. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  124. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  125. package/scripts/cm-host-liveness.test.mjs +150 -0
  126. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  127. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  128. package/scripts/cm-host-review-authority.test.mjs +0 -31
  129. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  130. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  131. package/scripts/cm-notify-command.test.mjs +54 -18
  132. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  133. package/scripts/cm-notify.mjs +16 -4
  134. package/scripts/cm-notify.test.mjs +135 -29
  135. package/scripts/cm-patrol.test.mjs +3 -2
  136. package/scripts/cm-prd-drive.test.mjs +1 -1
  137. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  138. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  139. package/scripts/cm-prd-summary.test.mjs +31 -0
  140. package/scripts/cm-release-smoke.sh +2 -14
  141. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  142. package/scripts/cm-task-gate.mjs +368 -34
  143. package/scripts/cm-task-gate.py +2 -0
  144. package/scripts/cm-task-gate.test.mjs +252 -4
  145. package/scripts/cm-test-suite.mjs +109 -0
  146. package/scripts/cm-test-suite.test.mjs +162 -0
  147. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  148. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  149. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  150. package/scripts/policy-binding-compat.test.mjs +4 -0
  151. package/skills/cm-ai/SKILL.md +8 -6
  152. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  153. package/skills/cm-ai/references/N4-review.md +11 -21
  154. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  155. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  156. package/skills/cm-ai/references/js-host-modes.md +35 -14
  157. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  158. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  159. package/skills/cm-ai/references/js-host.md +98 -29
  160. package/skills/cm-fix/SKILL.md +12 -0
  161. package/skills/cm-init/references/js-host.md +1 -1
  162. package/skills/cm-prd/references/js-host.md +1 -1
  163. package/skills/cm-refactor/SKILL.md +12 -0
  164. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  165. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -1,3 +1,4 @@
1
+ import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
1
2
  import {EXECUTION_POLICY_V1} from '../runtime/js/cm-ai/execution-policy.mjs';
2
3
  import test from 'node:test';
3
4
  import assert from 'node:assert/strict';
@@ -41,21 +42,35 @@ function fixture(runtime='codex'){
41
42
  ...(runtime==='claude'?['--runtime','claude']:[])]};
42
43
  }
43
44
 
44
- function execute(f,approvals,{cancel=false}={}){
45
+ // Use an actual first-round review finding for a launch-only revision pause.
46
+ // The synthetic native process still emits its normal bound review observation.
47
+ function requestFirstRevision(f,taskIds){
48
+ const fake=path.join(f.root,'bin',f.runtime);
49
+ const first=`${JSON.stringify(taskIds)}.includes(data.reviewPackage.identity.taskId)&&data.reviewPackage.identity.attempt===1`;
50
+ const source=fs.readFileSync(fake,'utf8');
51
+ assert(source.includes("verdict:'approved'")&&source.includes('findings:[]'),'native review fixture must retain its known response fields');
52
+ fs.writeFileSync(fake,source
53
+ .replace("verdict:'approved'",`verdict:(${first})?'changes_requested':'approved'`)
54
+ .replace('findings:[]',`findings:(${first})?[{id:'F1',severity:'P2',path:'task'+Number(data.reviewPackage.identity.taskId.slice(-1))+'.mjs',message:'Recheck the export in a revision',evidence:'Synthetic first-round review finding'}]:[]`));
55
+ return taskIds.flatMap(taskId=>['--hold-revision',`1.work/${taskId}`]);
56
+ }
57
+
58
+ function execute(f,{cancel=false,args=[]}={}){
45
59
  return new Promise((resolve,reject)=>{
46
- const child=spawn(process.execPath,[cli,...f.args,...approvals.flatMap(value=>['--allow-review',value])],
60
+ const child=spawn(process.execPath,[cli,...f.args,...args],
47
61
  {env:f.env,stdio:['pipe','pipe','pipe']});
48
62
  let buffer='',stderr='',sessionId;const calls=[],rows=[];
49
- const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error('batch host timeout'));},Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
50
- child.stderr.on('data',part=>{stderr+=part;});child.once('error',reject);
51
- const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
63
+ const timeoutMs=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000),trace=hostDiagnostic(child,{timeoutMs});
64
+ const timer=setTimeout(()=>{child.kill('SIGTERM');reject(trace.attach(Error('batch host timeout')));},timeoutMs);
65
+ child.stderr.on('data',part=>{stderr+=part;});child.once('error',error=>reject(trace.attach(error)));
66
+ const send=value=>{trace.send(value);child.stdin.write(JSON.stringify(value)+'\n');};
52
67
  const respond=(row,result)=>send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
53
68
  child.stdout.on('data',part=>{
54
69
  buffer+=part;let newline;
55
70
  while((newline=buffer.indexOf('\n'))!==-1){
56
71
  const line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);if(!line)continue;
57
72
  try{
58
- const row=JSON.parse(line);rows.push(row);
73
+ const row=JSON.parse(line);rows.push(row);trace.receive(row);
59
74
  if(row.type==='host_ready')sessionId=row.sessionId;
60
75
  if(row.type==='host_request'){
61
76
  const payload=row.payload,identity=payload.identity??payload.request.identity;
@@ -69,7 +84,7 @@ function execute(f,approvals,{cancel=false}={}){
69
84
  assert.deepEqual(payload.request.payload.scope,f.batch.tasks[n-1].scope);
70
85
  assert.equal(payload.request.payload.specification.task.id,identity.taskId);
71
86
  assert.deepEqual(payload.request.payload.specification.sources,buildManifest(f.specsDir));
72
- const content=`export const value = ${40+n};\n`;
87
+ const content=`export const value = ${40+n};\n${identity.attempt===2?"// Revised after the independent review finding.\n":""}`;
73
88
  if(!f.protected)fs.writeFileSync(path.join(cwd,`task${n}.mjs`),content);
74
89
  respond(row,{status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
75
90
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}},...(f.protected?{edits:
@@ -81,8 +96,7 @@ function execute(f,approvals,{cancel=false}={}){
81
96
  const result=spawnSync(command[0],command.slice(1));assert.equal(result.status,0);
82
97
  return {id:'syntax',command,outcome:'passed',exitCode:0,evidence:'Actual Node syntax check exited 0'};
83
98
  });respond(row,checks);
84
- }else if(row.kind==='qa_assess')respond(row,{scores:{scope:2,risk:2,accumulation:2,boundary:2},
85
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
99
+ }else if(row.kind==='qa_assess')respond(row,{confirmed:true});
86
100
  else if(row.kind==='documentation_sync'){
87
101
  assert.equal(identity.taskId,'T-002');assert.deepEqual(payload.paths,['README.md']);
88
102
  fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Exports 41 and 42\n');respond(row,{status:'completed'});
@@ -94,10 +108,10 @@ function execute(f,approvals,{cancel=false}={}){
94
108
  }else assert.fail(`Unexpected ${row.kind}`);
95
109
  }
96
110
  if(row.requestId==='advance'&&(row.result||row.error))send({type:'host_close',sessionId});
97
- }catch(error){clearTimeout(timer);child.kill('SIGTERM');reject(error);}
111
+ }catch(error){clearTimeout(timer);child.kill('SIGTERM');reject(trace.attach(error));}
98
112
  }
99
113
  });
100
- child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,calls,rows,result:rows.find(row=>row.requestId==='advance')?.result});});
114
+ child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,calls,rows,diagnostic:trace.snapshot(),result:rows.find(row=>row.requestId==='advance')?.result});});
101
115
  send({operation:'advance',requestId:'advance'});
102
116
  });
103
117
  }
@@ -112,13 +126,16 @@ for(const runtime of ['codex','claude'])test(`${runtime} real batch host freezes
112
126
  const sent=path.join(f.root,'sent.jsonl'),fake=path.join(f.root,'bin',runtime);
113
127
  fs.writeFileSync(fake,fs.readFileSync(fake,'utf8').replace("import {randomUUID}",`import fs from 'node:fs';fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify(process.argv.slice(2))+'\\n');\nimport {randomUUID}`));
114
128
  const review=JSON.parse(fs.readFileSync(f.review));review.effort=pair.effort;review.preflight.config_fingerprint=(runtime==='claude'?claudeReviewFingerprint:configFingerprint)({cwd:f.codeProject,...pair});fs.writeFileSync(f.review,JSON.stringify(review));f.args.push('--external-models');
115
- const first=await execute(f,[]);assert.equal(first.result.state,'awaiting_review',first.stderr+JSON.stringify(first.result));
129
+ const held=requestFirstRevision(f,['T-001']);
130
+ const first=await execute(f,{args:held});assert.equal(first.result.state,'changes_requested',first.stderr+JSON.stringify(first.result));
131
+ assert.equal(first.result.code,'revision_answer_required');assert.equal(first.result.identity.attempt,2);
132
+ assert.deepEqual(first.calls,['T-001:develop','T-001:check']);
116
133
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');const statePath=n=>path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-00'+n),'state.json');
117
134
  assert(!fs.existsSync(statePath(2)));assert.deepEqual(JSON.parse(fs.readFileSync(statePath(1))).records[0].payload.config.externalModels,models);
118
135
  fs.writeFileSync(settings,'invalid new user defaults');
119
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
136
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
120
137
  for(const n of [1,2])assert.deepEqual(JSON.parse(fs.readFileSync(statePath(n))).records[0].payload.config.externalModels,models);
121
- const calls=fs.readFileSync(sent,'utf8').trim().split('\n').map(JSON.parse);assert.equal(calls.length,2);
138
+ const calls=fs.readFileSync(sent,'utf8').trim().split('\n').map(JSON.parse);assert.equal(calls.length,3);
122
139
  for(const args of calls){if(runtime==='codex'){assert(args.includes('model_reasoning_effort="low"'));assert(args.includes('--ephemeral'));}else{assert(!args.includes('--effort'));assert(args.includes('--no-session-persistence'));}}
123
140
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'});assert(!tracked.stdout.includes('.cm-external-models-v1.json'));assert(!tracked.stdout.includes('.cm-model-config.lock'));
124
141
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -136,7 +153,7 @@ test('new parallel batch merges reviewed members without committing private bind
136
153
  const review=JSON.parse(fs.readFileSync(f.review));review.effort='low';review.preflight.config_fingerprint=configFingerprint({cwd:f.codeProject,model:'fixture',effort:'low'});fs.writeFileSync(f.review,JSON.stringify(review));f.args.push('--external-models');
137
154
  fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Exports 41 and 42\n');
138
155
  for(const args of [['add','README.md'],['commit','-m','fixture documentation']])assert.equal(spawnSync('git',['-C',f.codeProject,...args]).status,0);
139
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1','1.work/T-003:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
156
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
140
157
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'}).stdout;assert(!tracked.includes('.cm-external-models-v1.json'));assert(!tracked.includes('.cm-model-config.lock'));
141
158
  for(const n of [1,2])assert(!fs.existsSync(path.join(f.root,'.cm-worktrees',f.batch.batchId.slice(0,8),'T-00'+n)));
142
159
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -145,12 +162,16 @@ test('new parallel batch merges reviewed members without committing private bind
145
162
  test('optimization-only serial batch freezes policy for later members after removing launch flag',async()=>{
146
163
  const f=fixture();f.args.push('--execution-optimizations');f.env.CM_WORKFLOW_HOME=path.join(f.root,'home');f.env.CM_WORKFLOW_LOG_HOME=path.join(f.root,'logs');
147
164
  try{
148
- const first=await execute(f,[]);assert.equal(first.result.state,'awaiting_review',first.stderr+JSON.stringify(first.result));
165
+ const held=requestFirstRevision(f,['T-001']);
166
+ const first=await execute(f,{args:held});assert.equal(first.result.state,'changes_requested',first.stderr+JSON.stringify(first.result));
167
+ assert.equal(first.result.code,'revision_answer_required');assert.equal(first.result.identity.attempt,2);
168
+ assert.deepEqual(first.calls,['T-001:develop','T-001:check']);
149
169
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');
150
170
  const statePath=n=>path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-00'+n),'state.json');
171
+ assert(!fs.existsSync(statePath(2)));
151
172
  assert.deepEqual(JSON.parse(fs.readFileSync(statePath(1))).records[0].payload.config.executionPolicy,EXECUTION_POLICY_V1);
152
173
  f.args=f.args.filter(arg=>arg!=='--execution-optimizations');
153
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
174
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
154
175
  for(const n of [1,2])assert.deepEqual(JSON.parse(fs.readFileSync(statePath(n))).records[0].payload.config.executionPolicy,EXECUTION_POLICY_V1);
155
176
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'});assert(!tracked.stdout.includes('.cm-external-models-v1.json'));
156
177
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -62,7 +62,7 @@ else for(const event of [{type:'thread.started',thread_id:dev?'fake-author':'fak
62
62
  const routes=resolveProtectedRuntimes(loadConfig({projectRoot:codeProject}),'codex');
63
63
  const execution=(selected=models,{legacy=false}={})=>createConversationExecution(definition,'fixture-host',bridge,
64
64
  legacy?((({effort,...rest})=>({...rest,model:'fixture-codex',preflight:{...rest.preflight,config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture-codex'})}}))(review)):review,
65
- 1,null,false,'codex',{
65
+ null,null,false,'codex',{
66
66
  ...(efficiency?{executionPolicy:EXECUTION_POLICY_V1}:{}),
67
67
  ...(!legacy?{externalModels:selected}:{}),
68
68
  ...(!session?{protection,providerDevelopment:{model:legacy?'fixture-codex':selected.providers.codex.model,
@@ -9,15 +9,9 @@ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
9
9
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
10
10
  import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
11
11
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
12
- import {writeHandoff,writeReview} from '../experiments/js-orchestration/native-gate-fixture.mjs';
12
+ import {writeHandoff,writeReview} from './fixtures/native-gate-fixture.mjs';
13
13
  import {acquireExternalRunGuard} from '../runtime/js/cm-ai/external-run-guard.mjs';
14
14
  import {memberSupersedeAdmitted} from './cm-ai-batch-run.mjs';
15
- const grant=(request,issuedAt)=>{
16
- const value={version:1,kind:'cm-review-dispatch-grant',grantId:'grant-'+request.invocationId,adapterId:'codex-review-adapter',
17
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,reviewerId:'reviewer',logicalContextId:request.contextId,
18
- packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'host',decisionId:'decision-'+request.invocationId,decision:'approved',issuedAt,expiresAt:issuedAt+60000};
19
- return {...value,grantDigest:digest(value)};
20
- };
21
15
  async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=false,policyOnly=false}={}){
22
16
  const tmp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-external-recovery-'))),root=path.join(tmp,'code'),specsRoot=path.join(tmp,'specs');
23
17
  fs.mkdirSync(root);fs.mkdirSync(specsRoot);fs.mkdirSync(path.join(specsRoot,'feature'));fs.mkdirSync(path.join(specsRoot,'.reviews'));
@@ -33,7 +27,7 @@ async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=f
33
27
  }},reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,contexts:['review-1','review-2'],run:(request,control)=>{calls++;const result=review(request,control);if(result?.status==='succeeded')writeReview(path.join(specsRoot,'.reviews/feature-T-001-r'+request.identity.attempt+'.md'),path.join(specsRoot,'.reviews/feature-T-001-a'+request.identity.attempt+'-handoff.json'),request.identity.attempt,result.value.verdict);return result;}}],
34
28
  check:()=>[{id:'check',command:['controlled'],outcome:'passed',exitCode:0,evidence:'fixture'}],
35
29
  taskCompletion:{reviewsDir:path.join(specsRoot,'.reviews'),handoffs:[path.join(specsRoot,'.reviews/feature-T-001-a1-handoff.json'),path.join(specsRoot,'.reviews/feature-T-001-a2-handoff.json')]},
36
- reviewInvocation:{developerThreadId:'developer-thread',excludedThreadIds:['host'],hostContextId:'host',authorize:(request,{authorizationAt})=>grant(request,authorizationAt)}};
30
+ reviewInvocation:{developerThreadId:'developer-thread',excludedThreadIds:['host'],hostContextId:'host'}};
37
31
  const make=mode=>createTaskRunner({...options,persistence:{store,mode,version:3}});
38
32
  const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
39
33
  const records=()=>store.snapshot().records;
@@ -110,7 +104,7 @@ test('valid changes_requested permits a fresh separately authorized second attem
110
104
  const runner=f.make();await runner.executeEffect(f.effect('develop'));assert.equal((await runner.executeEffect(f.effect('review'))).state,'changes_requested');
111
105
  await runner.executeEffect(f.effect('develop',2));assert.equal((await runner.executeEffect(f.effect('review',2))).state,'approved');
112
106
  const done=await runner.executeEffect(f.effect('complete',2));assert.equal(done.state,'fixture_completed',JSON.stringify(done));assert.equal(f.calls(),2);
113
- const registered=f.records().filter(row=>row.payload.type==='review-invocation-registered');assert.equal(registered.length,2);assert.notEqual(registered[0].payload.grant.invocationId,registered[1].payload.grant.invocationId);
107
+ const registered=f.records().filter(row=>row.payload.type==='review-invocation-registered');assert.equal(registered.length,2);assert.notEqual(registered[0].payload.binding.invocationId,registered[1].payload.binding.invocationId);
114
108
  assert.throws(()=>f.guard({identity:{repositoryId:'fixture',runId:'next-task-run',taskId:'T-002',attempt:1}}),{code:'external_prior_writer_active'});
115
109
  f.closeStore();
116
110
  const next=f.guard({identity:{repositoryId:'fixture',runId:'next-task-run',taskId:'T-002',attempt:1}});next.close();assert.equal(f.calls(),2);
@@ -58,7 +58,7 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0,exter
58
58
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
59
59
  }};
60
60
  const executionFor=live=>{
61
- const execution=createConversationExecution(definition,live,bridge,review,1,workflow,true,'codex',
61
+ const execution=createConversationExecution(definition,live,bridge,review,null,workflow,true,'codex',
62
62
  live===A?{}:{originalHostContextId:A});
63
63
  execution.check=createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]});
64
64
  execution.reviewers[0].run=async(request,{onEvent})=>{
@@ -25,13 +25,6 @@ import {createClaudeReviewRun} from '../runtime/js/cm-ai/claude-review-adapter.m
25
25
 
26
26
 
27
27
  const checks=[{id:'check',command:['synthetic'],outcome:'passed',exitCode:0,evidence:'fixture'}];
28
- const grantFor=(request,authorizationAt,change=grant=>grant)=>{
29
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.invocationId}`,adapterId:`${request.provider}-review-adapter`,
30
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
31
- reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
32
- hostContextId:'actual-main',decisionId:'decision-1',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
33
- change(body);return {...body,grantDigest:digest(body)};
34
- };
35
28
  const events=(onEvent,thread='actual-review')=>{
36
29
  onEvent({event:'thread.started',provider_thread:thread});
37
30
  onEvent({event:'turn.started',item_type:null});
@@ -40,7 +33,7 @@ const events=(onEvent,thread='actual-review')=>{
40
33
  onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
41
34
  };
42
35
 
43
- async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='codex'}={}) {
36
+ async function fixture(fn,{reviewRun,times,timeoutMs=1000,provider='codex'}={}) {
44
37
  const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-v3-')));
45
38
  const root=path.join(temp,'code'),specsRoot=path.join(temp,'specs'),reviewsDir=path.join(specsRoot,'.reviews');
46
39
  fs.mkdirSync(root);fs.mkdirSync(reviewsDir,{recursive:true});
@@ -64,8 +57,7 @@ async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='co
64
57
  dispatches++;lateEvent=control.onEvent;return (reviewRun??defaultRun)(request,control);
65
58
  }}],check:()=>checks,
66
59
  taskCompletion:{reviewsDir,handoffs:[path.join(reviewsDir,'a1.json'),path.join(reviewsDir,'a2.json')]},
67
- reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
68
- authorize:authorize??((request,{authorizationAt})=>grantFor(request,authorizationAt))}};
60
+ reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main']}};
69
61
  const make=mode=>{
70
62
  const old=Date.now,values=times?[...times]:null;if(values)Date.now=()=>values.length>1?values.shift():values[0];
71
63
  try{return createTaskRunner({...options,persistence:{store,mode,version:3}});}finally{Date.now=old;}
@@ -127,7 +119,7 @@ for(const provider of ['codex','claude'])test(`${provider} late terminal receipt
127
119
  assert.equal(f.dispatches(),1);
128
120
  },{timeoutMs:20,provider,reviewRun:lateReceiptRun({duplicate:true})}));
129
121
 
130
- test('reconciled provider failure spends the original one-retry budget and requires a fresh grant',()=>fixture(async f=>{
122
+ test('reconciled provider failure spends the original one-retry budget and requires a fresh request binding',()=>fixture(async f=>{
131
123
  const runner=f.make();await runner.executeEffect(f.effect('develop'));
132
124
  const first=await runner.executeEffect(f.effect('review'));
133
125
  const after=runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
@@ -135,7 +127,7 @@ test('reconciled provider failure spends the original one-retry budget and requi
135
127
  const second=await runner.executeEffect(retryEffect(f));assert.equal(second.state,'unknown');
136
128
  const final=runner.reconcileReview({invocationId:second.reviewReconciliation.invocationId});
137
129
  assert.equal(final.state,'blocked');assert.equal(final.code,'review_provider_failed');assert.equal(f.dispatches(),2);
138
- assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,second.reviewInvocation.registration.grant.grantDigest);
130
+ assert.notEqual(first.reviewInvocation.registration.binding.requestDigest,second.reviewInvocation.registration.binding.requestDigest);
139
131
  assert.equal((await runner.executeEffect({...retryEffect(f),id:'third-review'})).code,'stage_mismatch');
140
132
  assert.equal(f.dispatches(),2);assert.deepEqual(f.reopen().status(),final);
141
133
  },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true})}));
@@ -147,7 +139,7 @@ test('replay rejects receipt or reconciliation bindings even when an attacker re
147
139
  const original=f.getStore().snapshot().records;
148
140
  for(const [type,key,value] of [
149
141
  ['review-invocation-receipt','invocationId','other-call'],['review-invocation-receipt','effectId','review-2'],
150
- ['review-invocation-receipt','registeredDigest',digest('other-grant')],
142
+ ['review-invocation-receipt','registeredDigest',digest('other-registration')],
151
143
  ['review-invocation-receipt','startedDigest',digest('other-thread')],
152
144
  ['review-invocation-receipt','resultDigest',digest('other-result')],
153
145
  ['review-invocation-reconciled','receiptDigest',digest('other-receipt')],
@@ -160,16 +152,6 @@ test('replay rejects receipt or reconciliation bindings even when an attacker re
160
152
  assert.deepEqual(f.getStore().snapshot().records,original);assert.equal(f.dispatches(),1);
161
153
  },{timeoutMs:20,reviewRun:lateReceiptRun()}));
162
154
 
163
- test('reconciliation is not dispatch approval and the original grant cannot authorize another invocation',()=>{
164
- let originalGrant;
165
- return fixture(async f=>{
166
- const runner=f.make();await runner.executeEffect(f.effect('develop'));
167
- const first=await runner.executeEffect(f.effect('review'));
168
- runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
169
- assert.equal((await runner.executeEffect(retryEffect(f))).code,'authorization_invalid');
170
- assert.equal(f.dispatches(),1);
171
- },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true}),authorize:(request,{authorizationAt})=>originalGrant??=grantFor(request,authorizationAt)});
172
- });
173
155
 
174
156
  for(const [name,change] of [
175
157
  ['only local exit',r=>{r.events=r.events.filter(e=>!['item.completed','turn.completed'].includes(e.event));r.result={status:'failed',code:'incomplete_result'};}],
@@ -241,7 +223,7 @@ setInterval(()=>{},1000);
241
223
  const retry=await resumed.executeEffect(retryEffect(f));assert.equal(retry.state,'unknown');
242
224
  const exhausted=resumed.reconcileReview({invocationId:retry.reviewReconciliation.invocationId});
243
225
  assert.equal(exhausted.state,'blocked');assert.equal(spawns,2);
244
- assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,retry.reviewInvocation.registration.grant.grantDigest);
226
+ assert.notEqual(first.reviewInvocation.registration.binding.requestDigest,retry.reviewInvocation.registration.binding.requestDigest);
245
227
  }
246
228
  },{provider,timeoutMs:2000}));
247
229
 
@@ -180,7 +180,7 @@ test('one authorized CLI continuation preserves old history and reaches the orig
180
180
  await resumed.reviewFinal();assert.equal(f.calls(),2);assert.equal(f.repairs(),1);
181
181
  });
182
182
 
183
- for(const mode of ['loss-again','reuse-thread','approved','changes_requested'])test(`continuation refuses unsafe reuse: ${mode}`,{timeout:10000},async t=>{
183
+ for(const mode of ['loss-again','reuse-thread','approved','changes_requested'])test(`continuation refuses unsafe reuse: ${mode}`,{timeout:FIXTURE_TIMEOUT_MS},async t=>{
184
184
  const f=await fixture(t,mode);
185
185
  if(['approved','changes_requested'].includes(mode)){
186
186
  await f.cli([f.request],['--allow-final-review-recovery']).then(rows=>assert.equal(rows[0].error.code,'host_request_failed'));
@@ -0,0 +1,33 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {EventEmitter} from 'node:events';
4
+ import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
5
+
6
+ function fixture(){
7
+ const child=new EventEmitter();child.pid=123;child.stdout=new EventEmitter();child.stderr=new EventEmitter();
8
+ let clock=10;const trace=hostDiagnostic(child,{timeoutMs:60000,now:()=>clock});
9
+ return {child,trace,tick:ms=>{clock+=ms;}};
10
+ }
11
+ test('fixture diagnostics retain last stage, time budget and child exit without changing the failure',()=>{
12
+ const {child,trace,tick}=fixture();trace.send({operation:'advance',requestId:'private-request'});tick(30);
13
+ trace.receive({type:'host_request',kind:'develop',payload:{private:'source'}});tick(50);
14
+ trace.receive({result:{state:'blocked',code:'develop_answer_missing'}});
15
+ child.stderr.emit('data',Buffer.from('private stderr'));child.emit('close',7,'SIGTERM');
16
+ const failure=new Error('fixture failure');assert.equal(trace.attach(failure),failure);
17
+ const data=failure.diagnostic;
18
+ assert.equal(data.timeoutMs,60000);assert.equal(data.elapsedMs,80);assert.equal(data.lastKind,'develop');
19
+ assert.equal(data.lastState,'blocked');assert.equal(data.lastCode,'develop_answer_missing');
20
+ assert.equal(data.exitCode,7);assert.equal(data.signal,'SIGTERM');assert.equal(data.closed,true);
21
+ assert.equal(data.stderrBytes,14);assert.equal(data.lastOperation,'advance');
22
+ assert(!JSON.stringify(data).includes('private'));
23
+ });
24
+ test('fixture diagnostics bound history and allowlist even hostile metadata',()=>{
25
+ const {child,trace}=fixture(),secret='private-synthetic-secret';
26
+ for(let i=0;i<80;i++)trace.receive({type:secret,kind:secret,requestId:secret,
27
+ result:{state:secret,code:secret},payload:{text:secret}});
28
+ child.stdout.emit('data',Buffer.from(secret));child.stderr.emit('data',Buffer.from(secret));child.emit('close',null,secret);
29
+ const data=trace.snapshot();assert.equal(data.events.length,32);assert.equal(data.eventCount,80);
30
+ assert.equal(data.lastKind,'other');assert.equal(data.lastCode,'other');assert.equal(data.signal,'other');
31
+ assert(!JSON.stringify(data).includes(secret));assert(JSON.stringify(data).length<6000);
32
+ data.events[0].kind=secret;assert(!JSON.stringify(trace.snapshot()).includes(secret));
33
+ });
@@ -0,0 +1,150 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {PassThrough} from 'node:stream';
4
+ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
5
+ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
6
+ import {beginHostStage} from '../runtime/js/cm-ai/host-stage-observer.mjs';
7
+
8
+ const tick=()=>new Promise(resolve=>setImmediate(resolve));
9
+ async function waitFor(rows,predicate,timeout=1500){
10
+ const end=Date.now()+timeout;
11
+ while(Date.now()<end){const found=rows.find(predicate);if(found)return found;await new Promise(resolve=>setTimeout(resolve,5));}
12
+ assert.fail(`missing row: ${JSON.stringify(rows)}`);
13
+ }
14
+ function session(handle,{heartbeat=false}={}){
15
+ const input=new PassThrough(),output=new PassThrough(),rows=[],bridge=createHostToolBridge();
16
+ output.on('data',chunk=>{for(const line of chunk.toString().trim().split('\n'))if(line)rows.push(JSON.parse(line));});
17
+ const serving=serveCmAiHost({host:{handle:(request)=>handle(request,bridge)},input,output,toolBridge:bridge,heartbeat});
18
+ return {rows,bridge,input,serving,send:row=>input.write(JSON.stringify(row)+'\n')};
19
+ }
20
+
21
+ test('host busy explains active request and close refuses a running operation without stopping it',async()=>{
22
+ let resolve;const done=new Promise(r=>{resolve=r;});
23
+ const s=session(async()=>{await done;return {outcome:'complete'};});
24
+ try{
25
+ const ready=await waitFor(s.rows,r=>r.type==='host_ready');
26
+ s.send({requestId:'first',operation:'advance'});await tick();
27
+ s.send({requestId:'second',operation:'advance'});
28
+ const busy=await waitFor(s.rows,r=>r.requestId==='second');
29
+ assert.equal(busy.error.code,'host_busy');assert.equal(busy.error.inFlight.requestId,'first');
30
+ assert.equal(busy.error.inFlight.operation,'advance');assert.equal(busy.error.inFlight.stage,'advance');
31
+ assert.ok(Number.isFinite(Date.parse(busy.error.inFlight.startedAt)));assert.match(busy.error.message,/继续等待/);
32
+ s.send({type:'host_close',sessionId:ready.sessionId});
33
+ const refused=await waitFor(s.rows,r=>r.type==='host_response');
34
+ assert.equal(refused.code,'host_close_busy');assert.equal(refused.accepted,false);
35
+ assert.equal(refused.inFlight.requestId,'first');
36
+ resolve();await waitFor(s.rows,r=>r.requestId==='first');
37
+ s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
38
+ assert.equal(s.rows.at(-1).closing,true);
39
+ }finally{resolve();s.input.end();await s.serving;}
40
+ });
41
+
42
+ test('bridge close validates session and force, exposes metadata only and preserves pending reply',async()=>{
43
+ const bridge=createHostToolBridge(),rows=[];bridge.attach(row=>{rows.push(row);});
44
+ const pending=bridge.call('develop',{secret:'never expose this'},new AbortController().signal,{timeoutMs:1000});
45
+ try{
46
+ await tick();const request=rows.find(r=>r.type==='host_request'),snapshot=bridge.inFlight();
47
+ assert.deepEqual(Object.keys(snapshot).sort(),['callId','deadlineMs','kind','startedAt']);
48
+ assert.equal(snapshot.kind,'develop');assert.equal(snapshot.deadlineMs-Date.parse(snapshot.startedAt),1000);
49
+ assert.equal(bridge.accept({type:'host_close',sessionId:'wrong',force:true}).code,'host_response_mismatch');
50
+ assert.equal(bridge.accept({type:'host_close',sessionId:request.sessionId,force:'true'}).code,'host_response_mismatch');
51
+ assert.equal(bridge.accept({type:'host_close',sessionId:request.sessionId}).code,'host_close_busy');
52
+ assert.equal(bridge.accept({...request,type:'host_result',kind:undefined,payload:undefined}).accepted,false);
53
+ const result={type:'host_result',sessionId:request.sessionId,callId:request.callId,requestDigest:request.requestDigest,result:{ok:true}};
54
+ assert.equal(bridge.accept(result).accepted,true);assert.deepEqual(await pending,{ok:true});
55
+ assert.equal(bridge.inFlight(),null);assert.equal(bridge.accept({type:'host_close',sessionId:request.sessionId}).closing,true);
56
+ }finally{bridge.close();await pending.catch(()=>{});}
57
+ });
58
+
59
+ test('forced close explicitly warns and interrupts a pending bridge call',{timeout:3000},async()=>{
60
+ const s=session(async(request,bridge)=>{try{await bridge.call('develop',{},new AbortController().signal);return {bad:true};}catch(error){return {code:error.code};}});
61
+ try{
62
+ const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'active',operation:'advance'});
63
+ await waitFor(s.rows,r=>r.type==='host_request');s.send({type:'host_close',sessionId:ready.sessionId,force:true});
64
+ const closed=await waitFor(s.rows,r=>r.type==='host_response');assert.equal(closed.closing,true);
65
+ await s.serving;assert.match(closed.warning,/unknown/);
66
+ assert.equal(s.rows.find(r=>r.requestId==='active').result.code,'host_disconnected');
67
+ }finally{s.input.end();await s.serving;}
68
+ });
69
+
70
+ test('heartbeat is opt-in, contains no payload, and idle ticks do not claim progress or poll runner',{timeout:14000},async()=>{
71
+ let calls=0;const s=session(async(request,bridge)=>{calls++;return bridge.call('check',{private:'payload'},new AbortController().signal,{timeoutMs:13000});},{heartbeat:true});
72
+ try{
73
+ const ready=await waitFor(s.rows,r=>r.type==='host_ready');assert.deepEqual(ready.heartbeat,{intervalMs:5000,timeoutMs:30000});
74
+ const first=await waitFor(s.rows,r=>r.type==='host_heartbeat');assert.equal(first.inFlight,null);
75
+ s.send({requestId:'check',operation:'advance'});const request=await waitFor(s.rows,r=>r.type==='host_request');
76
+ const beat=await waitFor(s.rows,r=>r.type==='host_heartbeat'&&r.inFlight?.call,6000);
77
+ assert.equal(beat.inFlight.stage,'check');assert.equal(beat.inFlight.call.kind,'check');assert.equal(beat.pid,process.pid);
78
+ assert.equal(beat.sessionId,ready.sessionId);assert.equal(calls,1);assert.equal(JSON.stringify(beat).includes('payload'),false);
79
+ assert.equal(beat.lastProgressAt,beat.inFlight.call.startedAt);
80
+ const second=await waitFor(s.rows,r=>r.type==='host_heartbeat'&&r.at!==beat.at&&r.inFlight?.call,6000);
81
+ assert.equal(second.lastProgressAt,beat.lastProgressAt);assert.deepEqual(second.inFlight,beat.inFlight);
82
+ s.send({type:'host_result',sessionId:ready.sessionId,callId:request.callId,requestDigest:request.requestDigest,result:{ok:true}});
83
+ await waitFor(s.rows,r=>r.requestId==='check');s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
84
+ const old=session(async()=>({ok:true}));const oldReady=await waitFor(old.rows,r=>r.type==='host_ready');
85
+ assert.equal(oldReady.heartbeat,undefined);assert.equal(old.rows.some(r=>r.type==='host_heartbeat'),false);
86
+ old.send({type:'host_close',sessionId:oldReady.sessionId});await old.serving;
87
+ }finally{s.input.end();await s.serving;}
88
+ });
89
+
90
+ for(const operation of ['status','cancel'])test(`close refuses in-flight ${operation} control`,async()=>{
91
+ let resolve;const done=new Promise(r=>{resolve=r;});const s=session(async()=>{await done;return {ok:true};});
92
+ try{
93
+ const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'control',operation});await tick();
94
+ s.send({type:'host_close',sessionId:ready.sessionId});
95
+ const refused=await waitFor(s.rows,r=>r.type==='host_response');
96
+ assert.equal(refused.code,'host_close_busy');assert.equal(refused.inFlight.operation,operation);
97
+ resolve();await waitFor(s.rows,r=>r.requestId==='control');s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
98
+ }finally{resolve();s.input.end();await s.serving;}
99
+ });
100
+
101
+ test('poll reusing requestId cannot release a different running operation',async()=>{
102
+ let resolve;const done=new Promise(r=>{resolve=r;});const s=session(async request=>{
103
+ if(request.operation==='advance')await done;return {operation:request.operation};
104
+ });
105
+ try{
106
+ const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'same',operation:'advance'});await tick();
107
+ s.send({requestId:'same',operation:'status'});await waitFor(s.rows,r=>r.result?.operation==='status');
108
+ s.send({type:'host_close',sessionId:ready.sessionId});
109
+ const refused=await waitFor(s.rows,r=>r.type==='host_response');assert.equal(refused.code,'host_close_busy');
110
+ assert.equal(refused.inFlight.operation,'advance');resolve();await waitFor(s.rows,r=>r.result?.operation==='advance');
111
+ s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
112
+ }finally{resolve();s.input.end();await s.serving;}
113
+ });
114
+
115
+ test('close sent synchronously when the result is written is allowed',async()=>{
116
+ const input=new PassThrough(),output=new PassThrough(),bridge=createHostToolBridge(),rows=[];let sessionId;
117
+ output.on('data',chunk=>{for(const line of chunk.toString().trim().split('\n'))if(line){
118
+ const row=JSON.parse(line);rows.push(row);
119
+ if(row.type==='host_ready'){sessionId=row.sessionId;input.write(JSON.stringify({requestId:'instant',operation:'advance'})+'\n');}
120
+ if(row.requestId==='instant')input.write(JSON.stringify({type:'host_close',sessionId})+'\n');
121
+ }});
122
+ const serving=serveCmAiHost({host:{handle:async()=>({ok:true})},input,output,toolBridge:bridge});
123
+ try{const closed=await waitFor(rows,r=>r.type==='host_response');assert.equal(closed.closing,true);await serving;assert.equal(rows.some(r=>r.code==='host_close_busy'),false);}
124
+ finally{input.end();await serving;}
125
+ });
126
+
127
+ test('CM_HOST_HEARTBEAT enables the wire contract without changing host operations',async()=>{
128
+ const previous=process.env.CM_HOST_HEARTBEAT;process.env.CM_HOST_HEARTBEAT='1';
129
+ const input=new PassThrough(),output=new PassThrough(),bridge=createHostToolBridge(),rows=[];
130
+ output.on('data',chunk=>{for(const line of chunk.toString().trim().split('\n'))if(line)rows.push(JSON.parse(line));});
131
+ const serving=serveCmAiHost({host:{handle:async()=>assert.fail('heartbeat must not invoke host')},input,output,toolBridge:bridge});
132
+ try{
133
+ const ready=await waitFor(rows,r=>r.type==='host_ready');assert.deepEqual(ready.heartbeat,{intervalMs:5000,timeoutMs:30000});
134
+ await waitFor(rows,r=>r.type==='host_heartbeat');input.write(JSON.stringify({type:'host_close',sessionId:ready.sessionId})+'\n');await serving;
135
+ }finally{input.end();await serving;if(previous===undefined)delete process.env.CM_HOST_HEARTBEAT;else process.env.CM_HOST_HEARTBEAT=previous;}
136
+ });
137
+
138
+ test('native stage exposes its real budget without requiring a bridge call',async()=>{
139
+ let resolve;const done=new Promise(r=>{resolve=r;});const s=session(async()=>{
140
+ const end=beginHostStage('check',5000);try{await done;return {ok:true};}finally{end();}
141
+ });
142
+ try{
143
+ const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'native',operation:'advance'});await tick();
144
+ s.send({requestId:'duplicate',operation:'advance'});const busy=await waitFor(s.rows,r=>r.requestId==='duplicate');
145
+ assert.equal(busy.error.inFlight.stage,'check');assert.equal(busy.error.inFlight.call,null);
146
+ const stage=busy.error.inFlight.nativeStage;assert.equal(stage.kind,'check');assert.equal(stage.deadlineMs-Date.parse(stage.startedAt),5000);
147
+ s.send({type:'host_close',sessionId:ready.sessionId});assert.equal((await waitFor(s.rows,r=>r.type==='host_response')).code,'host_close_busy');
148
+ resolve();await waitFor(s.rows,r=>r.requestId==='native');s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
149
+ }finally{resolve();s.input.end();await s.serving;}
150
+ });
@@ -84,8 +84,7 @@ for(const transport of ['synchronous','jsonl','coalesced-jsonl'])test(`incident
84
84
  const seen=[];
85
85
  const answer=row=>{
86
86
  seen.push(row.kind==='qa_assess'?row.kind:row.payload.case.id);
87
- if(row.kind==='qa_assess')return {scores:{scope:1,risk:1,accumulation:1,boundary:1},
88
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
87
+ if(row.kind==='qa_assess')return {confirmed:true};
89
88
  if(row.kind==='qa_logic')return {verdict:'SUPPORTED',evidence:['Synthetic static observation']};
90
89
  const artifact=path.join(f.configuration.specsDir,'.reviews',`${row.payload.case.id}.txt`);
91
90
  fs.writeFileSync(artifact,'Synthetic browser evidence; no real browser');
@@ -4,26 +4,38 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {inspectCmAiQaTaskContext} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
7
- import {createHostQaDecisionProvider,decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
7
+ import {createHostQaDecisionProvider,decideHostQaPolicy,readQaAssessment} from '../runtime/js/cm-ai/host-qa-policy.mjs';
8
8
 
9
- const low=()=>({scores:{scope:1,risk:1,accumulation:1,boundary:1},
10
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
11
- test('N6 enforces mandatory triggers ahead of low scores and bounds the API merge exemption',()=>{
12
- const input={assessment:low(),pending:2,mergeEligible:false,unassessedTasks:1};
13
- assert.equal(decideHostQaPolicy(input).status,'skipped');
9
+ const low=()=>({confirmed:true});
10
+ const basePolicy=()=>({changedFiles:['src/ordinary.mjs'],criticalPaths:{},pending:2,mergeEligible:false,unassessedTasks:1});
11
+ test('N6 no_fixed_trigger is skipped with null score, without model risk inputs',()=>{
12
+ assert.deepEqual(decideHostQaPolicy(basePolicy()),{status:'skipped',score:null,reason:'no_fixed_trigger'});
13
+ const input=basePolicy();
14
14
  assert.equal(decideHostQaPolicy({...input,pending:0}).reason,'feature_complete');
15
15
  assert.equal(decideHostQaPolicy({...input,unassessedTasks:5}).reason,'five_tasks_without_qa');
16
- for(const field of Object.keys(input.assessment.changes)){
17
- const assessment=low();assessment.changes[field]=true;
18
- assert.equal(decideHostQaPolicy({...input,assessment}).status,'triggered',field);
16
+ });
17
+ test('N6 registered path matching triggers all categories and bounds API merge',()=>{
18
+ const input=basePolicy();
19
+ for(const name of ['migration','authentication','authorization','payment','api']){
20
+ const criticalPaths={[name]:['src/**/critical?.mjs']};
21
+ assert.deepEqual(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/critical1.mjs']}),
22
+ {status:'triggered',score:null,reason:name});
23
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/deep/critical2.mjs']}).reason,name);
24
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/critical12.mjs']}).status,'skipped');
19
25
  }
20
- const assessment=low();assessment.changes.api=true;
21
- assert.equal(decideHostQaPolicy({...input,assessment,pending:1,mergeEligible:true}).reason,'merged_to_feature_qa');
22
- assessment.changes.payment=true;
23
- assert.equal(decideHostQaPolicy({...input,assessment,pending:1,mergeEligible:true}).reason,'payment');
24
- const high=low();high.scores.risk=5;
25
- assert.deepEqual(decideHostQaPolicy({...input,assessment:high}),{status:'triggered',score:8,reason:'risk_score'});
26
- high.scores.risk=0;assert.throws(()=>decideHostQaPolicy({...input,assessment:high}),{code:'qa_assessment_invalid'});
26
+ const criticalPaths={api:['src/api/*'],payment:['src/pay.mjs'],migration:['db/schema.sql']};
27
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/api/a.mjs'],pending:1,mergeEligible:true}).reason,'merged_to_feature_qa');
28
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/api/deep/a.mjs']}).reason,'no_fixed_trigger');
29
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['db/schema.sql','src/pay.mjs','src/api/a.mjs'],pending:0,unassessedTasks:5}).reason,
30
+ 'feature_complete,migration,payment,five_tasks_without_qa,api');
31
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/pay.mjs','src/api/a.mjs'],pending:1,mergeEligible:true}).reason,'payment');
32
+ });
33
+ test('N6 rejects unsafe registry and paths rather than silently missing triggers',()=>{
34
+ const input=basePolicy();
35
+ for(const criticalPaths of [{unknown:['a']},{api:'a'},{api:['../a']},{api:['/a']},{api:['src/{a,b}.mjs']},{api:['src/[ab].mjs']},{api:['src/**x.mjs']},{api:['src\\a.mjs']}])
36
+ assert.throws(()=>decideHostQaPolicy({...input,criticalPaths}));
37
+ for(const changedFiles of [['../a'],['/a'],['a\\b'],['a','a'],['a//b']])
38
+ assert.throws(()=>decideHostQaPolicy({...input,changedFiles}));
27
39
  });
28
40
 
29
41
  test('N6 derives consecutive work from original task inventory and QA log without a counter store',async()=>{
@@ -53,6 +65,15 @@ test('N6 derives consecutive work from original task inventory and QA log withou
53
65
  const skips=rows.map(row=>({...row,status:'skipped',score:4}));
54
66
  fs.writeFileSync(log,[oldCurrent,...skips].map(row=>JSON.stringify(row)).join('\n')+'\n');
55
67
  assert.equal((await decide()).reason,'five_tasks_without_qa');assert.equal(seen.at(-1),5);
68
+ const sourced=createHostQaDecisionProvider({timeoutMs:1000,criticalPaths:{payment:['source.js']},assess:async request=>{
69
+ assert.deepEqual(request.changedFiles,{paths:['source.js'],source:'review_package'});
70
+ assert.deepEqual(request.criticalPaths,{payment:['source.js']});
71
+ assert.equal(Object.hasOwn(request,'scores'),false);assert.equal(Object.hasOwn(request,'changes'),false);
72
+ return {confirmed:true};}});
73
+ const sourceBinding={...binding,changedFiles:{paths:['source.js'],source:'review_package'}};
74
+ const sourcedDecision=await sourced.decide(sourceBinding,new AbortController().signal);
75
+ assert.equal(sourcedDecision.reason,'payment,five_tasks_without_qa');assert.equal(sourcedDecision.changedFilesSource,'review_package');
76
+ await assert.rejects(sourced.decide(binding,new AbortController().signal),{code:'qa_policy_unavailable'});
56
77
  const stale=createHostQaDecisionProvider({timeoutMs:1000,assess:async()=>{
57
78
  fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [x] T-005: task\n');return low();}});
58
79
  await assert.rejects(stale.decide(binding,new AbortController().signal),{code:'stale_qa'});
@@ -91,3 +112,9 @@ test('step30 unseen excludes closed features, includes other open features, and
91
112
  await decide();assert.equal(seen.at(-1),2);
92
113
  }finally{fs.rmSync(root,{recursive:true,force:true});}
93
114
  });
115
+
116
+ test('qa_assess confirms only inventory source and rejects self-reported scores or risk flags',()=>{
117
+ assert.deepEqual(readQaAssessment({confirmed:true}),{confirmed:true});
118
+ for(const value of [{confirmed:false},{confirmed:true,scores:{scope:5}},{confirmed:true,changes:{api:true}},
119
+ {scores:{scope:1,risk:1,accumulation:1,boundary:1},changes:{api:false}}])assert.throws(()=>readQaAssessment(value));
120
+ });