@aibyzero/cm-workflow 0.16.5 → 0.16.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +19 -1
  4. package/README.md +17 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +28 -7
  17. package/docs/js-workflow-control.md +96 -6
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/untested-branches.md +27 -4
  21. package/docs/user-guide.md +23 -8
  22. package/install-codex.sh +28 -11
  23. package/package.json +1 -1
  24. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  25. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  26. package/runtime/js/cm-ai/cm-ai-admission.mjs +34 -10
  27. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  28. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
  29. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
  30. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  31. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  32. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  33. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  34. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  35. package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
  36. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  37. package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
  38. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  39. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  40. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  41. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  42. package/runtime/js/cm-ai/external-models.mjs +52 -0
  43. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  44. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  45. package/runtime/js/cm-ai/host-check.mjs +30 -4
  46. package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
  47. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  48. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  49. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +54 -8
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  52. package/runtime/js/cm-ai/host-session.mjs +1 -1
  53. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  54. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  55. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  56. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  57. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  58. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  59. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  60. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  61. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  62. package/runtime/js/cm-ai/operator-guidance.mjs +89 -0
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  64. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  65. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  66. package/runtime/js/cm-ai/review-package.mjs +11 -0
  67. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  68. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  69. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  70. package/runtime/js/cm-ai/task-runner.mjs +176 -25
  71. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  72. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  73. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  74. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  75. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  76. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  77. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  78. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  79. package/runtime/js/cm-fix/execution.mjs +183 -40
  80. package/runtime/js/cm-fix/final-review.mjs +18 -10
  81. package/runtime/js/cm-fix/finish.mjs +2 -19
  82. package/runtime/js/cm-fix/host-review.mjs +25 -6
  83. package/runtime/js/cm-fix/host.mjs +4 -1
  84. package/runtime/js/cm-fix/layout.mjs +1 -1
  85. package/runtime/js/cm-fix/log-events.mjs +29 -0
  86. package/runtime/js/cm-fix/metrics.mjs +3 -2
  87. package/runtime/js/cm-fix/progress.mjs +4 -0
  88. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  89. package/runtime/js/cm-prd/analysis.mjs +5 -2
  90. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  91. package/runtime/js/cm-prd/review-host.mjs +2 -1
  92. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  93. package/runtime/js/cm-prd/review-time.mjs +29 -0
  94. package/runtime/js/cm-prd/session.mjs +53 -6
  95. package/runtime/js/cm-security/finalize.mjs +32 -0
  96. package/runtime/js/cm-test/recovery.mjs +4 -4
  97. package/runtime/review.md +5 -0
  98. package/runtime/task-gates.md +6 -0
  99. package/runtime/workflow-config.md +10 -1
  100. package/scripts/cm-ai-admission.mjs +14 -3
  101. package/scripts/cm-ai-batch-drive.mjs +52 -23
  102. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  103. package/scripts/cm-ai-batch-host.mjs +44 -16
  104. package/scripts/cm-ai-batch-run.mjs +77 -29
  105. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  106. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  107. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  108. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  109. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  110. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  111. package/scripts/cm-ai-drive.mjs +73 -28
  112. package/scripts/cm-ai-drive.test.mjs +119 -1
  113. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  114. package/scripts/cm-ai-host.mjs +79 -27
  115. package/scripts/cm-ai-host.test.mjs +88 -0
  116. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  117. package/scripts/cm-ai-progress.test.mjs +521 -0
  118. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  119. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  120. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  121. package/scripts/cm-ai-run.mjs +94 -19
  122. package/scripts/cm-ai-run.test.mjs +2 -1
  123. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  124. package/scripts/cm-check-drive.test.mjs +1 -0
  125. package/scripts/cm-check-runtime.sh +11 -0
  126. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  127. package/scripts/cm-claude-probe.test.mjs +1 -1
  128. package/scripts/cm-codex-plugin-metadata.py +83 -0
  129. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  130. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  131. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  132. package/scripts/cm-efficiency-offline.mjs +35 -0
  133. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  134. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  135. package/scripts/cm-efficiency-response.test.mjs +117 -0
  136. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  137. package/scripts/cm-external-batch-host.test.mjs +157 -0
  138. package/scripts/cm-external-fix-host.test.mjs +281 -0
  139. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  140. package/scripts/cm-external-group-models.test.mjs +60 -0
  141. package/scripts/cm-external-model-host.test.mjs +180 -0
  142. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  143. package/scripts/cm-external-models.test.mjs +89 -0
  144. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  145. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  146. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  147. package/scripts/cm-fix-drive.mjs +28 -13
  148. package/scripts/cm-fix-final-review.test.mjs +11 -6
  149. package/scripts/cm-fix-host.mjs +17 -10
  150. package/scripts/cm-fix-large-log.test.mjs +113 -0
  151. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  152. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  153. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  154. package/scripts/cm-host-qa-executor.test.mjs +329 -3
  155. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  156. package/scripts/cm-live-evidence.test.mjs +64 -0
  157. package/scripts/cm-log-event.mjs +34 -7
  158. package/scripts/cm-log-event.py +15 -0
  159. package/scripts/cm-model-setup.mjs +79 -0
  160. package/scripts/cm-prd-drive.mjs +32 -11
  161. package/scripts/cm-prd-drive.test.mjs +15 -0
  162. package/scripts/cm-prd-host.mjs +26 -6
  163. package/scripts/cm-prd-host.test.mjs +4 -0
  164. package/scripts/cm-prd-review-host.test.mjs +17 -0
  165. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  166. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  167. package/scripts/cm-release-smoke.sh +5 -1
  168. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  169. package/scripts/cm-runtime-i18n.mjs +15 -4
  170. package/scripts/cm-runtime-install.mjs +8 -4
  171. package/scripts/cm-runtime.mjs +116 -23
  172. package/scripts/cm-runtime.test.mjs +121 -12
  173. package/scripts/cm-security.test.mjs +32 -0
  174. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  175. package/scripts/cm-task-gate.mjs +146 -10
  176. package/scripts/cm-task-gate.py +1 -0
  177. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  178. package/scripts/cm-test-drive.mjs +10 -4
  179. package/scripts/cm-test-drive.test.mjs +14 -1
  180. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  181. package/scripts/cm-usage-report.py +22 -3
  182. package/scripts/cm-workflow-config.mjs +10 -1
  183. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  184. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  185. package/scripts/fixtures/process-cleanup.mjs +3 -1
  186. package/scripts/test-cm-native-usage.py +62 -0
  187. package/scripts/test-external-model-setup.py +91 -0
  188. package/scripts/test-model-configuration-write.py +201 -0
  189. package/scripts/test-npm-install.py +10 -1
  190. package/skills/cm-ai/SKILL.md +2 -2
  191. package/skills/cm-ai/references/N1-init.md +1 -1
  192. package/skills/cm-ai/references/N8-finish.md +5 -0
  193. package/skills/cm-ai/references/js-host.md +16 -7
  194. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  195. package/skills/cm-fix/SKILL.md +1 -1
  196. package/skills/cm-fix/references/js-host.md +30 -2
  197. package/skills/cm-prd/SKILL.md +5 -4
  198. package/skills/cm-prd/references/spec-self-check.md +3 -1
  199. package/skills/cm-runtime/SKILL.md +29 -6
  200. package/skills/cm-security/SKILL.md +4 -2
  201. package/skills/cm-security/references/scan-contract.md +1 -0
  202. package/templates/cm-workflow.yml +1 -1
@@ -6,7 +6,7 @@ import {fileURLToPath} from 'node:url';
6
6
  import {inspectCmAiAdmission,approveCmAiSpecs,matchesCmAiTaskSelection,explainCmAiTaskSelection} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
7
7
  import {validateRunDefinition} from './cm-ai-run.mjs';
8
8
 
9
- const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve --approval-response TEXT (no --yes)] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
9
+ const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve --approval-response TEXT (no --yes)] [--feature N.slug] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
10
10
 
11
11
  function parse(argv){
12
12
  const result={codeProjects:[]};
@@ -26,7 +26,7 @@ function parse(argv){
26
26
  if(index+1>=argv.length||result.codeProjects.length>=16)throw new Error('invalid arguments');
27
27
  result.codeProjects.push(argv[++index]);continue;
28
28
  }
29
- const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse',
29
+ const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse','--feature':'feature',
30
30
  '--scope':'scope','--task':'task','--requirements':'requirements','--run-id':'runId','--repository-id':'repositoryId'}[flag];
31
31
  if(!key||index+1>=argv.length||Object.hasOwn(result,key))throw new Error('invalid arguments');
32
32
  result[key]=argv[++index];
@@ -40,6 +40,10 @@ function parse(argv){
40
40
 
41
41
  function buildRunDefinition(admission,input){
42
42
  if(!admission.codeProject)throw new Error('--print-run-definition requires one --code-project');
43
+ // An explicit feature never yields another feature's definition.
44
+ if(input.feature!==undefined&&admission.nextTask.feature!==input.feature)
45
+ throw Object.assign(new Error('feature_tasks_terminal'),{code:'feature_tasks_terminal',
46
+ reason:`所选 feature ${input.feature} 已无待办任务,不为其他 feature 生成运行定义;请明确选择下一个 feature`});
43
47
  const selected=input.task===undefined?admission.nextTask:{feature:admission.nextTask.feature,id:input.task};
44
48
  if(input.task!==undefined&&!matchesCmAiTaskSelection(admission,selected.feature,selected.id,{version:1,taskId:input.task}))
45
49
  throw Object.assign(new Error('task_selection_mismatch'),{code:'task_selection_mismatch',
@@ -57,7 +61,8 @@ function buildRunDefinition(admission,input){
57
61
  identity:{repositoryId,runId:input.runId??`${selected.feature.replace(/^\d+\./,'')}-${selected.id}`,
58
62
  taskId:selected.id,attempt:1},
59
63
  scope:list(input.scope),requirements:list(input.requirements),
60
- ...(input.task===undefined?{}:{taskSelection:{version:1,taskId:selected.id}})};
64
+ ...(input.task===undefined?{}:{taskSelection:{version:1,taskId:selected.id}}),
65
+ ...(input.feature===undefined?{}:{featureSelection:{version:1,feature:input.feature}})};
61
66
  return validateRunDefinition(definition);
62
67
  }
63
68
 
@@ -82,6 +87,12 @@ export function main(argv=process.argv.slice(2)){
82
87
  projectAdmissions:projectResults.map(item=>({codeProject:item.codeProject,state:item.state,reason:item.reason}))};
83
88
  if(result.state==='awaiting_spec_approval'&&(result.approvalIntent!=='explicit'||input.assumeYes))
84
89
  result.message='确认规格摘要后,用 --approval-response 传入用户原话,并明确回复“开始”。';
90
+ // An explicit feature with nothing left never prints a definition, whether the
91
+ // project still has other work (ready) or none (complete).
92
+ if(input.printRunDefinition&&!result.approveRefused&&input.feature!==undefined&&result.requestedFeatureComplete===input.feature){
93
+ process.stderr.write(`${JSON.stringify({error:{code:'feature_tasks_terminal',
94
+ reason:`所选 feature ${input.feature} 已无待办任务,不为其他 feature 生成运行定义;请明确选择下一个 feature`}})}\n`);return 1;
95
+ }
85
96
  if(input.printRunDefinition&&!result.approveRefused&&result.state==='ready'){
86
97
  try{process.stdout.write(`${JSON.stringify(buildRunDefinition(result,input))}\n`);return 0;}
87
98
  catch(error){process.stderr.write(`${JSON.stringify({error:{code:error.code??error.message,
@@ -13,10 +13,13 @@
13
13
  // status/cancel -> none: batch-run.mjs handle routes only these and advance;
14
14
  // host-session.mjs operationNames admits all three. Other operationNames belong
15
15
  // to child/single-task hosts and are not batch operations.
16
+ import {readBatchExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
17
+ import {readBatchExternalModels,batchModelsFile} from '../runtime/js/cm-ai/external-group-models.mjs';
18
+ import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
16
19
  import fs from 'node:fs';
17
20
  import path from 'node:path';
18
21
  import {fileURLToPath} from 'node:url';
19
- import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
22
+ import {createHostCheck,reportHostCheckProgress} from '../runtime/js/cm-ai/host-check.mjs';
20
23
  import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
21
24
  import {validateHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
22
25
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
@@ -30,12 +33,15 @@ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
30
33
  import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
31
34
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
32
35
 
36
+ import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
37
+
38
+ // PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
33
39
  const HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
34
40
  const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
35
41
  documentation_sync:'documentation-sync.json',documentation_inspect:'documentation-inspect.json'};
36
- const PAIRS=new Set(['--runtime','--review-config','--browser-qa','--protected-conversation-config',
42
+ const PAIRS=new Set(['--external-models-config','--runtime','--review-config','--browser-qa','--protected-conversation-config',
37
43
  '--protected-config','--allow-provider-development','--allow-review','--input-limit']);
38
- const FLAGS=new Set(['--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
44
+ const FLAGS=new Set(['--execution-optimizations','--external-models','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
39
45
  '--allow-bootstrap-write']);
40
46
  const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
41
47
  const nonempty=x=>typeof x==='string'&&x.trim().length>0;
@@ -57,11 +63,11 @@ function actualCwd(bundle,key,generation=1){
57
63
  const id=key.slice(key.lastIndexOf('/')+1);
58
64
  return path.resolve(bundle.batch.codeProject,'..','.cm-worktrees',bundle.batch.batchId.slice(0,8),id);
59
65
  }
60
- function checkCommandShape(commands,key,plan){
66
+ function checkCommandShape(commands,key,plan,executionPolicy){
61
67
  if(!Array.isArray(commands)||!commands.length||commands.length>32)stop(2,`任务 ${key} 会反问 check,但 PLAN.checks.${key} 缺少真实命令列表`);
62
68
  const ids=new Set();
63
69
  for(const item of commands){
64
- if(!isObject(item)||Object.keys(item).some(field=>!['id','command','timeoutMs'].includes(field))
70
+ if(!isObject(item)||Object.keys(item).some(field=>!['id','command','timeoutMs',...(executionPolicy?['sameExecutionAs']:[])].includes(field))
65
71
  ||!nonempty(item.id)||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item.id)
66
72
  ||ids.has(item.id)||!Array.isArray(item.command)||!item.command.length
67
73
  ||item.command.some(arg=>typeof arg!=='string'||!arg.trim()||arg.includes('\0')))
@@ -69,6 +75,10 @@ function checkCommandShape(commands,key,plan){
69
75
  try{planCheckTimeout(plan,item);}catch(error){stop(2,error.message);}
70
76
  ids.add(item.id);
71
77
  }
78
+ try{
79
+ for(const [index,item] of commands.entries())if(Object.hasOwn(item,'sameExecutionAs')&&(index===0||planCheckTimeout(plan,item)!==planCheckTimeout(plan,commands[index-1])))throw Error('alias timeout mismatch');
80
+ createHostCheck({cwd:process.cwd(),commands:commands.map(({timeoutMs,...item})=>item),reuseDeclared:executionPolicy!==null});
81
+ }catch(error){stop(2,`PLAN.checks.${key} 格式错误: ${error.code??error.message}`);}
72
82
  }
73
83
  function preflight(){
74
84
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
@@ -79,7 +89,7 @@ function preflight(){
79
89
  +'带 --allow-review 任务:1 但还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
80
90
  process.exit(0);
81
91
  }
82
- const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel'])});
92
+ const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel','reconcile_review'])});
83
93
  const {plan,base,operation}=loaded;
84
94
  requireFields(plan,['config','mode','hostContext','permissions']);
85
95
  try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
@@ -121,9 +131,9 @@ function preflight(){
121
131
  if(bundle.workflows[key]!==null)validateHostWorkflowConfiguration(bundle.workflows[key]);
122
132
  }
123
133
  // Use the batch owner's selection/parallel-group validator without opening a run.
124
- createCmAiBatch({configuration:batch,executionFor:async()=>({}),
134
+ createCmAiBatch({configuration:batch,executionFor:async()=>({}),bootstrapKeys:Object.keys(bundle.bootstraps??{}),
125
135
  logHome:path.join(batch.specsDir,'.reviews','host-log-mirror')});
126
- }catch(error){stop(2,`批次定义、scope 或 workflow 无效: ${error.code??error.message}`);}
136
+ }catch(error){stop(2,`批次定义、scope 或 workflow 无效: ${error.code??error.message}${error.code==='protected_scope'&&typeof error.reason==='string'?`;${error.reason}`:''}`);}
127
137
  const log=path.join(batch.specsDir,'运行日志.jsonl');
128
138
  const stores=Array.from(definitions.values(),d=>path.join(batch.specsDir,'.reviews','.execution',d.identity.runId,'state.json'));
129
139
  const hasLog=fs.existsSync(log),hasStore=stores.some(file=>fs.existsSync(file));
@@ -132,17 +142,26 @@ function preflight(){
132
142
  if(plan.mode==='create'&&operation==='advance'&&(hasLog||hasStore))
133
143
  stop(2,`批次已有存档,请用 resume: ${log}`);
134
144
  if(operation==='status'&&!hasStore)stop(2,`只读 status 需要已有任务存档: ${stores.join(', ')}`);
145
+ const argumentValue=name=>permissions.includes(name)?permissions[permissions.indexOf(name)+1]:undefined;
146
+ if(argumentValue('--external-models-config'))permissions[permissions.indexOf('--external-models-config')+1]=path.resolve(base,argumentValue('--external-models-config'));
147
+ const chosenRuntime=argumentValue('--runtime')??'codex';
148
+ const routes=permissions.includes('--protected-config')?resolveProtectedRuntimes(loadConfig({projectRoot:batch.codeProject}),chosenRuntime):{reviewerRuntime:chosenRuntime};
149
+ let executionPolicy;
150
+ try{executionPolicy=readBatchExecutionPolicy({batch,started:hasStore,enabled:permissions.includes('--execution-optimizations')});}catch(error){stop(2,error.code??'execution_policy_invalid');}
151
+ let externalModels;
152
+ try{externalModels=readBatchExternalModels({batch,started:hasStore,enabled:permissions.includes('--external-models'),inputFile:argumentValue('--external-models-config'),providers:[routes.coderRuntime,routes.reviewerRuntime].filter(Boolean)});}catch(error){stop(2,error.code??'external_model_configuration_invalid');}
153
+ if(operation==='reconcile_review'&&(plan.mode!=='resume'||!keys.includes(plan.taskKey)||!nonempty(plan.invocationId)))stop(2,'reconcile_review requires resume, taskKey and original invocationId');
135
154
  for(let i=0;i<permissions.length;i++)if(PAIRS.has(permissions[i])){
136
155
  const name=permissions[i],value=permissions[++i];
137
156
  if(['--review-config','--protected-conversation-config','--protected-config'].includes(name)){
138
157
  const file=path.resolve(base,value),data=readJson(file,name);
139
158
  if(data===undefined)stop(2,`${name} 文件不存在: ${file}`);
140
159
  try{
141
- if(name==='--review-config')readConversationReviewConfiguration(file);
160
+ if(name==='--review-config')readConversationReviewConfiguration(file,externalModels?.providers[routes.reviewerRuntime]??null);
142
161
  else if(name==='--protected-conversation-config')readConversationProtection(file);
143
162
  else {
144
- if(!isObject(data)||Object.keys(data).sort().join()!=='checkCommands,model,timeoutMs'
145
- ||!nonempty(data.model)||!/^[A-Za-z0-9._-]+$/.test(data.model)
163
+ if(!isObject(data)||Object.keys(data).some(key=>!['checkCommands','model','effort','timeoutMs'].includes(key))
164
+ ||!externalModels&&(!nonempty(data.model)||!/^[A-Za-z0-9._-]+$/.test(data.model))
146
165
  ||!Number.isSafeInteger(data.timeoutMs)||data.timeoutMs<=0||data.timeoutMs>3600000)
147
166
  throw Error('invalid_protected_config');
148
167
  createHostCheck({cwd:batch.codeProject,commands:data.checkCommands,timeoutMs:data.timeoutMs});
@@ -169,7 +188,11 @@ function preflight(){
169
188
  const protectedMode=permissions.includes('--protected-config')||permissions.includes('--protected-conversation-config');
170
189
  const providerAll=permissions.includes('--protected-config')&&keys.every(key=>
171
190
  permissions.includes(`${key}:1`)&&permissions[permissions.indexOf(`${key}:1`)-1]==='--allow-provider-development');
172
- if(operation==='advance'&&permissions.includes('--verification-precheck'))
191
+ let live;
192
+ try{live=driverLiveEvidence(plan,{base,protectedRoots:[batch.codeProject,batch.specsDir,path.resolve(batch.codeProject,'..','.cm-worktrees'),...(batch.codeProjects??[])],
193
+ allowedKinds:['qa_logic','qa_browser','verification_precheck'],maxBytes:inputLimitFrom(permissions)});}
194
+ catch(error){stop(2,error.message);}
195
+ if(operation==='advance'&&permissions.includes('--verification-precheck')&&!live.has('verification_precheck'))
173
196
  stop(2,'缺少真实执行 runner: verification_precheck;不能从静态答案文件应答');
174
197
  if(operation==='advance'&&bundle.bootstraps&&Object.keys(bundle.bootstraps).length)
175
198
  stop(2,'缺少真实执行 runner: init_verify;不能从静态答案文件应答');
@@ -191,9 +214,9 @@ function preflight(){
191
214
  for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
192
215
  }
193
216
  if(workflow)kinds.push('documentation_inspect');
194
- const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind));
217
+ const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind)&&!live.has(kind));
195
218
  if(evidence.length)stop(2,`缺少真实执行 runner: ${evidence.join(', ')};不能从静态答案文件应答`);
196
- if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key,plan);
219
+ if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key,plan,executionPolicy);
197
220
  const taskRoot=root&&path.join(root,task.feature,task.taskId);
198
221
  const perAttempt=new Map();
199
222
  if(kinds.includes('develop')){
@@ -255,7 +278,7 @@ function preflight(){
255
278
  if(answers[key].documentation_sync)for(const target of Object.keys(answers[key].documentation_sync.edits))
256
279
  if(!workflow.documentationPaths.includes(target))stop(2,`任务 ${key} documentation-sync.json.edits 越过文档 scope: ${target}`);
257
280
  }
258
- return {...loaded,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds};
281
+ return {...loaded,executionPolicy,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds,live};
259
282
  }
260
283
 
261
284
  let loaded;
@@ -271,7 +294,8 @@ function safeWrite(map,root,cwd,allowed){
271
294
  fs.writeFileSync(file,fs.readFileSync(path.join(root,local)));
272
295
  }
273
296
  }
274
- async function answerFor(row){
297
+ async function answerFor(row,answers,paths,control){
298
+ if(loaded.live.has(row.kind))return loaded.live.answer(row,control);
275
299
  const identity=row.payload.identity??row.payload.request?.identity;
276
300
  const binding=loaded.runs.get(identity?.runId),key=binding?.key;
277
301
  if(!Object.hasOwn(loaded.answers,key))return null;
@@ -282,13 +306,18 @@ async function answerFor(row){
282
306
  if(row.kind==='check'){
283
307
  if(row.payload.codeProject!==cwd)return null;
284
308
  const results=[];
309
+ const groups=[];
285
310
  for(const command of loaded.plan.checks[key]){
286
- const run=createHostCheck({cwd,commands:[{id:command.id,command:command.command}],
287
- timeoutMs:planCheckTimeout(loaded.plan,command),onOutput:({stream,chunk})=>{
288
- process.stderr.write(`[drive check ${key} ${command.id} ${stream}] ${chunk.toString('utf8')}`);
289
- }});
290
- const [result]=await run({identity},{signal:new AbortController().signal});
291
- results.push(result);if(result.outcome!=='passed')break;
311
+ const timeoutMs=planCheckTimeout(loaded.plan,command);
312
+ if(groups.at(-1)?.timeoutMs!==timeoutMs)groups.push({timeoutMs,commands:[]});
313
+ const {timeoutMs:ignored,...item}=command;groups.at(-1).commands.push(item);
314
+ }
315
+ for(const group of groups){
316
+ let currentId=group.commands[0].id;
317
+ const run=createHostCheck({cwd,commands:group.commands,reuseDeclared:loaded.executionPolicy!==null,
318
+ timeoutMs:group.timeoutMs,onProgress:event=>{if(event.phase==='start')currentId=event.id;reportHostCheckProgress(event);},
319
+ onOutput:({stream,chunk})=>process.stderr.write(`[drive check ${key} ${currentId} ${stream}] ${chunk.toString('utf8')}`)});
320
+ const rows=await run({identity},control);results.push(...rows);if(rows.some(row=>row.outcome!=='passed'))break;
292
321
  }
293
322
  return results;
294
323
  }
@@ -317,7 +346,7 @@ function main(){
317
346
  loaded=preflight();
318
347
  const {plan,operation,bundle,config,permissions}=loaded;
319
348
  driveHost({host:HOST,args:['serve','--config',config,'--host-context',plan.hostContext,
320
- '--allow-development',...permissions,...loaded.holds.flatMap(key=>['--hold-revision',key])],cwd:bundle.batch.codeProject,operation,
349
+ '--allow-development',...permissions,...loaded.holds.flatMap(key=>['--hold-revision',key])],cwd:bundle.batch.codeProject,operation,request:operation==='reconcile_review'?{taskKey:plan.taskKey,invocationId:plan.invocationId}:{},
321
350
  answers:loaded.answers,answerFor});
322
351
  }
323
352
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main();
@@ -8,6 +8,7 @@ import {fileURLToPath} from 'node:url';
8
8
  import {buildManifest} from './cm-spec-manifest.mjs';
9
9
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
10
  import {batchDevelopAttempts} from './cm-ai-batch-drive.mjs';
11
+ import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
11
12
 
12
13
  const DRIVER=fileURLToPath(new URL('./cm-ai-batch-drive.mjs',import.meta.url));
13
14
  const reviewer=fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url));
@@ -66,6 +67,36 @@ function prepared(f){
66
67
  f.write('documentation-inspect.json',{status:'completed',reason:'README and task artifacts inspected'});
67
68
  }
68
69
  function noStore(f){assert.equal(fs.existsSync(f.store),false);assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);}
70
+ test('batch reaches live logic and browser QA through the real member host',async t=>{
71
+ const f=fixture(t);prepared(f);
72
+ const cases=['logic','browser'].map((kind,index)=>({id:`TC-00${index+1}`,origin:'user',kind,blocking:true,
73
+ acIds:[],taskIds:['T-001'],title:'Fixture observation',preconditions:[],steps:['Observe fixture'],expected:['value is 42'],cleanup:[]}));
74
+ fs.writeFileSync(path.join(f.specsDir,'1.work/test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases}));
75
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
76
+ const plan=f.plan({permissions:['--allow-qa','--allow-review',`${key}:1`,'--browser-qa','available'],
77
+ liveEvidence:{directory:'exchange',kinds:['qa_logic','qa_browser'],timeoutMs:1000}});
78
+ const out=await runLiveDriver(DRIVER,plan,'advance',row=>row.kind==='qa_logic'
79
+ ?{verdict:'SUPPORTED',evidence:['Fixture target.mjs exports 42']}
80
+ :{verdict:'BLOCKED',evidence:[],environment:row.payload.environment,cleanup:'not_needed'},
81
+ {timeoutMs:60000,env:{...process.env,PATH:path.join(f.root,'bin')+path.delimiter+process.env.PATH,
82
+ CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
83
+ assert.equal(out.status,0,out.stderr);assert.deepEqual(out.requests.map(r=>r.kind),['qa_logic','qa_browser']);
84
+ assert.equal(JSON.parse(out.stdout).result.code,'qa_result_blocked');
85
+ });
86
+ test('batch live verification request can reject a written requirement without review',async t=>{
87
+ const f=fixture(t);prepared(f);
88
+ fs.writeFileSync(path.join(f.specsDir,'1.work/tasks.md'),'- [ ] T-001: implement target\n - 验证: value is 43\n');
89
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
90
+ const plan=f.plan({permissions:['--allow-qa','--verification-precheck'],
91
+ liveEvidence:{directory:'exchange',kinds:['verification_precheck'],timeoutMs:1000}});
92
+ const out=await runLiveDriver(DRIVER,plan,'advance',row=>{
93
+ assert.equal(row.kind,'verification_precheck');
94
+ assert.match(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),/42/);
95
+ return {items:[{requirement:'value is 43',satisfied:false,evidence:'Fixture source exports 42'}]};
96
+ },{timeoutMs:60000,env:{...process.env,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
97
+ assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
98
+ assert.match(out.stdout,/verification_precheck_failed/);
99
+ });
69
100
 
70
101
  test('help names plan invocation',()=>{
71
102
  const run=spawnSync(process.execPath,[DRIVER,'--help'],{encoding:'utf8'});
@@ -100,12 +131,14 @@ test('real batch reaches completion with an independently dispatched fixture rev
100
131
  const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
101
132
  const first=f.drive(f.plan({permissions}),'advance');
102
133
  assert.equal(first.status,0,first.stderr);assert.match(first.stderr,/应答 check/);
103
- let result=JSON.parse(first.stdout).result;
134
+ let result=JSON.parse(first.stdout).result,stderr=first.stderr;
104
135
  for(let n=0;n<4&&result.state!=='run_done';n++){
105
136
  const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
106
- assert.equal(next.status,0,next.stderr);result=JSON.parse(next.stdout).result;
137
+ assert.equal(next.status,0,next.stderr);result=JSON.parse(next.stdout).result;stderr+=next.stderr;
107
138
  }
108
139
  assert.equal(result.state,'run_done',JSON.stringify(result));
140
+ assert.match(stderr,/开始检查.*value/,'quiet QA command start reaches the batch caller');
141
+ assert.match(stderr,/检查结束.*value.*passed/,'quiet QA command result reaches the batch caller');
109
142
  });
110
143
  // Deliberately replaced (#30). The batch driver has no separate decision step, so
111
144
  // demanding develop-a2.json before any findings existed made a first review with
@@ -259,6 +292,8 @@ test('D1 batch retries failed checks before review in the same attempt',t=>{
259
292
  const first=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude'],checks:failed}),'advance');assert.equal(first.status,0,first.stderr);
260
293
  const result=JSON.parse(first.stdout).result;
261
294
  assert.equal(result.code,'develop_checks_not_passed');assert.equal(result.pendingAction,'resume');
295
+ assert.equal(result.guidance.recoveryOperation,'advance');assert.equal(result.guidance.authorizationGranted,false);
296
+ assert.match(first.stderr,/原批次入口/);assert.doesNotMatch(result.guidance.prerequisites.join(' '),/--mode/);
262
297
  const clean={[key]:[{id:'test',command:[process.execPath,'-e','0']}]};
263
298
  const second=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions:['--allow-qa','--runtime','claude'],checks:clean}),'advance');
264
299
  assert.equal(second.status,0,second.stderr);assert.match(second.stderr,/应答 develop/);
@@ -318,3 +353,13 @@ test('resume binding is required before launch',t=>{
318
353
  const run=f.drive(f.plan({mode:'resume'}),'advance');assert.equal(run.status,2);
319
354
  assert.match(run.stderr,/originalHostContext/);noStore(f);
320
355
  });
356
+
357
+ test('optimized real batch driver shares only a declared same-plan check and rejects legacy aliases before launch',t=>{
358
+ const f=fixture(t);prepared(f);const counter=path.join(f.root,'physical-check-count');
359
+ const command=[process.execPath,'-e',`require('node:fs').appendFileSync(${JSON.stringify(counter)},'x')`];
360
+ const checks={[key]:[{id:'first',command},{id:'same',command,sameExecutionAs:'first'}]};
361
+ const denied=f.drive(f.plan({checks}), 'advance');assert.equal(denied.status,2);noStore(f);assert(!fs.existsSync(counter));
362
+ const out=f.drive(f.plan({permissions:['--allow-qa','--execution-optimizations'],checks}), 'advance');
363
+ assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'awaiting_review',out.stdout+out.stderr);
364
+ assert.equal(fs.readFileSync(counter,'utf8'),'x');
365
+ });
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import {readBatchExecutionPolicy,freezeBatchExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
3
+ import {readBatchExternalModels,freezeBatchExternalModels,batchModelsFile} from '../runtime/js/cm-ai/external-group-models.mjs';
2
4
  // Current-conversation transport for the existing batch driver, not a new loop.
3
5
  import fs from 'node:fs';
4
6
  import path from 'node:path';
5
7
  import {fileURLToPath} from 'node:url';
6
8
  import {createCmAiBatch,batchTaskRunId} from './cm-ai-batch-run.mjs';
9
+ import {assertCreatableScope} from './cm-ai-run.mjs';
7
10
  import {createConversationExecution,readConversationReviewConfiguration,readConversationProtection,runReviewPreflight} from './cm-ai-host.mjs';
8
11
  import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
9
12
  import {preflightMatches} from '../runtime/js/cm-ai/worker-codex.mjs';
@@ -14,20 +17,20 @@ import {validateHostWorkflowConfiguration,featureHasBrowserCases,readBrowserCapa
14
17
  import {digest,json,need,shape} from '../runtime/js/cm-ai/effect-contract.mjs';
15
18
  import {identifyApprovedBootstrapFeature} from '../runtime/js/cm-ai/bootstrap-feature.mjs';
16
19
 
17
- const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development --review-config PATH (required for a new batch; later launches pass the same file) [--runtime codex|claude] [--input-limit BYTES] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--rerun-unknown-qa | --rerun-blocked-qa] [--verification-precheck] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]... [--hold-revision FEATURE/TASK]...';
20
+ const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development --review-config PATH (required for a new batch; later launches pass the same file) [--execution-optimizations] [--external-models [--external-models-config PATH]] [--runtime codex|claude] [--input-limit BYTES] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--rerun-unknown-qa | --rerun-blocked-qa] [--verification-precheck] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]... [--hold-revision FEATURE/TASK]...';
18
21
  const safeCode=error=>typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'batch_host_failed';
19
22
 
20
23
  export async function serveHostTransport(options,rawInputLimit,serve=serveCmAiHost){
21
24
  return serve({...options,inputLimit:parseHostInputLimit(rawInputLimit)});
22
25
  }
23
26
 
24
- async function memberReviewConfiguration(batch,definition,review,runtime){
27
+ async function memberReviewConfiguration(batch,definition,review,runtime,pair=null,allowPreflight=true){
25
28
  try{
26
29
  need(review!==null,'review_configuration_required');
27
- const options={cwd:definition.codeProject,model:review.model,disabledSkills:review.disabledSkills,promptTransport:'stdin'};
30
+ const options={cwd:definition.codeProject,model:review.model,...(pair?{effort:pair.effort}:{}),disabledSkills:review.disabledSkills,promptTransport:'stdin'};
28
31
  const matches=config=>config.model===review.model&&digest(config.disabledSkills)===digest(review.disabledSkills)
29
32
  &&(runtime==='claude'?claudePreflightMatches:preflightMatches)(config.preflight,options);
30
- const directory=path.join(batch.specsDir,'.reviews','.execution',batch.batchId);
33
+ const directory=path.join(batch.specsDir,'.reviews',...(pair?['external-preflight']:['.execution']),batch.batchId);
31
34
  fs.mkdirSync(directory,{recursive:true,mode:0o700});
32
35
  need(fs.realpathSync(directory)===directory,'invalid_preflight_cache');
33
36
  const file=path.join(directory,`preflight-${definition.identity.taskId}.json`);
@@ -36,10 +39,11 @@ async function memberReviewConfiguration(batch,definition,review,runtime){
36
39
  const withTimeout=config=>review.timeoutMs==null?config:{...config,timeoutMs:review.timeoutMs};
37
40
  if(fs.existsSync(file)){
38
41
  const info=fs.lstatSync(file);need(info.isFile()&&!info.isSymbolicLink(),'invalid_preflight_cache');
39
- try{const cached=readConversationReviewConfiguration(file);if(matches(cached))return withTimeout(cached);}
42
+ try{const cached=readConversationReviewConfiguration(file,pair);if(matches(cached))return withTimeout(cached);}
40
43
  catch{/* Invalid or obsolete diagnostics require a fresh loopback, never a rewritten fingerprint. */}
41
44
  }
42
- const config=await runReviewPreflight(definition,{model:review.model,runtime,disabledSkills:review.disabledSkills});
45
+ need(allowPreflight,'review_preflight_missing');
46
+ const config=await runReviewPreflight(definition,{model:review.model,...(pair?{effort:pair.effort}:{}),runtime,disabledSkills:review.disabledSkills});
43
47
  need(matches(config),'review_preflight_failed');
44
48
  const temporary=`${file}.${process.pid}.tmp`;
45
49
  fs.writeFileSync(temporary,JSON.stringify(config)+'\n',{flag:'wx',mode:0o600});
@@ -49,6 +53,7 @@ async function memberReviewConfiguration(batch,definition,review,runtime){
49
53
  }
50
54
 
51
55
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
56
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional --execution-optimizations freezes policy v1 for new runs only; recovery retains the original policy and legacy runs reject retrofit. See docs/execution-optimizations.md.\n');
52
57
  if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --input-limit BYTES sets the host input transport limit to an integer from 65536 to 4194304 (default 65536); it may change on resume.\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional --protected-config PATH {model,checkCommands,timeoutMs} enables CLI development only for per-task --allow-provider-development FEATURE/TASK:1|2 grants; mutually exclusive with --protected-conversation-config. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\n--review-config PATH is required when no member run of the batch exists yet (like single-task create): it is bound into every member fingerprint and cannot be added on resume. It is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000). It is independent of --protected-conversation-config/--protected-config and wins over their timeoutMs for the reviewer. It is not part of the authorized configuration digest, so a resumed run may raise it after review_transport_timeout.\n--browser-qa available|unavailable declares interactive QA capability for applicable feature carriers including browser and ios-simulator; the flag name is retained for compatibility.\nOptional --rerun-unknown-qa / --rerun-blocked-qa carry the same single-task QA recovery into a batch and require --allow-qa; they are mutually exclusive. A batch has no --mode, so each task applies the flag only when it resumes an existing run and has a QA executor; a created run or a task without QA ignores it rather than failing the whole batch. Semantics, limits and the qaRound cap are the single-task ones, unchanged.\nOptional --verification-precheck sends the written verification of the task and the collected checks back as a verification_precheck request before any handoff or review package is built. It may only block: a requirement reported unsatisfied stops the task at blocked / verification_precheck_failed with pendingAction resume and spends no review round. Passing it is not an approval, writes no receipt and does not replace the independent review. A task with no written verification is unaffected.\nOptional --hold-revision FEATURE/TASK (repeatable, launch-only, never persisted) stops that task after a changes_requested review with code revision_answer_required, before any second-round develop intent; the next launch without it resumes the revision. It only narrows what this launch does.\nBatch entry requires a clean Git main checkout (including untracked files); batch_main_dirty lists dirty files before any task or worktree starts. Serial tasks are committed automatically before batch_handoff, with task_commit recording the SHA (null if unchanged). Terminal parallel members preserve WIP on their retained branches and fall back once to serial generation 2 after ready members merge.\n');return 0;}
53
58
  let bridge;
54
59
  try{
@@ -69,9 +74,11 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
69
74
  for(const key of keys)if(workflows[key]!==null)validateHostWorkflowConfiguration(workflows[key]);
70
75
  let review=null,allowQa=false,allowBootstrap=false,runtime=null,protection=null,providerConfig=null,browserQaFlag,inputLimitRaw;
71
76
  let rerunUnknownQa=false,rerunBlockedQa=false,verificationPrecheck=false;const approvals=new Set(),developments=new Map(),holds=new Set();
77
+ let externalEnabled=false,externalFile,executionPolicyEnabled=false;
72
78
  for(let index=6;index<argv.length;index++){
73
79
  const name=argv[index];
74
- if(name==='--allow-qa'){need(!allowQa,'invalid_arguments');allowQa=true;}
80
+ if(name==='--execution-optimizations'){need(!executionPolicyEnabled,'invalid_arguments');executionPolicyEnabled=true;}
81
+ else if(name==='--allow-qa'){need(!allowQa,'invalid_arguments');allowQa=true;}
75
82
  else if(name==='--rerun-unknown-qa'){need(!rerunUnknownQa,'invalid_arguments');rerunUnknownQa=true;}
76
83
  else if(name==='--rerun-blocked-qa'){need(!rerunBlockedQa,'invalid_arguments');rerunBlockedQa=true;}
77
84
  else if(name==='--verification-precheck'){need(!verificationPrecheck,'invalid_arguments');verificationPrecheck=true;}
@@ -86,7 +93,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
86
93
  need(protection===null&&providerConfig===null&&typeof argv[index+1]==='string','invalid_arguments');
87
94
  const file=argv[++index],info=fs.lstatSync(file);
88
95
  need(info.isFile()&&!info.isSymbolicLink()&&info.size<=64*1024,'invalid_protected_config');
89
- providerConfig=json(JSON.parse(fs.readFileSync(file,'utf8')));shape(providerConfig,['model','checkCommands','timeoutMs']);
96
+ providerConfig=json(JSON.parse(fs.readFileSync(file,'utf8')));shape(providerConfig,['checkCommands','timeoutMs',...['model','effort'].filter(key=>Object.hasOwn(providerConfig,key))]);
90
97
  }
91
98
  else if(name==='--allow-provider-development'){
92
99
  const approval=argv[++index];need(typeof approval==='string','invalid_arguments');
@@ -94,6 +101,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
94
101
  need(keys.includes(key)&&['1','2'].includes(attempt),'invalid_arguments');
95
102
  need(!developments.has(key),'invalid_arguments');developments.set(key,Number(attempt));
96
103
  }
104
+ else if(name==='--external-models'){need(!externalEnabled,'invalid_arguments');externalEnabled=true;}
105
+ else if(name==='--external-models-config'){need(externalFile===undefined&&typeof argv[index+1]==='string','invalid_arguments');externalFile=argv[++index];}
97
106
  else if(name==='--runtime'){
98
107
  need(runtime===null&&['codex','claude'].includes(argv[index+1]),'invalid_runtime');runtime=argv[++index];
99
108
  }
@@ -101,7 +110,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
101
110
  need(inputLimitRaw===undefined&&typeof argv[index+1]==='string','invalid_arguments');
102
111
  inputLimitRaw=argv[++index];parseHostInputLimit(inputLimitRaw);
103
112
  }
104
- else if(name==='--review-config'){need(review===null&&typeof argv[index+1]==='string','invalid_arguments');review=readConversationReviewConfiguration(argv[++index]);}
113
+ else if(name==='--review-config'){need(review===null&&typeof argv[index+1]==='string','invalid_arguments');review=argv[++index];}
105
114
  else if(name==='--hold-revision'){
106
115
  const held=argv[++index];need(typeof held==='string'&&keys.includes(held)&&!holds.has(held),'invalid_arguments');holds.add(held);
107
116
  }
@@ -111,6 +120,22 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
111
120
  need(keys.includes(key)&&['1','2'].includes(attempt),'review_task_mismatch');approvals.add(approval);
112
121
  }else need(false,'invalid_arguments');
113
122
  }
123
+ const started=keys.some(key=>fs.existsSync(path.join(batch.specsDir,'.reviews','.execution',batchTaskRunId(batch.batchId,key),'state.json')));
124
+ // Same read-only create gate as the batch owner, before any model or policy configuration is read or frozen.
125
+ for(const [index,task] of batch.tasks.entries())
126
+ if(!Object.hasOwn(bootstraps??{},keys[index])&&!fs.existsSync(path.join(batch.specsDir,'.reviews','.execution',batchTaskRunId(batch.batchId,keys[index]),'state.json')))
127
+ try{assertCreatableScope(task.scope);}catch(cause){cause.reason=`${keys[index]}: ${cause.reason}`;throw cause;}
128
+ const executionPolicy=readBatchExecutionPolicy({batch,started,enabled:executionPolicyEnabled});
129
+ const routes=providerConfig?resolveProtectedRuntimes(loadConfig({projectRoot:batch.codeProject}),runtime??'codex'):{reviewerRuntime:runtime??'codex'};
130
+ const externalModels=readBatchExternalModels({batch,started,enabled:externalEnabled,inputFile:externalFile,providers:[routes.coderRuntime,routes.reviewerRuntime].filter(Boolean)});
131
+ if(providerConfig&&!externalModels)shape(providerConfig,['model','checkCommands','timeoutMs']);
132
+ if(providerConfig&&externalModels){
133
+ const pair=externalModels.providers[routes.coderRuntime];
134
+ need(!Object.hasOwn(providerConfig,'model')||providerConfig.model===pair.model,'external_model_configuration_conflict');
135
+ need(!Object.hasOwn(providerConfig,'effort')||providerConfig.effort===pair.effort,'external_model_configuration_conflict');
136
+ providerConfig={...providerConfig,...pair};
137
+ }
138
+ review=review===null?null:readConversationReviewConfiguration(review,externalModels?.providers[routes.reviewerRuntime]??null);
114
139
  need(!developments.size||providerConfig!==null,'protected_configuration_required');
115
140
  // Same launch-time assertion as the single-task host, evaluated across every
116
141
  // task whose approved contract can select a browser case.
@@ -141,20 +166,23 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
141
166
  const pending=hostCallTail.then(()=>bridge.call(...args));
142
167
  hostCallTail=pending.then(()=>{},()=>{});return pending;
143
168
  }};
144
- const driver=createCmAiBatch({configuration:batch,logHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
169
+ let reconciling=false;
170
+ const driver=createCmAiBatch({configuration:{...batch,...(externalModels?{externalModels}:{}),...(executionPolicy?{executionPolicy}:{})},logHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
145
171
  runtime:runtime??'codex',checkCommands:(providerConfig??protection)?.checkCommands??null,checkTimeoutMs:(providerConfig??protection)?.timeoutMs??60000,
146
- rerunUnknownQa,rerunBlockedQa,holdRevisions:[...holds],
172
+ rerunUnknownQa,rerunBlockedQa,holdRevisions:[...holds],bootstrapKeys:Object.keys(bootstraps??{}),
147
173
  executionFor:async(definition,{parallelMember=false}={})=>{
174
+ await freezeBatchExecutionPolicy(batch,executionPolicy);
175
+ freezeBatchExternalModels(batch,externalModels);
148
176
  const key=`${definition.feature}/${definition.identity.taskId}`;
149
177
  const attempts=[1,2].filter(attempt=>approvals.has(`${key}:${attempt}`));
150
- const memberReview=parallelMember?await memberReviewConfiguration(batch,definition,review,runtime??'codex'):review;
178
+ const memberReview=parallelMember?await memberReviewConfiguration(batch,definition,review,externalModels?routes.reviewerRuntime:runtime??'codex',externalModels?.providers[routes.reviewerRuntime]??null,!reconciling):review;
151
179
  const execution=createConversationExecution(definition,argv[4],parallelMember?memberBridge:bridge,memberReview,attempts,workflows[key],allowQa,runtime??'codex',
152
- {parallelMember,...(verificationPrecheck?{verificationPrecheck:true}:{}),batchWorkflowsDigest:digest(bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
180
+ {parallelMember,...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels,...(providerConfig?{reviewerRuntime:routes.reviewerRuntime}:{})}:{}),...(verificationPrecheck?{verificationPrecheck:true}:{}),batchWorkflowsDigest:digest(executionPolicy?{workflows,bootstraps,externalModels,executionPolicy}:externalModels?{workflows,bootstraps,externalModels}:bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
153
181
  // A protected CLI config also protects unauthorized tasks: they stay on the
154
182
  // current-session transport but with the same sandbox checks (protected-text edits).
155
183
  ...(protection?{protection}:providerConfig?{protection:{checkCommands:providerConfig.checkCommands,timeoutMs:providerConfig.timeoutMs}}:{}),
156
184
  ...(developments.has(key)?{
157
- providerDevelopment:{model:providerConfig.model,attempt:developments.get(key),
185
+ providerDevelopment:{...(providerConfig.model?{model:providerConfig.model}:{}),...(Object.hasOwn(providerConfig,'effort')?{effort:providerConfig.effort}:{}),attempt:developments.get(key),
158
186
  ...resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime??'codex')},
159
187
  }:{}),...(bootstraps?.[key]?{bootstrap:{...bootstraps[key],allowWrite:allowBootstrap}}:{})});
160
188
  // Bind the entire approved capability map before the first task starts,
@@ -162,13 +190,13 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
162
190
  return execution;
163
191
  }});
164
192
  const host={async handle(request){
165
- try{return await driver.handle(request);}catch(cause){return {outcome:'blocked',code:safeCode(cause)};}
193
+ try{reconciling=request.operation==='reconcile_review';return await driver.handle(request);}catch(cause){return {outcome:'blocked',code:safeCode(cause)};}
166
194
  }};
167
195
  const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
168
196
  try{await serveHostTransport({host,input,output,toolBridge:bridge},inputLimitRaw);}
169
197
  finally{if(rawMode)input.setRawMode(false);}
170
198
  return 0;
171
- }catch(cause){const code=safeCode(cause);error.write(JSON.stringify({error:{code,...(['browser_capability_required','browser_capability_unavailable','invalid_arguments','review_configuration_required'].includes(code)
199
+ }catch(cause){const code=safeCode(cause);error.write(JSON.stringify({error:{code,...(['browser_capability_required','browser_capability_unavailable','invalid_arguments','review_configuration_required','protected_scope'].includes(code)
172
200
  &&typeof cause.reason==='string'?{reason:cause.reason}:{}),...(code==='request_too_large'?{reason:inputLimitReason(cause.limit)}:{})}})+'\n');return 1;}
173
201
  finally{bridge?.close();}
174
202
  }