@aibyzero/cm-workflow 0.16.9 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +9 -1
  4. package/VERSION +1 -1
  5. package/docs/cm-control-policy-v2.md +331 -0
  6. package/docs/execution-optimizations.md +1 -1
  7. package/docs/external-models.md +3 -3
  8. package/docs/human-correction.md +5 -5
  9. package/docs/installation.md +1 -1
  10. package/docs/js-workflow-control.md +101 -84
  11. package/docs/next-steps.md +11 -0
  12. package/docs/untested-branches.md +2 -3
  13. package/docs/user-guide.md +3 -3
  14. package/package.json +1 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  17. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  18. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  20. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  23. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  24. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  25. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  26. package/runtime/js/cm-ai/host-tool-bridge.mjs +3 -0
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  28. package/runtime/js/cm-ai/host.mjs +1 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +1 -24
  30. package/runtime/js/cm-ai/review-package.mjs +16 -4
  31. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  32. package/runtime/js/cm-ai/task-runner.mjs +36 -99
  33. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  34. package/runtime/js/cm-prd/review-host.mjs +1 -1
  35. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  36. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  37. package/runtime/js/notify-send.mjs +15 -14
  38. package/runtime/js/notify.mjs +27 -4
  39. package/runtime/js/policy-binding-compat.mjs +2 -1
  40. package/runtime/review.md +52 -7
  41. package/runtime/task-gates.md +107 -9
  42. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  43. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  44. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  45. package/scripts/cm-ai-batch-drive.mjs +50 -31
  46. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  47. package/scripts/cm-ai-batch-host.mjs +39 -20
  48. package/scripts/cm-ai-batch-host.test.mjs +62 -38
  49. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  50. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  51. package/scripts/cm-ai-batch-run.mjs +34 -8
  52. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  53. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  54. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  55. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  56. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  57. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  58. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  59. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  60. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  61. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  62. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  63. package/scripts/cm-ai-drive.mjs +96 -54
  64. package/scripts/cm-ai-drive.test.mjs +43 -84
  65. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  66. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  67. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  68. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  69. package/scripts/cm-ai-host-fixture.mjs +38 -10
  70. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  71. package/scripts/cm-ai-host.mjs +103 -93
  72. package/scripts/cm-ai-host.test.mjs +19 -18
  73. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  74. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  75. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  76. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  77. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  78. package/scripts/cm-ai-progress.test.mjs +10 -8
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  80. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  81. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  82. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  83. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  84. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  85. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  86. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  87. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  88. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  89. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  90. package/scripts/cm-ai-review-timeout.test.mjs +15 -128
  91. package/scripts/cm-ai-run.mjs +78 -24
  92. package/scripts/cm-ai-run.test.mjs +11 -38
  93. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  94. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  95. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  96. package/scripts/cm-ai-supersede.test.mjs +3 -10
  97. package/scripts/cm-blocked-reason.test.mjs +2 -3
  98. package/scripts/cm-capability-gate.test.mjs +33 -1
  99. package/scripts/cm-check-drive-files.mjs +1 -1
  100. package/scripts/cm-check-runtime.sh +1 -1
  101. package/scripts/cm-claude-worker.test.mjs +5 -3
  102. package/scripts/cm-controlled-correction.test.mjs +469 -0
  103. package/scripts/cm-external-batch-host.test.mjs +30 -11
  104. package/scripts/cm-external-model-host.test.mjs +1 -1
  105. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  106. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  107. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  108. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  109. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  110. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  111. package/scripts/cm-host-review-authority.test.mjs +0 -31
  112. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  113. package/scripts/cm-notify-command.test.mjs +54 -18
  114. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  115. package/scripts/cm-notify.mjs +16 -4
  116. package/scripts/cm-notify.test.mjs +91 -19
  117. package/scripts/cm-patrol.test.mjs +3 -2
  118. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  119. package/scripts/cm-task-gate.mjs +368 -34
  120. package/scripts/cm-task-gate.py +2 -0
  121. package/scripts/cm-task-gate.test.mjs +252 -4
  122. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  123. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  124. package/scripts/policy-binding-compat.test.mjs +4 -0
  125. package/skills/cm-ai/SKILL.md +8 -6
  126. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  127. package/skills/cm-ai/references/N4-review.md +11 -21
  128. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  129. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  130. package/skills/cm-ai/references/js-host-modes.md +35 -14
  131. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  132. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  133. package/skills/cm-ai/references/js-host.md +65 -28
  134. package/skills/cm-fix/SKILL.md +12 -0
  135. package/skills/cm-init/references/js-host.md +1 -1
  136. package/skills/cm-prd/references/js-host.md +1 -1
  137. package/skills/cm-refactor/SKILL.md +12 -0
  138. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  139. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -6,6 +6,8 @@ import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {buildManifest} from './cm-spec-manifest.mjs';
9
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
+ import {claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
9
11
  import {cmInitRuleTargets} from '../runtime/js/cm-init/draft-generation.mjs';
10
12
  import {bootstrapDriverGap} from './cm-ai-drive.mjs';
11
13
  import {inspectDriverBootstrap,readBootstrapRulesAnswers,createBootstrapRulesResponder} from '../runtime/js/cm-ai/drive-bootstrap.mjs';
@@ -46,7 +48,8 @@ function fixture(t,{scaffolded=false,nested=false}={}){
46
48
  identity:{repositoryId:'app',runId:`bootstrap-${key}`,taskId,attempt:1},scope,requirements:[]}));
47
49
  const writeBootstrap=value=>fs.writeFileSync(path.join(root,'bootstrap.json'),JSON.stringify({selection:value}));
48
50
  // create requires a bound review configuration; this placeholder grants no review.
49
- fs.writeFileSync(path.join(root,'placeholder-review.json'),JSON.stringify({model:'fixture',preflight:{}}));
51
+ fs.writeFileSync(path.join(root,'placeholder-review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,provider:'claude',cli_model:'fixture',prompt_transport:'stdin',
52
+ config_fingerprint:claudeReviewFingerprint({cwd:codeProject,model:'fixture'})}}));
50
53
  const plan=(key,mode,permissions,extra={})=>{
51
54
  const file=path.join(root,`plan-${Math.random().toString(36).slice(2)}.json`);
52
55
  const bound=permissions.includes('--review-config')?permissions:[...permissions,'--review-config','placeholder-review.json'];
@@ -174,17 +177,35 @@ test('rules answer files are validated before the host starts',t=>{
174
177
  f.write('init-verify.json',verifyAnswer());f.write('init-verify-a1.json',verifyAnswer());
175
178
  assertRefusedBeforeLaunch(f,run(),/init-verify\.json 与 init-verify-a1\.json 不能同时存在/);
176
179
  fs.rmSync(path.join(f.answers,'init-verify-a1.json'));
177
- // A revision written before its findings exist is refused, even when preloaded.
178
- const pattern=/advance 不能带 --allow-review-attempt 1 直接进入第 2 轮.*\.reviews\/bootstrap-T-002-r1\.md.*init-verify-a2\.json/;
179
- assertRefusedBeforeLaunch(f,run({permissions:['--allow-review-attempt','1']}),pattern);
180
- const {generate:revision}=rulesDocuments(f,2);f.write('init-generate-a2.json',revision);f.write('init-verify-a2.json',verifyAnswer());
181
- assertRefusedBeforeLaunch(f,run({permissions:['--allow-review-attempt','1']}),pattern);
182
180
  // The host inspects the raw draft before merging AGENTS.md lessons; so does the driver.
183
181
  rulesDocuments(f,1);fs.writeFileSync(path.join(f.codeProject,'AGENTS.md'),'## 项目教训\n\n- 骨架教训\n');
184
182
  f.write(generate.documents[0].contentFile,' \n');
185
183
  assertRefusedBeforeLaunch(f,run(),/^\[drive\] init-generate\.json 无效: init_draft_invalid/m);
186
184
  });
187
185
 
186
+ // The claude review preflight needs the macOS loopback sandbox; keep this case
187
+ // darwin-only like the other review-dispatching cases in this file.
188
+ test('direct review holds the first revision even when attempt-2 answers are preloaded',
189
+ {skip:process.platform!=='darwin'},t=>{
190
+ const held=fixture(t,{scaffolded:true});held.writeRun('T-001',Object.keys(scaffold));held.writeRun('T-002',[...held.targets]);
191
+ held.writeBootstrap(selection);prepareRules(held,1);reviewFixture(held);
192
+ const paused=held.drive(held.plan('T-002','create',[...rulesPermissions,'--review-config','review.json']),'advance');
193
+ assert.equal(paused.status,0,paused.stderr);assert.equal(result(paused).state,'changes_requested');
194
+ assert.equal(result(paused).code,'revision_answer_required');assert.equal(result(paused).identity.attempt,2);
195
+ assert.equal(fs.existsSync(path.join(held.answers,'init-generate-a2.json')),false);
196
+ const heldRows=JSON.parse(fs.readFileSync(path.join(held.store('T-002'),'state.json'))).records;
197
+ assert.equal(heldRows.filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').length,1);
198
+ const preloaded=fixture(t,{scaffolded:true});preloaded.writeRun('T-001',Object.keys(scaffold));preloaded.writeRun('T-002',[...preloaded.targets]);
199
+ preloaded.writeBootstrap(selection);const initial=prepareRules(preloaded,1);prepareRules(preloaded,2);reviewFixture(preloaded);
200
+ const premature=preloaded.drive(preloaded.plan('T-002','create',[...rulesPermissions,'--review-config','review.json']),'advance');
201
+ assert.equal(premature.status,0,premature.stderr);assert.equal(result(premature).state,'changes_requested');
202
+ assert.equal(result(premature).code,'revision_answer_required');
203
+ const prematureRows=JSON.parse(fs.readFileSync(path.join(preloaded.store('T-002'),'state.json'))).records;
204
+ assert.equal(prematureRows.filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').length,1);
205
+ assert.equal(read(preloaded,'.claude/rules/testing.md'),initial['.claude/rules/testing.md'],'preloaded a2 bytes are never consumed before findings');
206
+ assert.equal(prematureRows.filter(row=>row.payload.type==='review-invocation-registered').length,1);
207
+ });
208
+
188
209
  test('attempt 1 refuses existing instructions the host would not overwrite',t=>{
189
210
  const f=fixture(t,{scaffolded:true});f.writeRun('T-002',[...f.targets]);f.writeBootstrap(selection);prepareRules(f,1);
190
211
  const run=()=>f.drive(f.plan('T-002','create',rulesPermissions),'advance');
@@ -329,9 +350,9 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
329
350
  edits:Object.fromEntries(scope.map(file=>[file,`t001/${file}`]))});
330
351
  reviewFixture(f);
331
352
  const review=['--review-config','review.json'];
332
- let run=f.drive(f.plan('T-001','create',[...rulesPermissions,...review]),'advance');
353
+ let run=f.drive(f.plan('T-001','create',[...rulesPermissions,...review]),'start');
333
354
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review');
334
- run=f.drive(f.plan('T-001','resume',[...rulesPermissions,...review,'--allow-review-attempt','1'],{packageDigest:result(run).packageDigest}),'decision');
355
+ run=f.drive(f.plan('T-001','resume',[...rulesPermissions,...review],{packageDigest:result(run).packageDigest}),'decision');
335
356
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'approved');
336
357
  run=f.drive(f.plan('T-001','resume',[...rulesPermissions,...review]),'advance');
337
358
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'fixture_completed');
@@ -339,7 +360,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
339
360
 
340
361
  f.writeRun('T-002',[...f.targets]);f.writeBootstrap(selection);
341
362
  // Missing answers are refused before the T-002 run exists.
342
- assertRefusedBeforeLaunch(f,f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'advance'),/init-generate\.json/);
363
+ assertRefusedBeforeLaunch(f,f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'start'),/init-generate\.json/);
343
364
  // Attempt 1 records a real lesson: the host writes it back into AGENTS.md after the rules.
344
365
  const lesson={status:'lesson_candidate',candidates:[{classification:'structured',trigger:'SwiftUI rules bootstrap',
345
366
  action:'Keep scripts/verify.sh as the structure check',evidence:['scripts/verify.sh']}],reason:null};
@@ -348,7 +369,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
348
369
  const matches=(docs)=>{for(const file of f.targets)if(file==='AGENTS.md'){
349
370
  assert(read(f,file).startsWith(docs[file]),file);assert.match(read(f,file),/## 项目教训[\s\S]*Keep scripts\/verify\.sh/);}
350
371
  else assert.equal(read(f,file),docs[file],file);};
351
- run=f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'advance');
372
+ run=f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'start');
352
373
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
353
374
  assert.match(run.stderr,/应答 init_generate/);assert.match(run.stderr,/应答 init_verify/);assert.match(run.stderr,/应答 check/);
354
375
  assert.doesNotMatch(run.stderr,/应答 develop/);
@@ -356,16 +377,18 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
356
377
  const waiting=result(run).packageDigest,state=path.join(f.store('T-002'),'state.json');
357
378
  // Review may lead straight into attempt 2 inside this advance: the revision must wait for findings.
358
379
  let before=fs.readFileSync(state);
359
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review,'--allow-review-attempt','1']),'advance');
360
- assert.equal(run.status,2,run.stderr);
361
- assert.match(run.stderr,new RegExp(`须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${waiting}.*bootstrap-T-002-r1\\.md`));
362
- assert.deepEqual(fs.readFileSync(state),before);
363
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review,'--allow-review-attempt','1'],{packageDigest:waiting}),'decision');
380
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'advance');
381
+ assert.equal(run.status,0,run.stderr);
382
+ assert.equal(result(run).state,'changes_requested');assert.equal(result(run).code,'revision_answer_required');
383
+ const afterReview=JSON.parse(fs.readFileSync(state)).records;
384
+ assert.deepEqual(afterReview.slice(0,JSON.parse(before).records.length),JSON.parse(before).records);
385
+ assert.equal(afterReview.filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').length,1);
386
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review],{packageDigest:waiting}),'decision');
364
387
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'changes_requested');
365
388
  assert(fs.existsSync(path.join(f.specsDir,'.reviews','bootstrap-T-002-r1.md')));
366
389
 
367
390
  before=fs.readFileSync(state);
368
- const again=()=>f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'advance');
391
+ const again=()=>f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'start');
369
392
  run=again();assert.equal(run.status,2,run.stderr);
370
393
  assert.match(run.stderr,/第 2 轮规范修订,但答案文件不存在: .*init-generate-a2\.json.*bootstrap-T-002-r1\.md/);
371
394
  assert.deepEqual(fs.readFileSync(state),before);
@@ -377,7 +400,13 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
377
400
  const marker=path.join(f.root,'ran.marker');
378
401
  prepareRules(f,2,{commands:[{id:'marker',command:['/bin/sh','-c',`echo ran > ${marker}`]}]});
379
402
  for(const extra of [{hostContext:'another-session'},{runtime:'codex'}]){
380
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review],extra),'advance');
403
+ let launchReview=review;
404
+ if(extra.runtime==='codex'){
405
+ fs.writeFileSync(path.join(f.root,'wrong-runtime-review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,
406
+ cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
407
+ launchReview=['--review-config','wrong-runtime-review.json'];
408
+ }
409
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...launchReview],extra),'start');
381
410
  assert.equal(run.status,1,run.stderr);assert.match(run.stderr,/fingerprint_mismatch/);
382
411
  assert.doesNotMatch(run.stderr,/\[drive init_verify/);
383
412
  assert.equal(fs.existsSync(marker),false);assert.deepEqual(fs.readFileSync(state),before);
@@ -396,7 +425,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
396
425
  assert.notEqual(second['.claude/rules/testing.md'],first['.claude/rules/testing.md']);
397
426
  // The driver's decision request carries the run definition's attempt-1 identity;
398
427
  // the second review runs inside advance with the attempt-2 review grant.
399
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review,'--allow-review-attempt','2']),'advance');
428
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'advance');
400
429
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'fixture_completed',run.stdout);
401
430
  assert.match(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8'),/\[x\] T-002/);
402
431
  const handoff=JSON.parse(fs.readFileSync(path.join(f.specsDir,'.reviews','bootstrap-T-002-a2-handoff.json'),'utf8'));
@@ -411,7 +440,7 @@ test('a failing init_verify command really runs after the host accepts the launc
411
440
  // The session's semantic groups say verified; only the real command decides the commands group.
412
441
  fs.writeFileSync(path.join(f.codeProject,'scripts/verify.sh'),'echo strict-check-ran >&2\n'+scaffold['scripts/verify.sh']);
413
442
  prepareRules(f,1,{commands:[{id:'strict',command:['/bin/sh','scripts/verify.sh','--strict'],timeoutMs:60000}]});
414
- const failed=f.drive(f.plan('T-002','create',permissions),'advance');
443
+ const failed=f.drive(f.plan('T-002','create',permissions),'start');
415
444
  assert.equal(failed.status,2,failed.stderr);
416
445
  assert.match(failed.stderr,/init-verify\.json 的命令在发送操作前实跑未通过:strict: failed(host check exited 1)/);
417
446
  assert.match(failed.stderr,/PLAN\.mode 改为 resume/);
@@ -422,7 +451,7 @@ test('a failing init_verify command really runs after the host accepts the launc
422
451
  assert.equal(fs.existsSync(path.join(f.codeProject,'.claude')),false);
423
452
  // Fix the draft's command list; the host-created ready run then advances on resume.
424
453
  const contents=prepareRules(f,1);
425
- const fixed=f.drive(f.plan('T-002','resume',permissions),'advance');
454
+ const fixed=f.drive(f.plan('T-002','resume',permissions),'start');
426
455
  assert.equal(fixed.status,0,fixed.stderr);assert.equal(result(fixed).state,'awaiting_review',fixed.stdout);
427
456
  assert.match(fixed.stderr,/\[drive init_verify verify /);
428
457
  for(const file of f.targets)assert.equal(read(f,file),contents[file],file);
@@ -436,7 +465,7 @@ test('rules written by this run survive a failed task check: fix the environment
436
465
  // The task check depends on an environment marker outside the code root.
437
466
  const checks=[{id:'environment',command:['/bin/sh','-c','test -f ../environment.ready']}];
438
467
  const contents=prepareRules(f,1);
439
- let run=f.drive(f.plan('T-002','create',permissions,{checks}),'advance');
468
+ let run=f.drive(f.plan('T-002','create',permissions,{checks}),'start');
440
469
  assert.equal(run.status,0,run.stderr);
441
470
  assert.equal(result(run).state,'blocked',run.stdout);assert.equal(result(run).code,'develop_checks_not_passed');
442
471
  assert.equal(result(run).pendingAction,'resume');
@@ -444,24 +473,24 @@ test('rules written by this run survive a failed task check: fix the environment
444
473
  // Rules edited by someone else after this run wrote them are refused before launch.
445
474
  const state=path.join(f.store('T-002'),'state.json'),before=fs.readFileSync(state);
446
475
  fs.appendFileSync(path.join(f.codeProject,'.claude/rules/security.md'),'foreign edit\n');
447
- run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
476
+ run=f.drive(f.plan('T-002','resume',permissions,{checks}),'start');
448
477
  assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/\.claude\/rules\/security\.md 与本运行已记录的写入不一致/);
449
478
  assert.deepEqual(fs.readFileSync(state),before);
450
479
  fs.writeFileSync(path.join(f.codeProject,'.claude/rules/security.md'),contents['.claude/rules/security.md']);
451
480
  // The rules effect only enters the admitted next task (host-bootstrap.mjs run()).
452
481
  const tasks=path.join(f.specsDir,f.feature,'tasks.md'),taskList=fs.readFileSync(tasks,'utf8');
453
482
  fs.writeFileSync(tasks,taskList.replace('[ ] T-002','[x] T-002'));
454
- run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
483
+ run=f.drive(f.plan('T-002','resume',permissions,{checks}),'start');
455
484
  assert.equal(run.status,2,run.stderr);
456
485
  assert.match(run.stderr,/T-002 不是当前可进入的 bootstrap 任务(nextTask 无,宿主以 bootstrap_task_required 拒绝);驾驶员不运行 init-verify 命令/);
457
486
  assert.deepEqual(fs.readFileSync(state),before);
458
487
  fs.writeFileSync(tasks,taskList);
459
488
  fs.writeFileSync(path.join(f.root,'environment.ready'),'ok\n');
460
- run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
489
+ run=f.drive(f.plan('T-002','resume',permissions,{checks}),'start');
461
490
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
462
491
  assert.equal(result(run).identity.attempt,1);
463
492
  for(const file of f.targets)assert.equal(read(f,file),contents[file],file);
464
- run=f.drive(f.plan('T-002','resume',[...permissions,'--allow-review-attempt','1'],{checks,packageDigest:result(run).packageDigest}),'decision');
493
+ run=f.drive(f.plan('T-002','resume',[...permissions],{checks,packageDigest:result(run).packageDigest}),'decision');
465
494
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'approved',run.stdout);
466
495
  run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
467
496
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'fixture_completed',run.stdout);
@@ -38,7 +38,7 @@ import path from 'node:path';
38
38
  import {createHash} from 'node:crypto';
39
39
  import {fileURLToPath} from 'node:url';
40
40
  import {createHostCheck,reportHostCheckProgress} from '../runtime/js/cm-ai/host-check.mjs';
41
- import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
41
+ import {readQaAssessment} from '../runtime/js/cm-ai/host-qa-policy.mjs';
42
42
  import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
43
43
  import {inspectCmAiQaTaskContext} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
44
44
  import {readLearningRetrospectiveContent} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
@@ -61,6 +61,7 @@ import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry
61
61
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
62
62
  import {attemptAnswerName,inspectDriverBootstrap,readBootstrapRulesAnswers,createBootstrapRulesResponder} from '../runtime/js/cm-ai/drive-bootstrap.mjs';
63
63
  import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
64
+ import {readControlPolicyFile,isControlRecovery as controlRecoveryRequest} from '../runtime/js/cm-ai/control-policy.mjs';
64
65
 
65
66
  // PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
66
67
  const HOST=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
@@ -86,7 +87,7 @@ const FIX_REASONED=['abandon_step','abandon_review','rediagnose','rerun_blocked_
86
87
  const FILES={develop:'develop.json',qa_assess:'qa-assess.json',documentation_inspect:'documentation-inspect.json',
87
88
  documentation_sync:'documentation-sync.json',fix_learning:'learning.json',fix_diagnose:'diagnosis.json',
88
89
  fix_test_author:'test-edits.json',fix_repair:'repair-edits.json',fix_retrospective:'retrospective.json'};
89
- const PAIR_FLAGS=new Set(['--external-models-config','--allow-review-attempt','--review-config','--workflow-config',
90
+ const PAIR_FLAGS=new Set(['--external-models-config','--review-config','--workflow-config',
90
91
  '--input-limit',
91
92
  '--protected-conversation-config','--protected-config','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure',
92
93
  '--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--browser-qa',
@@ -100,6 +101,47 @@ const FLAG_FLAGS=new Set(['--execution-optimizations','--external-models','--all
100
101
  'test-author','repair','cause-review','final-review','rediagnosis','rerun-blocked-step','final-review-recovery'].map(name=>`--allow-qa-fix-${name}`)]);
101
102
  const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
102
103
  const nonempty=value=>typeof value==='string'&&value.trim().length>0;
104
+ // V2 control is explicit configuration. Never derive a fresh recovery target
105
+ // from the journal or status here: the caller must carry its earlier preview.
106
+ export function readDriverControl(plan,base,operation,recovery=null){
107
+ if(!Object.hasOwn(plan,'controlConfig'))return null;
108
+ if(!nonempty(plan.controlConfig)||path.isAbsolute(plan.controlConfig))
109
+ throw Error('PLAN.controlConfig 必须是相对 PLAN 的配置文件路径');
110
+ if(!Array.isArray(plan.permissions)||plan.permissions.some(flag=>typeof flag!=='string'))
111
+ throw Error('permissions 必须是宿主参数数组');
112
+ if(plan.permissions.some(flag=>flag.startsWith('--allow-')))
113
+ throw Error('control v2 迁移错误:permissions 禁止 --allow-*;请改用 controlConfig 的明确模式和 expectedControl');
114
+ const recovering=recovery??isControlRecovery(operation,plan);
115
+ if(plan.mode==='create'&&Object.hasOwn(plan,'expectedControl'))
116
+ throw Error('control v2 create 禁止 expectedControl');
117
+ if(!recovering&&Object.hasOwn(plan,'expectedControl'))
118
+ throw Error('control v2 expectedControl 只用于显式恢复操作');
119
+ if(recovering&&(plan.mode!=='resume'||!object(plan.expectedControl)))
120
+ throw Error('control v2 恢复需要 PLAN.expectedControl;请携带此前 status 返回的 controlTarget');
121
+ const file=path.resolve(base,plan.controlConfig);
122
+ const policy=readControlPolicyFile(file);
123
+ if((policy.development==='provider')!==plan.permissions.includes('--protected-config'))
124
+ throw Error('invalid_arguments: development provider 需要 --protected-config;conversation 禁止 provider 配置');
125
+ if(policy.bootstrap==='disabled'&&plan.permissions.includes('--bootstrap-config'))
126
+ throw Error('invalid_arguments: bootstrap disabled 禁止 --bootstrap-config;未读取该配置');
127
+ if(policy.qaFix==='disabled'&&['--qa-fix-owner-config','--qa-fix-template-config'].some(flag=>plan.permissions.includes(flag)))
128
+ throw Error('invalid_arguments: qaFix disabled 禁止 QA Fix 配置;未读取该配置');
129
+ return {file,policy};
130
+ }
131
+ export const isControlRecovery=(operation,plan)=>controlRecoveryRequest({operation,fixOperation:plan.fixOperation});
132
+ export function controlDevelopAttempts(status,operation){
133
+ const {state,attempt,reviewPackage}=status;
134
+ const reviewAfterDevelop=operation==='advance'&&attempt===1;
135
+ if(state==='blocked'&&(RECHECK_CODES.includes(status.code)||DOCUMENTATION_SYNC_CODES.includes(status.code)))
136
+ return {attempts:reviewAfterDevelop?[2]:[],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
137
+ if(developmentRetryable(status))
138
+ return {attempts:reviewAfterDevelop?[1,2]:[attempt],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
139
+ if(state==='ready')return {attempts:reviewAfterDevelop?[1,2]:[attempt],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
140
+ if(state==='changes_requested')return {attempts:[attempt],reviewFirst:false,packageDigest:null};
141
+ if(operation==='advance'&&['awaiting_review','pending_review'].includes(state)&&attempt<2)
142
+ return {attempts:[attempt+1],reviewFirst:true,reviewAfterDevelop:true,holdable:true,packageDigest:reviewPackage?.packageDigest??null};
143
+ return {attempts:[],reviewFirst:false,packageDigest:null};
144
+ }
103
145
  // Needs the resolved --bootstrap-config path in permissions.
104
146
  export const bootstrapDriverGap=(operation,definition,permissions)=>
105
147
  inspectDriverBootstrap({advance:ADVANCE.has(operation),definition,permissions}).gap;
@@ -428,41 +470,23 @@ export function readRunJournal(definition){
428
470
  return {history:readRunnerHistory(snapshot.records,first.payload.config,3),config:first.payload.config,baseline:first.payload.baseline,
429
471
  frame:journalRestBytes(snapshot.records)};
430
472
  }
431
- function reachableDevelopAttempts({plan,operation,journal,permissions}){
473
+ function reachableDevelopAttempts({plan,operation,journal,permissions,controlPolicy=null}){
432
474
  if(plan.mode==='create'){
433
- const reviewAfterDevelop=operation==='advance'
434
- &&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1');
435
- return {attempts:reviewAfterDevelop?[1,2]:[1],reviewFirst:false,reviewAfterDevelop,packageDigest:null,learning:null};
475
+ const reviewAfterDevelop=operation==='advance';
476
+ return {attempts:reviewAfterDevelop?[1,2]:[1],reviewFirst:false,reviewAfterDevelop,
477
+ holdable:true,packageDigest:null,learning:null};
436
478
  }
437
479
  if(journal.error)stop(2,`无法只读检查恢复存档: ${journal.error.code??journal.error.message}`);
438
480
  // learning is the journal's Learning result the next develop effect starts from
439
481
  // (bootstrap rules bind their on-disk files to its recorded evidence).
440
482
  // Q28: decide from what the host will show (projected answer-gap blocks), not the raw replay state.
441
- return {...projectDevelopAttempts(projectedRunnerStatus(journal.history,journal.config),operation,permissions),
483
+ const status=projectedRunnerStatus(journal.history,journal.config);
484
+ return {...(controlPolicy?controlDevelopAttempts(status,operation):projectDevelopAttempts(status,operation,permissions)),
442
485
  learning:journal.history.state.learningResult??null};
443
486
  }
444
- export function projectDevelopAttempts(status,operation,permissions){
445
- const {state,attempt,reviewPackage}=status;
446
- // One advance can continue past the round-1 review into round 2 when it holds
447
- // --allow-review-attempt 1 (Codex round 1 on Q28): preflight that round too.
448
- const reviewAfterDevelop=operation==='advance'&&attempt===1
449
- &&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1');
450
- // A re-check (check_answer_*) re-runs only the checks: no developer answer for
451
- // this round, only for the round its review may lead to.
452
- // Q16/Q17: a documentation-only redo reuses the journaled developer answer.
453
- if(state==='blocked'&&(RECHECK_CODES.includes(status.code)||DOCUMENTATION_SYNC_CODES.includes(status.code)))
454
- return {attempts:reviewAfterDevelop?[2]:[],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
455
- if(developmentRetryable(status))
456
- return {attempts:reviewAfterDevelop?[1,2]:[attempt],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
457
- if(state==='ready'&&attempt===1&&operation==='advance'
458
- &&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1'))
459
- return {attempts:[1,2],reviewFirst:false,reviewAfterDevelop:true,packageDigest:null};
460
- if(['ready','changes_requested'].includes(state))return {attempts:[attempt],reviewFirst:false,packageDigest:null};
461
- if(operation==='advance'&&['awaiting_review','pending_review'].includes(state)
462
- &&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&Number(permissions[index+1])===attempt)
463
- &&attempt<2)return {attempts:[attempt+1],reviewFirst:true,
464
- packageDigest:reviewPackage?.packageDigest??null};
465
- return {attempts:[],reviewFirst:false,packageDigest:null};
487
+ export function projectDevelopAttempts(status,operation){
488
+ // Review dispatch is direct; both attempts follow the same reachable-state rules.
489
+ return controlDevelopAttempts(status,operation);
466
490
  }
467
491
  function predictedQaAsks(definition,qa){
468
492
  // Reuse the executor's validated initial plan for policy applicability.
@@ -523,7 +547,7 @@ export function validateCmAiAnswer(kind,value,root){
523
547
  try{developEntries(value.edits,root,'develop.json.edits');}catch(error){stop(2,`答案格式错误:${error.message}`);}
524
548
  }else {exact(value,['status','code'],'develop.json');requireShape(nonempty(value.code),'develop.json.code');}
525
549
  }else if(kind==='qa_assess'){
526
- try{decideHostQaPolicy({assessment:value,pending:1,mergeEligible:false,unassessedTasks:1});}
550
+ try{readQaAssessment(value);}
527
551
  catch{stop(2,'答案格式错误:qa-assess.json');}
528
552
  }else if(kind==='documentation_inspect'){
529
553
  exact(value,['status','reason','at','closeout'],'documentation-inspect.json');
@@ -560,7 +584,8 @@ export function validateCmAiAnswer(kind,value,root){
560
584
  }
561
585
  function load(){
562
586
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
563
- process.stdout.write('用法: cm-ai-drive.mjs --plan PLAN.json <operation>\nPLAN: config, mode, hostContext, originalHostContext (换会话 resume 必填), runtime, permissions, answers, checks, checkTimeoutMs。\nchecks 每项为 {id,command,timeoutMs?};checkTimeoutMs 与每项 timeoutMs 为 1..3600000 整数,默认 900000 ms(15 分钟)。\nabandon_review 需要 mode:resume、permissions:["--allow-abandon-review"] 与 PLAN.reason;abandon_effect 需要 mode:resume、permissions:["--allow-abandon-effect"] 与 PLAN.reason(均为单行、最多 500 UTF-8 字节)。develop_redo 需要 mode:resume、permissions:["--allow-develop-redo"] 与 PLAN.reason,先确认会话已停止修改代码。 bootstrap_review_recover 需要 mode:resume、permissions:["--allow-bootstrap-review-recovery"] 与 PLAN.reason;只核对原运行的已写规则与 handoff,不需要答案文件。\n人工答案放 answers/;check 只运行 PLAN.checks,不读取静态执行证据。bootstrap T-001 骨架可用;T-002 规范任务(纯规范 scope、单代码根、非 --protected-config)读 answers/init-generate.json({status:"generated",documents:[{path,contentFile}]},覆盖全部 targets)与 answers/init-verify.json(commands 为驾驶员实跑的草稿命令 {id,command,timeoutMs?},可选 commandsNotRun;checks 只含 globs/file_references/constraint_preservation/rule_applicability;constraintChanges:[];application/retrospective 沿原 Learning);第 1 轮也可用 *-a1.json,第 2 轮只读 init-generate-a2.json 与 init-verify-a2.json,且须先 decision 读取首轮 findings,不能带 --allow-review-attempt 跨轮。commands 在宿主接受启动后、发送操作前由驾驶员实跑(须先带 --allow-bootstrap-write 等宿主授权;受保护模式在 specs 沙箱内),失败或改动了预检核对的文件即退出 2 且不发送操作(create 时改用 resume 重跑);结果只来自实跑,答案文件不能提供。\n'
587
+ process.stdout.write('新版 PLAN.controlConfig 为相对 PLAN 的 v2 控制配置路径;development、bootstrap、qa、qaFix 使用明确模式,permissions 禁止所有 --allow-*。普通 advance 自动独立审查;缺少 develop-a2.json 时保持 revision_answer_required。显式恢复需要 resume 与此前 status 返回的 PLAN.expectedControl,驾驶员不会读取新目标覆盖它。\n');
588
+ process.stdout.write('用法: cm-ai-drive.mjs --plan PLAN.json <operation>\nPLAN: config, mode, hostContext, originalHostContext (换会话 resume 必填), runtime, permissions, answers, checks, checkTimeoutMs。\nchecks 每项为 {id,command,timeoutMs?};checkTimeoutMs 与每项 timeoutMs 为 1..3600000 整数,默认 900000 ms(15 分钟)。\nabandon_review 需要 mode:resume、permissions:["--allow-abandon-review"] 与 PLAN.reason;abandon_effect 需要 mode:resume、permissions:["--allow-abandon-effect"] 与 PLAN.reason(均为单行、最多 500 UTF-8 字节)。develop_redo 需要 mode:resume、permissions:["--allow-develop-redo"] 与 PLAN.reason,先确认会话已停止修改代码。 bootstrap_review_recover 需要 mode:resume、permissions:["--allow-bootstrap-review-recovery"] 与 PLAN.reason;只核对原运行的已写规则与 handoff,不需要答案文件。\n人工答案放 answers/;check 只运行 PLAN.checks,不读取静态执行证据。bootstrap T-001 骨架可用;T-002 规范任务(纯规范 scope、单代码根、非 --protected-config)读 answers/init-generate.json({status:"generated",documents:[{path,contentFile}]},覆盖全部 targets)与 answers/init-verify.json(commands 为驾驶员实跑的草稿命令 {id,command,timeoutMs?},可选 commandsNotRun;checks 只含 globs/file_references/constraint_preservation/rule_applicability;constraintChanges:[];application/retrospective 沿原 Learning);第 1 轮也可用 *-a1.json,第 2 轮只读 init-generate-a2.json 与 init-verify-a2.json,审查自动派发;缺少第2轮草稿时先停在 changes_requested,读取首轮 findings 后再写草稿。commands 在宿主接受启动后、发送操作前由驾驶员实跑(须先带 --allow-bootstrap-write 等宿主授权;受保护模式在 specs 沙箱内),失败或改动了预检核对的文件即退出 2 且不发送操作(create 时改用 resume 重跑);结果只来自实跑,答案文件不能提供。\n'
564
589
  +'develop.json.edits 每项是 scope 路径到下列之一:"内容文件"(写入;已有文件保留权限,新文件 0644)、{"file":"内容文件","mode":"0755"|"0644"}、{"mode":"0755"|"0644"}(只改已有文件权限)、{"delete":true}(删除已有文件)。改名 = 删旧路径 + 写新路径,两者都要在 scope 内;同时列在 requirements 里的路径不能删除。\n'
565
590
  +'启动前拒绝:单个 scope 文件超过 1 MiB、审查材料(按审查包快照:scope、requirements 与树中全部 AGENTS.md 正文)合计超过 2 MiB 或超过 256 个文件、交付后与任务基线完全相同(edits 为空或内容和权限都没变)、开发检查点(含 handoff 与 AGENTS.md 回写,按宿主同一套构建代码计)装不进运行存档单条 1 MiB 记录减去为有界审查与完成记录推出的预留,或任务基线装不进一条记录。受保护模式(--protected-conversation-config)只收合法 UTF-8 文本,应答大于 --input-limit(默认 65536)时提示应加的值。\n'
566
591
  +'runId 需 8–128 个字符(运行日志要求),create 前检查。resume 时按存档里的当前轮次发送 identity,第 2 轮的 decision/complete/qa 等无需手改。\n');
@@ -569,6 +594,12 @@ function load(){
569
594
  const loaded=loadPlanFile({name:'cm-ai-drive.mjs',known:OPERATIONS});
570
595
  const {plan,operation,base}=loaded;
571
596
  requireFields(plan,['config','mode','hostContext','permissions']);
597
+ let control;
598
+ try{control=readDriverControl(plan,base,operation);}catch(error){stop(2,error.message);}
599
+ if(control?.policy.bootstrap==='write'&&!plan.permissions.includes('--bootstrap-config'))
600
+ stop(2,'invalid_arguments: bootstrap write 需要 --bootstrap-config');
601
+ if(control?.policy.qaFix==='disabled'&&['fix_advance','fix_run','fix_action'].includes(operation))
602
+ stop(2,'invalid_arguments: qaFix disabled 不执行 QA Fix 操作');
572
603
  if(Object.hasOwn(plan,'verificationPrecheck')&&typeof plan.verificationPrecheck!=='boolean')stop(2,'verificationPrecheck 需要 boolean');
573
604
  try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
574
605
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
@@ -592,13 +623,18 @@ function load(){
592
623
  if(permissions.includes('--rebind-spec-material')!==permissions.includes('--spec-rebind-reason')
593
624
  ||permissions.includes('--rebind-spec-material')&&plan.mode!=='resume')
594
625
  stop(2,'--rebind-spec-material 只用于 mode resume,并须同时提供 --spec-rebind-reason 原因');
595
- const abandonError=abandonReviewPlanError(operation,plan,permissions);
626
+ // V2 recovery operations are gated by the original expectedControl in the
627
+ // host, while the driver still validates the explicit operation and reason.
628
+ if(control&&['abandon_review','abandon_effect','bootstrap_review_recover','develop_redo'].includes(operation)
629
+ &&(plan.mode!=='resume'||!nonempty(plan.reason)||Buffer.byteLength(plan.reason,'utf8')>500||/[\r\n\0]/.test(plan.reason)))
630
+ stop(2,`${operation} 需要 resume、expectedControl 与单行 reason(最多 500 UTF-8 字节)`);
631
+ const abandonError=control?null:abandonReviewPlanError(operation,plan,permissions);
596
632
  if(abandonError)stop(2,abandonError);
597
- const abandonEffectError=abandonEffectPlanError(operation,plan,permissions);
633
+ const abandonEffectError=control?null:abandonEffectPlanError(operation,plan,permissions);
598
634
  if(abandonEffectError)stop(2,abandonEffectError);
599
- const developRedoError=developRedoPlanError(operation,plan,permissions);
635
+ const developRedoError=control?null:developRedoPlanError(operation,plan,permissions);
600
636
  if(developRedoError)stop(2,developRedoError);
601
- const bootstrapRecoveryError=bootstrapReviewRecoveryPlanError(operation,plan,permissions);
637
+ const bootstrapRecoveryError=control?null:bootstrapReviewRecoveryPlanError(operation,plan,permissions);
602
638
  if(bootstrapRecoveryError)stop(2,bootstrapRecoveryError);
603
639
  const config=path.resolve(base,plan.config),answers=plan.answers?path.resolve(base,plan.answers):null;
604
640
  if(!fs.existsSync(config))stop(2,`运行定义不存在: ${config}`);
@@ -631,18 +667,18 @@ function load(){
631
667
  }
632
668
  const permissionFiles=[];
633
669
  for(let i=0;i<permissions.length;i++)if(PAIR_FLAGS.has(permissions[i])
634
- &&permissions[i]!=='--allow-review-attempt'&&permissions[i]!=='--browser-qa'
670
+ &&permissions[i]!=='--browser-qa'
635
671
  &&permissions[i]!=='--qa-config-revision-reason'&&permissions[i]!=='--qa-environment-failure'&&permissions[i]!=='--allow-provider-development-attempt'
636
672
  &&permissions[i]!=='--supersede-reason'&&permissions[i]!=='--spec-rebind-reason'&&permissions[i]!=='--input-limit'
637
673
  &&permissions[i]!=='--review-runtime'&&permissions[i]!=='--feature'&&permissions[i]!=='--qa-fix-final-review-recovery-invocation'){
638
674
  const file=path.resolve(base,permissions[i+1]);if(!fs.existsSync(file))stop(2,`${permissions[i]} 文件不存在: ${file}`);
639
675
  permissions[i+1]=file;permissionFiles.push(file);i++;
640
676
  }
641
- const bootstrap=inspectDriverBootstrap({advance:ADVANCE.has(operation),definition,permissions});
677
+ const bootstrap=inspectDriverBootstrap({advance:ADVANCE.has(operation),definition,permissions,controlPolicy:control?.policy??null});
642
678
  if(bootstrap.gap)stop(2,bootstrap.gap);
643
679
  const rules=bootstrap.mode==='instructions';
644
- const providerMode=permissions.includes('--protected-config');
645
- const protectedMode=providerMode||permissions.includes('--protected-conversation-config');
680
+ const providerMode=control?control.policy.development==='provider':permissions.includes('--protected-config');
681
+ const protectedMode=permissions.includes('--protected-config')||permissions.includes('--protected-conversation-config');
646
682
  const asks=[];
647
683
  if(ADVANCE.has(operation)){
648
684
  // A pure rules scope never reaches develop: host-bootstrap.mjs asks the session instead.
@@ -652,15 +688,15 @@ function load(){
652
688
  }
653
689
  if((plan.verificationPrecheck===true||permissions.includes('--verification-precheck'))&&(ADVANCE.has(operation)||operation==='complete'))asks.push('verification_precheck');
654
690
  if(operation==='complete'&&!protectedMode)asks.push('check');
655
- if((operation==='advance'||operation==='qa')&&workflow?.qa){asks.push('qa_assess');
691
+ if((operation==='advance'||operation==='qa')&&workflow&&(control||workflow.qa)){asks.push('qa_assess');
656
692
  }
657
- if((operation==='advance'||operation==='qa')&&workflow?.qa){
693
+ if((operation==='advance'||operation==='qa')&&workflow?.qa&&(!control||control.policy.qa==='run')){
658
694
  try{asks.push(...predictedQaAsks(definition,workflow.qa));}
659
695
  catch(error){stop(2,`QA 请求预测失败: ${error.code??error.message}`);}
660
696
  }
661
697
  if(operation==='advance'&&workflow?.documentationPaths?.length&&!protectedMode)asks.push('documentation_sync');
662
698
  if(['advance','finish','run_finalize'].includes(operation)&&workflow)asks.push('documentation_inspect');
663
- if(operation==='advance'&&permissions.includes('--auto-qa-fix')){
699
+ if(operation==='advance'&&(control?control.policy.qaFix==='auto':permissions.includes('--auto-qa-fix'))){
664
700
  asks.push(...new Set(Object.values(FIX_ASKS).flat()));
665
701
  }
666
702
  if(['fix_advance','fix_run'].includes(operation))asks.push(...new Set(Object.values(FIX_ASKS).flat()));
@@ -668,7 +704,7 @@ function load(){
668
704
  if(plan.fixOperation==='reconcile_review'&&(plan.mode!=='resume'||!nonempty(plan.invocationId)))stop(2,'fix reconciliation requires resume and original invocationId');
669
705
  if(!FIX_ACTIONS.has(plan.fixOperation))stop(2,'fix_action 需要宿主支持的 fixOperation');
670
706
  const actionFlag=FIX_ACTION_FLAGS[plan.fixOperation];
671
- if(actionFlag&&!permissions.includes(actionFlag))stop(2,`${plan.fixOperation} 需要 ${actionFlag}`);
707
+ if(actionFlag&&!control&&!permissions.includes(actionFlag))stop(2,`${plan.fixOperation} 需要 ${actionFlag}`);
672
708
  if(FIX_REASONED.includes(plan.fixOperation)&&!(nonempty(plan.reason)&&Buffer.byteLength(plan.reason,'utf8')<=1000
673
709
  &&!/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))stop(2,`${plan.fixOperation} 需要单行 reason(最多 1000 UTF-8 字节)`);
674
710
  if(plan.fixOperation==='rediagnose'&&plan.mode!=='resume')stop(2,'rediagnose 需要 mode:resume');
@@ -696,12 +732,16 @@ function load(){
696
732
  }
697
733
  catch(error){stop(2,`PLAN.checks 格式错误: ${error.code??error.message}`);}
698
734
  }
699
- const reachable=(asks.includes('develop')||rules)&&!providerMode
700
- ?reachableDevelopAttempts({plan,operation,journal,permissions})
735
+ let reachable=(asks.includes('develop')||rules)&&!providerMode
736
+ ?reachableDevelopAttempts({plan,operation,journal,permissions,controlPolicy:control?.policy??null})
701
737
  :{attempts:[],reviewFirst:false,packageDigest:null};
738
+ // Rules answers are authored after reading the review findings. V2 can run
739
+ // that review automatically, but it must stop before asking for a new draft.
740
+ const holdBootstrapRevision=Boolean(rules&&reachable.reviewAfterDevelop);
741
+ if(holdBootstrapRevision)reachable={...reachable,attempts:reachable.attempts.filter(attempt=>attempt<2),reviewAfterDevelop:false,reviewFirst:false};
702
742
  const bootstrapAnswers=rules
703
- ?readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable}):null;
704
- const developAnswers=new Map(),deliveries=[];let holdRevision=false;
743
+ ?readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable,controlPolicy:control?.policy??null}):null;
744
+ const developAnswers=new Map(),deliveries=[];let holdRevision=holdBootstrapRevision;
705
745
  if(asks.includes('develop'))for(const attempt of reachable.attempts){
706
746
  const file=answerPath(answers??'',developFilename(answers??'',attempt));
707
747
  if(!answers||!fs.existsSync(file)){
@@ -714,8 +754,6 @@ function load(){
714
754
  stderr(`没有 ${path.basename(file)}:本次 advance 的首轮审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 2 轮开发;读取 ${reviewFile} 的 findings,写 answers/develop-a2.json 后再 advance`);
715
755
  continue;
716
756
  }
717
- if(reachable.reviewAfterDevelop&&attempt===2)
718
- stop(2,`缺少 ${file};本次 advance 带 --allow-review-attempt 1,宿主完成首轮审查后可能直接进入第 2 轮 develop。可选:1) 从 PLAN.permissions 移除 --allow-review-attempt 1,先 advance 到 awaiting_review;再用该运行返回的 packageDigest 执行 decision,读取 ${reviewFile} 的 findings;若要求修改,写 answers/develop-a2.json 后 advance。2) 若有意一次跑完,预先写 answers/develop-a2.json 后重试 advance。develop-a2.json 必须针对首轮 findings 修改;与第 1 轮被要求修改的代码逐字节相同时,第 2 轮停在 blocked/develop_unchanged_after_review,不送审,改好后再 advance。`);
719
757
  if(reachable.reviewFirst)stop(2,`缺少 ${path.basename(file)};请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 .reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}-r${attempt-1}.md 中的 findings,写 answers/develop-a${attempt}.json 后再 advance`);
720
758
  stop(2,`步骤 ${operation} 会反问 develop,但答案文件不存在: ${file}`);
721
759
  }
@@ -740,7 +778,7 @@ function load(){
740
778
  });
741
779
  if(answer.documentation_sync)for(const target of Object.keys(answer.documentation_sync.edits))
742
780
  if(!workflow.documentationPaths.includes(target))stop(2,`documentation-sync.json.edits 越过文档 scope: ${target}`);
743
- return {...loaded,definition,identity,permissions,config,answers,answer,developAnswers,live,executionPolicy,holdRevision,
781
+ return {...loaded,control,definition,identity,permissions,config,answers,answer,developAnswers,live,executionPolicy,holdRevision,
744
782
  bootstrapRules:bootstrapAnswers&&createBootstrapRulesResponder({definition,plan,bootstrap,answers:bootstrapAnswers,
745
783
  // Same execution as the task checks: the host's specs sandbox in protected mode, else the driver's own.
746
784
  specsRoot:protectedMode?definition.specsDir:null,watch:[config,...permissionFiles]})};
@@ -815,7 +853,11 @@ async function answerFor(row,answer,paths,control){
815
853
  return value??null;
816
854
  }
817
855
  export function buildCmAiDriveRequest(operation,plan,definition,identity=definition.identity){
818
- return {version:1,identity,
856
+ // Recovery is bound to the caller's earlier preview, including its attempt.
857
+ // The host compares that whole target before dispatching anything.
858
+ if(Object.hasOwn(plan,'controlConfig')&&isControlRecovery(operation,plan))identity=plan.expectedControl?.identity??identity;
859
+ return {version:Object.hasOwn(plan,'controlConfig')?2:1,identity,
860
+ ...(Object.hasOwn(plan,'controlConfig')&&isControlRecovery(operation,plan)?{expectedControl:plan.expectedControl}:{}),
819
861
  ...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),
820
862
  ...(['abandon_review','abandon_effect','bootstrap_review_recover','develop_redo'].includes(operation)?{reason:plan.reason}:{}),
821
863
  ...(PACKAGE_OPERATIONS.has(operation)?{packageDigest:plan.packageDigest}:{}),
@@ -827,9 +869,9 @@ export function buildCmAiDriveRequest(operation,plan,definition,identity=definit
827
869
  ...(plan.fixOperation==='recover_final_review'?{invocationId:plan.invocationId,reviewPackageDigest:plan.reviewPackageDigest,
828
870
  previousInvocationStopped:plan.previousInvocationStopped}:{})}: {})}: {})};
829
871
  }
830
- export function buildCmAiDriveHostArgs(plan,permissions,config){
872
+ export function buildCmAiDriveHostArgs(plan,permissions,config,controlConfig=null){
831
873
  return ['serve','--config',config,'--mode',plan.mode,'--host-context',plan.hostContext,
832
- '--allow-development',
874
+ ...(Object.hasOwn(plan,'controlConfig')?['--control-config',controlConfig??plan.controlConfig]:['--allow-development']),
833
875
  ...(plan.verificationPrecheck===true&&!permissions.includes('--verification-precheck')?['--verification-precheck']:[]),
834
876
  ...(plan.originalHostContext?['--original-host-context',plan.originalHostContext]:[]),
835
877
  '--runtime',plan.runtime??'codex',...permissions.filter(flag=>flag!=='--allow-development')];
@@ -849,7 +891,7 @@ async function main(){
849
891
  // Rules init_verify commands really run once the host has accepted the launch
850
892
  // (host_ready) and before the operation is sent: a failure never becomes an
851
893
  // unknown develop effect, and the host's own launch validation came first.
852
- driveHost({host:HOST,args:[...buildCmAiDriveHostArgs(plan,permissions,config),...(loaded.holdRevision?['--hold-revision']:[])],cwd:definition.codeProject,operation,request,
894
+ driveHost({host:HOST,args:[...buildCmAiDriveHostArgs(plan,permissions,config,loaded.control?.file),...(loaded.holdRevision?['--hold-revision']:[])],cwd:definition.codeProject,operation,request,
853
895
  answers:answer,paths:{answers:loaded.answers},answerFor,
854
896
  ...(loaded.bootstrapRules?{beforeRequest:()=>loaded.bootstrapRules.prepare(plan.mode)}:{})});
855
897
  }