@aibyzero/cm-workflow 0.16.6 → 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 (51) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +12 -1
  3. package/README.md +7 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +48 -6
  7. package/package.json +1 -1
  8. package/runtime/js/cm-ai/cm-ai-admission.mjs +34 -10
  9. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  10. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +32 -14
  11. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +92 -27
  12. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  13. package/runtime/js/cm-ai/drive-bootstrap.mjs +2 -2
  14. package/runtime/js/cm-ai/durable-runner-state.mjs +29 -0
  15. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -3
  16. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  17. package/runtime/js/cm-ai/host-qa-executor.mjs +52 -6
  18. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  19. package/runtime/js/cm-ai/operator-guidance.mjs +3 -0
  20. package/runtime/js/cm-ai/task-runner.mjs +6 -1
  21. package/runtime/js/cm-fix/finish.mjs +2 -19
  22. package/runtime/js/cm-fix/log-events.mjs +29 -0
  23. package/runtime/js/cm-fix/metrics.mjs +3 -2
  24. package/runtime/js/cm-prd/analysis.mjs +5 -2
  25. package/runtime/js/cm-prd/review-host.mjs +2 -1
  26. package/runtime/js/cm-test/recovery.mjs +4 -4
  27. package/scripts/cm-ai-admission.mjs +14 -3
  28. package/scripts/cm-ai-batch-drive.mjs +2 -2
  29. package/scripts/cm-ai-batch-host.mjs +7 -2
  30. package/scripts/cm-ai-batch-run.mjs +6 -2
  31. package/scripts/cm-ai-drive.mjs +14 -3
  32. package/scripts/cm-ai-drive.test.mjs +22 -0
  33. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  34. package/scripts/cm-ai-host.mjs +18 -6
  35. package/scripts/cm-ai-host.test.mjs +88 -0
  36. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  37. package/scripts/cm-ai-run.mjs +36 -5
  38. package/scripts/cm-fix-large-log.test.mjs +113 -0
  39. package/scripts/cm-host-qa-executor.test.mjs +308 -3
  40. package/scripts/cm-log-event.mjs +26 -5
  41. package/scripts/cm-prd-host.mjs +13 -2
  42. package/scripts/cm-prd-host.test.mjs +4 -0
  43. package/scripts/cm-prd-review-host.test.mjs +17 -0
  44. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  45. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  46. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  47. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  48. package/skills/cm-ai/references/N1-init.md +1 -1
  49. package/skills/cm-ai/references/js-host.md +3 -2
  50. package/skills/cm-prd/SKILL.md +5 -4
  51. package/skills/cm-prd/references/spec-self-check.md +3 -1
@@ -16,6 +16,8 @@ import {inspectPrdDesignRiskSelection} from './design-risk.mjs';
16
16
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
17
17
  import {prdDraftJson} from './validation-reason.mjs';
18
18
 
19
+ const initialTaskInstructions=' For FIRST task planning only: combine related low-risk work around one independently verifiable and reversible objective. Retain every AC, original user test, expected result and verification prerequisite; keep AC-to-test-to-task references complete. Same file/component alone is not evidence to combine. Keep high-risk work, unknown-risk work, explicit user requests for independent tasks and unrelated objectives separate; preserve legitimate contract-first tasks and real dependencies. Use requirement/design/context evidence, not keyword risk classification or another model call. No fixed merge ratio or task-count target. Do not repartition an existing draft, revision, restored task list, change or in-flight task. Scope expansion during development requires the existing explicit change and renewed approval. Keep configured developer/reviewer roles and each task independent N4 unchanged.';
20
+
19
21
  export function createCmPrdAnalysis({input,runtime,analyze,record,processMaterials,generate,checkContext,restored=null,allowInputDrift=false}){
20
22
  need(['codex','claude'].includes(runtime)&&typeof analyze==='function'&&typeof record==='function','prd_host_invalid');
21
23
  input=json(input);
@@ -192,11 +194,12 @@ export function createCmPrdAnalysis({input,runtime,analyze,record,processMateria
192
194
  revision:draft===null?null:{draft,contextCheck,round:selfCheckRound+1,
193
195
  instructions:'Correct findings only within these existing feature names/directories. Do not add, remove or rename features; retain user intent and tests. No review invocation. Two self-check rounds maximum.'},
194
196
  reference:path.join(admission.skillDir,'SKILL.md'),testContract:path.join(admission.workflowRoot,'runtime/test-contract.md'),
195
- instructions:canRevise?
197
+ instructions:(canRevise?
196
198
  'Correct the failed whole-draft self-check in the existing draft schema. Keep exactly the same ordered features and file inventory. Requirements/design changes require selfCheckRevisionReason. Return question or blocked if needed. No writes, review dispatch, invented approval or extra rounds.':acceptedDesign!==null?
197
199
  'Follow original cm-prd Step 10 and 10.4 on acceptedDesign. Return the existing draft schema with the exact same ordered features and exact requirements.md/design.md bytes supplied there; generate tasks.md and applicable test-cases.json only. Do not regenerate or revise accepted requirements/design, change scope or call a reviewer. Preserve original user cases and unresolved design findings for human review. Ask material questions with {status:question,question}; no invented user decisions. No writes, provider calls, installation, development or approval. Subsequent original self-check and split review remain required.':designOnly?
198
200
  'Follow cm-prd Steps 6-9 only, before original Step 9.5 design review. Read required references and actual relevant project context. Preserve user cases and requirements. No tasks or test-contract generation yet, even embedded in another document. Resolve material or human UI baseline decisions with {status:question,question}; never infer consent. Return {status:design,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md,content:string}]}]} with exactly both documents per feature, or {status:blocked,reason}. No writes, provider calls, browser launch, installation, review claims or development. These are unreviewed memory drafts, not authority to generate tasks.':
199
- 'Follow cm-prd Steps 6-10 for in-memory DRAFTS ONLY. Read required references and relevant project context. Resolve material questions and human UI baseline choices before design: return {status:question,question} and wait, never infer consent. No writes, provider calls, browser launch, installation, review claims or development. Return {status:draft,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md|tasks.md|test-cases.json,content:string}],testCasesReason:null|no_observable_behavior|generation_disabled}]} or {status:blocked,reason}. Each feature needs the triad. Apply functional task granularity <=15, AC/Task references, applicable test contract and original user-case intent; generateCases false forbids generated cases only. This draft is unreviewed; original conditional design review, split review, self-check and human approval remain pending.'},controller.signal),64*1024);
201
+ 'Follow cm-prd Steps 6-10 for in-memory DRAFTS ONLY. Read required references and relevant project context. Resolve material questions and human UI baseline choices before design: return {status:question,question} and wait, never infer consent. No writes, provider calls, browser launch, installation, review claims or development. Return {status:draft,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md|tasks.md|test-cases.json,content:string}],testCasesReason:null|no_observable_behavior|generation_disabled}]} or {status:blocked,reason}. Each feature needs the triad. Apply functional task granularity <=15, AC/Task references, applicable test contract and original user-case intent; generateCases false forbids generated cases only. This draft is unreviewed; original conditional design review, split review, self-check and human approval remain pending.')
202
+ +(draft===null&&!designOnly?initialTaskInstructions:'')},controller.signal),64*1024);
200
203
  need(!controller.signal.aborted,'cancelled');current();
201
204
  need(digest(inventory)===digest(prdFeatureInventory(admission.specs)),'prd_feature_inventory_changed');
202
205
  if(reply.status==='question'){
@@ -36,7 +36,8 @@ export async function runPrdHostReview({specs,prepared,authorContextId,writeEnab
36
36
  const paths=(pkg.stage==='design'?['requirements.md','design.md']:['requirements.md','design.md','tasks.md'])
37
37
  .map(file=>`${pkg.feature}/${file}`).sort();
38
38
  const response=json(await review({package:{...pkg,packageDigest:prepared.packageDigest},examinedPaths:paths,authorContextId,mode,
39
- instructions:'Use only the authorized current-host review channel. independent requires an actual fresh reviewer context, not the author. self-degraded uses the author and must explain unavailable independence. Verify context identity and forward the original result unchanged. No provider/CLI invocation, installation, external transmission, Git or project writes without separate authority. Return {reviewer,contextId,independent,at,result}, plus degradedReason only for self-degraded. Result follows verdict/packageDigest/examinedPaths/findings/summary. Do not retry or switch mode after this attempt; unavailable/interrupted remains unknown.'},signal),64*1024);
39
+ instructions:'Use only the authorized current-host review channel. independent requires an actual fresh reviewer context, not the author. self-degraded uses the author and must explain unavailable independence. Verify context identity and forward the original result unchanged. No provider/CLI invocation, installation, external transmission, Git or project writes without separate authority. Return {reviewer,contextId,independent,at,result}, plus degradedReason only for self-degraded. Result follows verdict/packageDigest/examinedPaths/findings/summary. Do not retry or switch mode after this attempt; unavailable/interrupted remains unknown.'
40
+ +(pkg.stage==='split'?' In this existing split attempt, assess submitted task boundaries: combined work must share one independently verifiable and reversible objective with every AC, original test and verification prerequisite retained. Check requirement/design/context evidence for high or unknown risk, explicit user independence and unrelated objectives; retain those boundaries and legitimate contract-first dependencies. Do not infer risk from keywords, add a classifier/review call, enforce a merge ratio or repartition already generated tasks for fewer reviews. Do not apply this new grouping guidance retroactively to older drafts, revisions, change plans or in-flight tasks. Report only existing requirement/design failures with concrete consequences; mechanical reference checks alone do not establish semantic risk or user intent. Configured roles and per-task N4 remain unchanged.':'')},signal),64*1024);
40
41
  need(!signal.aborted,'cancelled');current();
41
42
  validatePrdReviewMode(mode,response);
42
43
  const published=publishPrdReview({specs,reviewPackage:pkg,packageDigest:prepared.packageDigest,authorContextId,response});
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {inspectRunClosure} from '../../../scripts/cm-log-event.mjs';
6
6
  import {need,digest,json} from '../cm-ai/effect-contract.mjs';
7
+ import {readStableLogRows} from '../cm-ai/log-rows.mjs';
7
8
  import {inside,canonicalFuture,selectReportDirectory} from './source-snapshot.mjs';
8
9
 
9
10
  export function inspectCmTestRecovery(config,{runId,logFile}){
@@ -23,10 +24,9 @@ export function inspectCmTestRecovery(config,{runId,logFile}){
23
24
  const allowed=admission.specs?logFile===path.join(admission.specs,'运行日志.jsonl'):
24
25
  inside(path.join(logHome,'runs'),logFile)&&logFile.endsWith('.jsonl');
25
26
  need(allowed,'cm_test_log_path_invalid');
26
- const stat=fs.lstatSync(logFile);
27
- need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=32*1024*1024,'cm_test_log_invalid');
28
- const lines=fs.readFileSync(logFile,'utf8').split('\n').filter(Boolean);
29
- const records=lines.map(line=>JSON.parse(line)).filter(event=>event.run_id===runId);
27
+ // Streamed with the same single-link/stable-file checks: a shared project log
28
+ // keeps growing, and only this run's rows matter here (no 32 MiB whole-file cap).
29
+ const records=readStableLogRows(logFile,event=>event?.run_id===runId,'cm_test_log_invalid');
30
30
  const starts=records.filter(event=>event.event==='run_start');
31
31
  need(starts.length===1&&starts[0].workflow==='cm-test'&&starts[0].project_path===admission.project,
32
32
  'cm_test_run_binding_invalid');
@@ -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,
@@ -131,9 +131,9 @@ function preflight(){
131
131
  if(bundle.workflows[key]!==null)validateHostWorkflowConfiguration(bundle.workflows[key]);
132
132
  }
133
133
  // Use the batch owner's selection/parallel-group validator without opening a run.
134
- createCmAiBatch({configuration:batch,executionFor:async()=>({}),
134
+ createCmAiBatch({configuration:batch,executionFor:async()=>({}),bootstrapKeys:Object.keys(bundle.bootstraps??{}),
135
135
  logHome:path.join(batch.specsDir,'.reviews','host-log-mirror')});
136
- }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}`:''}`);}
137
137
  const log=path.join(batch.specsDir,'运行日志.jsonl');
138
138
  const stores=Array.from(definitions.values(),d=>path.join(batch.specsDir,'.reviews','.execution',d.identity.runId,'state.json'));
139
139
  const hasLog=fs.existsSync(log),hasStore=stores.some(file=>fs.existsSync(file));
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {createCmAiBatch,batchTaskRunId} from './cm-ai-batch-run.mjs';
9
+ import {assertCreatableScope} from './cm-ai-run.mjs';
9
10
  import {createConversationExecution,readConversationReviewConfiguration,readConversationProtection,runReviewPreflight} from './cm-ai-host.mjs';
10
11
  import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
11
12
  import {preflightMatches} from '../runtime/js/cm-ai/worker-codex.mjs';
@@ -120,6 +121,10 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
120
121
  }else need(false,'invalid_arguments');
121
122
  }
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;}
123
128
  const executionPolicy=readBatchExecutionPolicy({batch,started,enabled:executionPolicyEnabled});
124
129
  const routes=providerConfig?resolveProtectedRuntimes(loadConfig({projectRoot:batch.codeProject}),runtime??'codex'):{reviewerRuntime:runtime??'codex'};
125
130
  const externalModels=readBatchExternalModels({batch,started,enabled:externalEnabled,inputFile:externalFile,providers:[routes.coderRuntime,routes.reviewerRuntime].filter(Boolean)});
@@ -164,7 +169,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
164
169
  let reconciling=false;
165
170
  const driver=createCmAiBatch({configuration:{...batch,...(externalModels?{externalModels}:{}),...(executionPolicy?{executionPolicy}:{})},logHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
166
171
  runtime:runtime??'codex',checkCommands:(providerConfig??protection)?.checkCommands??null,checkTimeoutMs:(providerConfig??protection)?.timeoutMs??60000,
167
- rerunUnknownQa,rerunBlockedQa,holdRevisions:[...holds],
172
+ rerunUnknownQa,rerunBlockedQa,holdRevisions:[...holds],bootstrapKeys:Object.keys(bootstraps??{}),
168
173
  executionFor:async(definition,{parallelMember=false}={})=>{
169
174
  await freezeBatchExecutionPolicy(batch,executionPolicy);
170
175
  freezeBatchExternalModels(batch,externalModels);
@@ -191,7 +196,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
191
196
  try{await serveHostTransport({host,input,output,toolBridge:bridge},inputLimitRaw);}
192
197
  finally{if(rawMode)input.setRawMode(false);}
193
198
  return 0;
194
- }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)
195
200
  &&typeof cause.reason==='string'?{reason:cause.reason}:{}),...(code==='request_too_large'?{reason:inputLimitReason(cause.limit)}:{})}})+'\n');return 1;}
196
201
  finally{bridge?.close();}
197
202
  }
@@ -7,7 +7,7 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import {spawnSync} from 'node:child_process';
9
9
  import {fileURLToPath} from 'node:url';
10
- import {openControlRun,validateRunDefinition} from './cm-ai-run.mjs';
10
+ import {openControlRun,validateRunDefinition,assertCreatableScope} from './cm-ai-run.mjs';
11
11
  import {developmentRetryable,completionRetryable,reviewRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
12
12
  import {batchOperatorGuidance} from '../runtime/js/cm-ai/operator-guidance.mjs';
13
13
  import {digest,json,shape,need,id,hex} from '../runtime/js/cm-ai/effect-contract.mjs';
@@ -39,7 +39,7 @@ export function batchMemberResult(result,{parallel=false}={}){
39
39
  :`${revert};或取消本批次,还原该任务已改动的代码后,用单任务宿主 cm-ai-host.mjs 以 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务。`}));
40
40
  }
41
41
  export function createCmAiBatch({configuration,executionFor,logHome,runtime='codex',checkCommands=null,checkTimeoutMs=60000,
42
- rerunUnknownQa=false,rerunBlockedQa=false,holdRevisions=[]}){
42
+ rerunUnknownQa=false,rerunBlockedQa=false,holdRevisions=[],bootstrapKeys=[]}){
43
43
  const config=json(configuration);
44
44
  shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...['externalModels','executionPolicy','codeProjects','parallel'].filter(name=>Object.hasOwn(config,name))]);
45
45
  need(config.version===1);id(config.repositoryId);id(config.batchId);need(config.batchId.length>=8);
@@ -70,6 +70,10 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
70
70
  identity:{repositoryId:config.repositoryId,runId:batchTaskRunId(config.batchId,key(task)),
71
71
  taskId:task.taskId,attempt:1},scope:task.scope,requirements:task.requirements});
72
72
  need(definition.specsDir===config.specsDir&&definition.codeProject===config.codeProject,'invalid_path');
73
+ // A member that will be created is refused before the batch locks, logs or
74
+ // prepares a worktree; an existing member keeps its own recovery path.
75
+ if(!bootstrapKeys.includes(key(task))&&!fs.existsSync(path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json')))
76
+ try{assertCreatableScope(definition.scope);}catch(error){error.reason=`${key(task)}: ${error.reason}`;throw error;}
73
77
  plans.set(key(task),definition);
74
78
  }
75
79
  // Tasks whose second-round answer is not written yet stop after a changes_requested review.
@@ -84,7 +84,8 @@ const PAIR_FLAGS=new Set(['--external-models-config','--allow-review-attempt','-
84
84
  '--input-limit',
85
85
  '--protected-conversation-config','--protected-config','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure',
86
86
  '--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--browser-qa',
87
- '--bootstrap-config','--allow-provider-development-attempt','--supersede-reason','--spec-rebind-reason']);
87
+ '--bootstrap-config','--allow-provider-development-attempt','--supersede-reason','--spec-rebind-reason',
88
+ '--review-runtime','--feature']);
88
89
  const FLAG_FLAGS=new Set(['--execution-optimizations','--external-models','--allow-development','--allow-qa','--allow-qa-fix-start','--auto-qa-fix',
89
90
  '--verification-precheck',
90
91
  '--allow-bootstrap-write','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
@@ -252,7 +253,7 @@ export function projectDevelopCheckpoint({preview,codeProject,attempt,value,proj
252
253
  const {definition}=preview,identity={...definition.identity,attempt};
253
254
  if(value.value?.outcome!=='implemented')return null;
254
255
  const learningInput=inspectCmAiTaskLearningInput({specsDir:definition.specsDir,codeProject,feature:definition.feature,
255
- identity,applicableAgentFiles:[]},{admission:null,parallelSelection:preview.parallelSelection});
256
+ identity,applicableAgentFiles:[],...(definition.featureSelection?{featureSelection:definition.featureSelection.feature}:{})},{admission:null,parallelSelection:preview.parallelSelection});
256
257
  const binding={feature:definition.feature,identity,learningDigest:learningInput.learningDigest};
257
258
  const application=createCmAiTaskLearningApplication({...binding,...value.value.application});
258
259
  const retrospective=createCmAiTaskLearningRetrospective({...binding,...value.value.retrospective});
@@ -575,6 +576,15 @@ function load(){
575
576
  if(!fs.existsSync(config))stop(2,`运行定义不存在: ${config}`);
576
577
  let definition;
577
578
  try{definition=readRunDefinition(config);}catch(error){stop(2,`运行定义无效或 codeProject/specsDir 无法解析: ${error.code??error.message}`);}
579
+ // --feature is forwarded to the host, which binds it as featureSelection.
580
+ // Use that same effective definition here (Learning input, bootstrap checks).
581
+ const featureAt=permissions.indexOf('--feature');
582
+ if(featureAt!==-1){
583
+ const selected=permissions[featureAt+1];
584
+ if(selected!==definition.feature||definition.featureSelection&&definition.featureSelection.feature!==selected)
585
+ stop(2,`--feature ${selected} 必须与运行定义的 feature ${definition.feature} 一致`);
586
+ definition={...definition,featureSelection:{version:1,feature:selected}};
587
+ }
578
588
  if(plan.mode==='create')try{assertCreatableRunId(definition.identity);}
579
589
  catch(error){stop(2,`运行定义的 ${error.code.replace(/^invalid_config: /,'')};宿主未启动,请换一个更长的 runId`);}
580
590
  const store=path.join(definition.specsDir,'.reviews','.execution',definition.identity.runId);
@@ -595,7 +605,8 @@ function load(){
595
605
  for(let i=0;i<permissions.length;i++)if(PAIR_FLAGS.has(permissions[i])
596
606
  &&permissions[i]!=='--allow-review-attempt'&&permissions[i]!=='--browser-qa'
597
607
  &&permissions[i]!=='--qa-config-revision-reason'&&permissions[i]!=='--qa-environment-failure'&&permissions[i]!=='--allow-provider-development-attempt'
598
- &&permissions[i]!=='--supersede-reason'&&permissions[i]!=='--spec-rebind-reason'&&permissions[i]!=='--input-limit'){
608
+ &&permissions[i]!=='--supersede-reason'&&permissions[i]!=='--spec-rebind-reason'&&permissions[i]!=='--input-limit'
609
+ &&permissions[i]!=='--review-runtime'&&permissions[i]!=='--feature'){
599
610
  const file=path.resolve(base,permissions[i+1]);if(!fs.existsSync(file))stop(2,`${permissions[i]} 文件不存在: ${file}`);
600
611
  permissions[i+1]=file;permissionFiles.push(file);i++;
601
612
  }
@@ -582,3 +582,25 @@ test('legacy real driver rejects optimization aliases before any host or command
582
582
  const result=f.drive(f.plan({checks:[{id:'one',command},{id:'two',command,sameExecutionAs:'one'}]}),'advance');
583
583
  assert.notEqual(result.status,0);assert(!fs.existsSync(f.store));assert(!fs.existsSync(path.join(f.codeProject,'marker')));
584
584
  });
585
+ // The driver forwards the explicit batch choice and the cross-tool review
586
+ // binding, and previews with the same effective definition as the host.
587
+ test('driver forwards --feature for a later approved feature and --review-runtime for a cross-tool run',t=>{
588
+ const f=fixture(t);
589
+ const early=path.join(f.specsDir,'0.early');fs.mkdirSync(early);
590
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(early,name),'# Early\n');
591
+ fs.writeFileSync(path.join(early,'tasks.md'),'- [ ] T-001: earlier batch\n');
592
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['0.early','1.work'],specFiles:buildManifest(f.specsDir)}));
593
+ fs.writeFileSync(path.join(f.codeProject,'.cm-workflow.yml'),'version: 1\nruntimes: {available: both}\nroles:\n coder: {adapter: codex-cli, source: subscription}\n reviewer: {adapter: claude-cli, source: subscription}\n');
594
+ const bare={answers:undefined,checks:undefined};
595
+ const unselected=f.drive(f.plan({...bare}),'status');
596
+ assert.notEqual(unselected.status,0);assert.match(unselected.stdout+unselected.stderr,/task_selection_mismatch/);
597
+ const wrong=f.drive(f.plan({...bare,permissions:['--feature','0.early']}),'status');
598
+ assert.equal(wrong.status,2);assert.match(wrong.stderr,/必须与运行定义的 feature 1\.work 一致/);
599
+ const bound=['--feature','1.work','--review-runtime','claude'];
600
+ const created=f.drive(f.plan({...bare,permissions:bound}),'status');
601
+ assert.equal(created.status,0,created.stderr);assert.equal(fs.existsSync(f.store),true);
602
+ const resumed=f.drive(f.plan({...bare,mode:'resume',permissions:bound}),'status');
603
+ assert.equal(resumed.status,0,resumed.stderr);
604
+ const unbound=f.drive(f.plan({...bare,mode:'resume'}),'status');
605
+ assert.notEqual(unbound.status,0);assert.match(unbound.stdout+unbound.stderr,/fingerprint_mismatch/);
606
+ });
@@ -0,0 +1,178 @@
1
+ // Explicit batch (feature) selection. An approved cross-feature order may run a
2
+ // later feature while an earlier one still has pending tasks: the 2026-10-06
3
+ // AI潮 6.api-native-reading batch before 5.author-column T-009/T-010. Without an
4
+ // explicit selection, admission still picks the lowest-numbered pending feature.
5
+ import nodeTest from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {spawnSync} from 'node:child_process';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {buildManifest} from './cm-spec-manifest.mjs';
13
+ import {inspectCmAiAdmission,isFinalCmAiTask} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
14
+ import {inspectCmAiContextRefresh} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
15
+ import {openControlRun,validateRunDefinition} from './cm-ai-run.mjs';
16
+ import {isSupportedExecutionPlatform} from '../runtime/js/cm-ai/execution-platform.mjs';
17
+
18
+ const platform=isSupportedExecutionPlatform();
19
+ const test=(name,fn)=>nodeTest(name,{skip:!platform},fn);
20
+ const admissionCli=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
21
+ const runCli=fileURLToPath(new URL('./cm-ai-run.mjs',import.meta.url));
22
+ const EARLY='5.author',LATER='6.reader';
23
+
24
+ function project(t,{later='- [ ] T-001: reader contract\n- [ ] T-002: mapping\n\n## 依赖\n\n- T-002 依赖 T-001\n'}={}){
25
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-feature-selection-')));
26
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
27
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code');
28
+ fs.mkdirSync(codeProject);fs.writeFileSync(path.join(codeProject,'a.js'),'old\n');
29
+ for(const [feature,tasks] of [[EARLY,'- [x] T-008: done\n- [ ] T-009: after the reader batch\n'],[LATER,later]]){
30
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
31
+ for(const file of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,file),`# ${feature}\n`);
32
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),tasks);
33
+ }
34
+ const approve=()=>fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',
35
+ features:[EARLY,LATER],specFiles:buildManifest(specsDir)}));
36
+ approve();
37
+ const admission=(...args)=>{
38
+ const out=spawnSync(process.execPath,[admissionCli,'--specs-dir',specsDir,'--code-project',codeProject,...args],{encoding:'utf8'});
39
+ return {...out,json:out.stdout.trim()?JSON.parse(out.stdout):null};
40
+ };
41
+ const definition=(taskId,extra={})=>({version:1,specsDir,codeProject,feature:LATER,
42
+ identity:{repositoryId:'fixture',runId:`reader-${taskId}-run`,taskId,attempt:1},scope:['a.js'],requirements:[],...extra});
43
+ const selected={featureSelection:{version:1,feature:LATER}};
44
+ return {root,specsDir,codeProject,approve,admission,definition,selected};
45
+ }
46
+
47
+ test('without an explicit choice admission still selects the lowest-numbered pending feature',t=>{
48
+ const f=project(t);
49
+ const result=f.admission();
50
+ assert.equal(result.status,0,result.stderr);
51
+ assert.deepEqual(result.json.nextTask,{feature:EARLY,id:'T-009',description:'after the reader batch'});
52
+ assert.equal(Object.hasOwn(result.json,'requestedFeatureComplete'),false);
53
+ });
54
+
55
+ test('an explicit later feature is selected with its own dependency rule and the earlier feature untouched',t=>{
56
+ const f=project(t);
57
+ const tasksBefore=fs.readFileSync(path.join(f.specsDir,EARLY,'tasks.md'));
58
+ const result=f.admission('--feature',LATER);
59
+ assert.equal(result.status,0,result.stderr);
60
+ assert.equal(result.json.state,'ready');
61
+ assert.deepEqual(result.json.nextTask,{feature:LATER,id:'T-001',description:'reader contract'});
62
+ // T-002 depends on T-001: only T-001 is eligible.
63
+ assert.deepEqual(result.json.eligibleTasks,[{feature:LATER,id:'T-001'}]);
64
+ assert.deepEqual(result.json.features.map(item=>[item.name,item.pending]),[[EARLY,1],[LATER,2]]);
65
+ assert.deepEqual(fs.readFileSync(path.join(f.specsDir,EARLY,'tasks.md')),tasksBefore);
66
+ const printed=f.admission('--feature',LATER,'--print-run-definition','--scope','a.js');
67
+ assert.equal(printed.status,0,printed.stderr);
68
+ assert.deepEqual(printed.json.featureSelection,{version:1,feature:LATER});
69
+ assert.equal(printed.json.feature,LATER);assert.equal(printed.json.identity.taskId,'T-001');
70
+ const blocked=f.admission('--feature',LATER,'--print-run-definition','--scope','a.js','--task','T-002');
71
+ assert.equal(blocked.status,1);assert.match(blocked.stderr,/task_selection_mismatch/);assert.match(blocked.stderr,/T-001 尚未完成/);
72
+ const missing=f.admission('--feature','7.missing');
73
+ assert.equal(missing.status,1);assert.equal(missing.json.reason,'feature_selection_invalid');
74
+ });
75
+
76
+ test('an explicit choice keeps every approval gate: manifest drift and unapproved specs still block',t=>{
77
+ const f=project(t);
78
+ fs.appendFileSync(path.join(f.specsDir,EARLY,'requirements.md'),'drift\n');
79
+ const drift=f.admission('--feature',LATER);
80
+ assert.equal(drift.status,1);assert.equal(drift.json.reason,'spec_drift');
81
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',features:[EARLY,LATER]}));
82
+ const pending=f.admission('--feature',LATER);
83
+ assert.equal(pending.json.state,'awaiting_spec_approval');assert.equal(pending.json.nextTask,null);
84
+ });
85
+
86
+ test('a completed selected feature is reported and never yields another feature definition or run',async t=>{
87
+ const f=project(t,{later:'- [x] T-001: reader contract\n'});
88
+ const result=f.admission('--feature',LATER);
89
+ assert.equal(result.status,0,result.stderr);
90
+ assert.equal(result.json.requestedFeatureComplete,LATER);
91
+ assert.equal(result.json.nextTask.feature,EARLY);
92
+ assert.match(result.json.warnings.join(' '),new RegExp(`所选 feature ${LATER} 已无待办任务`));
93
+ const printed=f.admission('--feature',LATER,'--print-run-definition','--scope','a.js');
94
+ assert.equal(printed.status,1);assert.equal(printed.stdout,'');assert.match(printed.stderr,/feature_tasks_terminal/);
95
+ await assert.rejects(openControlRun(validateRunDefinition(f.definition('T-001',f.selected)),'create'),
96
+ error=>error.code==='task_selection_mismatch'&&/已无待办任务/.test(error.reason));
97
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution')),false);
98
+ });
99
+
100
+ test('a run creates for an explicit later feature, refuses without it, and refuses a task whose dependency is pending',async t=>{
101
+ const f=project(t);
102
+ // Unchanged 0.16.7 behaviour without an explicit choice.
103
+ await assert.rejects(openControlRun(validateRunDefinition(f.definition('T-001')),'create'),
104
+ error=>error.code==='task_selection_mismatch'&&error.reason.includes(`当前 feature ${EARLY}`)&&error.reason.includes('--feature'));
105
+ await assert.rejects(openControlRun(validateRunDefinition(f.definition('T-002',f.selected)),'create'),
106
+ error=>error.code==='task_selection_mismatch'&&error.reason.includes('T-001 尚未完成'));
107
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution')),false);
108
+ const config=path.join(f.root,'run.json');fs.writeFileSync(config,JSON.stringify(f.definition('T-001',f.selected)));
109
+ const invoke=mode=>{
110
+ const out=spawnSync(process.execPath,[runCli,'serve','--config',config,'--mode',mode],{encoding:'utf8',timeout:20000,
111
+ input:[{version:1,operation:'status',requestId:'status',identity:f.definition('T-001').identity}].map(JSON.stringify).join('\n')+'\n'});
112
+ return {...out,rows:out.stdout.trim().split('\n').filter(Boolean).map(JSON.parse)};
113
+ };
114
+ const created=invoke('create');
115
+ assert.equal(created.status,0,created.stderr);
116
+ assert.equal(created.rows.find(row=>row.requestId==='status').result.identity.taskId,'T-001');
117
+ const journal=path.join(f.specsDir,'.reviews','.execution','reader-T-001-run','state.json');
118
+ const before=fs.readFileSync(journal);
119
+ const resumed=invoke('resume');
120
+ assert.equal(resumed.status,0,resumed.stderr);
121
+ assert.equal(resumed.rows.find(row=>row.requestId==='status').result.identity.taskId,'T-001');
122
+ assert.deepEqual(fs.readFileSync(journal),before);
123
+ // The selection is part of the durable definition: dropping it changes the run.
124
+ fs.writeFileSync(config,JSON.stringify(f.definition('T-001')));
125
+ const dropped=invoke('resume');assert.equal(dropped.status,1);assert.match(dropped.stderr,/fingerprint_mismatch/);
126
+ assert.match(fs.readFileSync(path.join(f.specsDir,EARLY,'tasks.md'),'utf8'),/- \[ \] T-009/);
127
+ });
128
+
129
+ test('in-run admission for an explicit run reads the selected feature (context refresh and last-task check)',t=>{
130
+ const f=project(t,{later:'- [ ] T-001: reader contract\n'});
131
+ const input={specsDir:f.specsDir,codeProject:f.codeProject,feature:LATER,applicableAgentFiles:[]};
132
+ assert.throws(()=>inspectCmAiContextRefresh(input),{code:'context_invalid'});
133
+ const refresh=inspectCmAiContextRefresh({...input,featureSelection:LATER});
134
+ assert.deepEqual(refresh.nextTask,{feature:LATER,id:'T-001',description:'reader contract'});
135
+ assert.throws(()=>inspectCmAiContextRefresh({...input,featureSelection:EARLY}),{code:'context_invalid'});
136
+ assert.throws(()=>isFinalCmAiTask({specsDir:f.specsDir,codeProject:f.codeProject,feature:LATER,taskId:'T-001'}),
137
+ {code:'documentation_admission_required'});
138
+ // Two tasks are pending in the project (T-009 too): not the final task.
139
+ assert.equal(isFinalCmAiTask({specsDir:f.specsDir,codeProject:f.codeProject,feature:LATER,taskId:'T-001',featureSelection:LATER}),false);
140
+ assert.equal(inspectCmAiAdmission({specsDir:f.specsDir,codeProject:f.codeProject}).nextTask.feature,EARLY);
141
+ });
142
+
143
+ test('run definitions accept featureSelection only for their own feature',t=>{
144
+ const f=project(t);
145
+ assert.deepEqual(validateRunDefinition(f.definition('T-001',f.selected)).featureSelection,{version:1,feature:LATER});
146
+ for(const bad of [{version:1,feature:EARLY},{version:2,feature:LATER},{version:1,feature:LATER,extra:true},null])
147
+ assert.throws(()=>validateRunDefinition(f.definition('T-001',{featureSelection:bad})),{code:'invalid_feature_selection'});
148
+ });
149
+
150
+ test('the human approval phrase 可以,请开始开发 is an explicit start; looser phrasings are not',t=>{
151
+ const f=project(t);
152
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',features:[EARLY,LATER]}));
153
+ for(const reply of ['可以,请开始开发','可以,请开始开发。'])
154
+ assert.equal(f.admission('--approval-response',reply).json.approvalIntent,'explicit',reply);
155
+ for(const reply of ['开始开发','请开始开发','可以,请开始开发,但别现在做','可以'])
156
+ assert.equal(f.admission('--approval-response',reply).json.approvalIntent,'not_approval',reply);
157
+ });
158
+
159
+ test('after its last task an explicit run still refreshes context; the next task is the project own one',t=>{
160
+ const f=project(t,{later:'- [x] T-001: reader contract\n'});
161
+ const refresh=inspectCmAiContextRefresh({specsDir:f.specsDir,codeProject:f.codeProject,feature:LATER,applicableAgentFiles:[],featureSelection:LATER});
162
+ assert.equal(refresh.state,'ready');assert.equal(refresh.nextTask.feature,EARLY);
163
+ assert(refresh.contextFiles.some(file=>file.path===`${LATER}/tasks.md`));
164
+ const admission=inspectCmAiAdmission({specsDir:f.specsDir,codeProject:f.codeProject,feature:LATER});
165
+ assert.deepEqual(admission.features.map(item=>item.name),[EARLY,LATER]);
166
+ });
167
+
168
+ test('with every task done an explicit feature still refuses to print or create, not exit 0',async t=>{
169
+ const f=project(t,{later:'- [x] T-001: reader contract\n'});
170
+ fs.writeFileSync(path.join(f.specsDir,EARLY,'tasks.md'),'- [x] T-008: done\n- [x] T-009: done\n');f.approve();
171
+ const admission=f.admission('--feature',LATER);
172
+ assert.equal(admission.json.state,'complete');assert.equal(admission.json.requestedFeatureComplete,LATER);
173
+ const printed=f.admission('--feature',LATER,'--print-run-definition','--scope','a.js');
174
+ assert.equal(printed.status,1);assert.equal(printed.stdout,'');assert.match(printed.stderr,/feature_tasks_terminal/);
175
+ await assert.rejects(openControlRun(validateRunDefinition(f.definition('T-001',f.selected)),'create'),
176
+ error=>error.code==='task_selection_mismatch'&&/已无待办任务/.test(error.reason));
177
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution')),false);
178
+ });
@@ -10,7 +10,7 @@ import path from 'node:path';
10
10
  import {spawnSync} from 'node:child_process';
11
11
  import {fileURLToPath} from 'node:url';
12
12
  import {REVIEWED_HANDOFF_HINT} from '../runtime/js/cm-ai/host-handoff.mjs';
13
- import {readRunDefinition,openControlRun,createCodexExecution} from './cm-ai-run.mjs';
13
+ import {readRunDefinition,openControlRun,createCodexExecution,assertCreatableScope} from './cm-ai-run.mjs';
14
14
  import {createConversationExecution as executionFor} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
15
15
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
16
16
  import {serveCmAiHost,parseHostInputLimit,inputLimitReason} from '../runtime/js/cm-ai/host-session.mjs';
@@ -46,12 +46,12 @@ export function readBootstrapConfiguration(file){
46
46
  const refuse=(ok,code,reason)=>{if(!ok)throw Object.assign(new Error(code),{code,reason});};
47
47
  const REASONED_CODES=['supersede_unavailable','supersede_code_drift','handoff_exists','browser_capability_required',
48
48
  'browser_capability_unavailable','invalid_arguments','fingerprint_mismatch','task_selection_mismatch','review_configuration_required',
49
- 'spec_rebind_refused','spec_rebind_unavailable'];
49
+ 'spec_rebind_refused','spec_rebind_unavailable','protected_scope'];
50
50
  const fixLocalPermissions=new Map(['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon',
51
51
  'abandon-review','test-author','repair','cause-review','final-review']
52
52
  .map(name=>[`--allow-qa-fix-${name}`,`--allow-${name}`]));
53
53
 
54
- const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development --review-config PATH (required at create; resume passes the same file) [--original-host-context ID] [--runtime codex|claude] [--input-limit BYTES] [--failover] [--allow-review-attempt 1|2] [--allow-abandon-review] [--allow-abandon-effect] [--allow-bootstrap-review-recovery] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it bounds every input line and every tool reply, and may change on resume. A longer line stops the session with request_too_large. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000), independent of protected mode and outside the authorized configuration digest. --browser-qa declares interactive QA capability for applicable carriers including browser and ios-simulator.\nNew runs: --external-models [--external-models-config FILE] freezes one pair per actual external provider; resume reads only its snapshot. preflight --config RUN_DEFINITION.json --external-provider codex|claude uses the saved pair.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
54
+ const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development --review-config PATH (required at create; resume passes the same file) [--original-host-context ID] [--runtime codex|claude] [--review-runtime codex|claude] [--feature N.slug] [--input-limit BYTES] [--failover] [--allow-review-attempt 1|2] [--allow-abandon-review] [--allow-abandon-effect] [--allow-bootstrap-review-recovery] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it bounds every input line and every tool reply, and may change on resume. A longer line stops the session with request_too_large. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000), independent of protected mode and outside the authorized configuration digest. --browser-qa declares interactive QA capability for applicable carriers including browser and ios-simulator.\nNew runs: --external-models [--external-models-config FILE] freezes one pair per actual external provider; resume reads only its snapshot. preflight --config RUN_DEFINITION.json --external-provider codex|claude uses the saved pair.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
55
55
 
56
56
  export function formatClaudeModelHint(config,version=null){
57
57
  const marker=config?.preflight?.request_checks?.find(check=>check?.model_recognized===false);
@@ -223,7 +223,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
223
223
  const extra=new Map();
224
224
  for(let index=8;index<argv.length;index++){
225
225
  const name=argv[index];refuse(!extra.has(name),'invalid_arguments',`参数重复:${name}`);
226
- refuse(['--execution-optimizations','--external-models','--external-models-config','--verification-precheck','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure','--supersede-reviewed-evidence','--supersede-reason','--accept-superseded-code-drift','--rebind-spec-material','--spec-rebind-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments',`未知参数:${name}`);
226
+ refuse(['--execution-optimizations','--external-models','--external-models-config','--verification-precheck','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure','--supersede-reviewed-evidence','--supersede-reason','--accept-superseded-code-drift','--rebind-spec-material','--spec-rebind-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--review-runtime','--feature','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments',`未知参数:${name}`);
227
227
  if(['--execution-optimizations','--external-models','--verification-precheck','--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material','--allow-bootstrap-write','--allow-qa','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--rerun-unknown-qa','--rerun-blocked-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
228
228
  else{refuse(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments',`${name} 需要一个值`);extra.set(name,argv[++index]);}
229
229
  }
@@ -262,13 +262,25 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
262
262
  need(!extra.has('--auto-qa-fix')||(extra.has('--qa-fix-template-config')&&extra.has('--allow-qa-fix-start')),'qa_fix_auto_authorization_required');
263
263
  need(![...fixLocalPermissions.keys()].some(flag=>extra.has(flag))||extra.has('--allow-qa-fix-start'),'qa_fix_start_authorization_required');
264
264
  need(!extra.has('--allow-provider-development-attempt')||extra.has('--protected-config'),'protected_configuration_required');
265
+ refuse(!(extra.has('--review-runtime')&&(extra.has('--protected-config')||extra.has('--external-models'))),'invalid_arguments',
266
+ '--review-runtime 只用于普通当前会话宿主;--protected-config 与 --external-models 按 roles 自行选择审查端');
265
267
  refuse(!(extra.has('--protected-config')&&extra.has('--protected-conversation-config')),'invalid_arguments','--protected-config 与 --protected-conversation-config 不能同时使用');
266
268
  const protection=extra.has('--protected-conversation-config')?readConversationProtection(extra.get('--protected-conversation-config')):null;
267
269
  const bootstrap=extra.has('--bootstrap-config')?readBootstrapConfiguration(extra.get('--bootstrap-config')):null;
268
270
  need(!extra.has('--allow-bootstrap-write')||bootstrap!==null,'bootstrap_configuration_required');
269
271
  // Checked before the definition is read so the conflict is reported on its own.
270
272
  need(!(extra.has('--failover')&&extra.has('--protected-config')),'failover_unsupported_in_protected_mode');
271
- const definition=readRunDefinition(argv[2]);
273
+ let definition=readRunDefinition(argv[2]);
274
+ // --feature binds an explicit batch choice into the run definition, exactly
275
+ // as a printed featureSelection does; resume must repeat it (fingerprint).
276
+ if(extra.has('--feature')){
277
+ refuse(extra.get('--feature')===definition.feature&&(!definition.featureSelection
278
+ ||definition.featureSelection.feature===definition.feature),'invalid_arguments',
279
+ `--feature ${extra.get('--feature')} 必须与运行定义的 feature ${definition.feature} 一致`);
280
+ definition={...definition,featureSelection:{version:1,feature:definition.feature}};
281
+ }
282
+ // Before any frozen model/policy configuration, execution or journal write.
283
+ if(argv[4]==='create'&&bootstrap===null)assertCreatableScope(definition.scope);
272
284
  const boundRuntime=extra.get('--runtime')??'codex';
273
285
  const routes=extra.has('--protected-config')?resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),boundRuntime):{reviewerRuntime:boundRuntime};
274
286
  const executionPolicy=readLaunchExecutionPolicy({definition,mode:argv[4],enabled:extra.has('--execution-optimizations')});
@@ -329,7 +341,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
329
341
  execution=extra.has('--protected-config')
330
342
  ?await protectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap,externalModels,executionPolicy)
331
343
  :executionFor(definition,argv[6],bridge,review,allowedAttempt,workflow,extra.has('--allow-qa'),runtime,
332
- {...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),...(extra.has('--verification-precheck')?{verificationPrecheck:true}:{}),...(extra.has('--original-host-context')?{originalHostContextId:extra.get('--original-host-context')}:{}),...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
344
+ {...(extra.has('--review-runtime')?{reviewRuntime:extra.get('--review-runtime')}:{}),...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),...(extra.has('--verification-precheck')?{verificationPrecheck:true}:{}),...(extra.has('--original-host-context')?{originalHostContextId:extra.get('--original-host-context')}:{}),...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
333
345
  run=await openControlRun(definition,argv[4],execution,{qaConfigRevision,rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa'),qaEnvironmentFailure:extra.get('--qa-environment-failure')??null,supersedeReason:extra.get('--supersede-reason')??null,acceptSupersededCodeDrift:extra.has('--accept-superseded-code-drift'),allowAbandonReview:extra.has('--allow-abandon-review'),allowAbandonEffect:extra.has('--allow-abandon-effect'),allowBootstrapReviewRecovery:extra.has('--allow-bootstrap-review-recovery'),specRebindReason:extra.get('--spec-rebind-reason')??null});
334
346
  }
335
347
  if(run.blocked){output.write(JSON.stringify({outcome:'blocked',admission:run.blocked})+'\n');return 1;}