@aibyzero/cm-workflow 0.16.5 → 0.16.6

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +7 -0
  4. package/README.md +11 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +28 -7
  17. package/docs/js-workflow-control.md +48 -0
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/untested-branches.md +27 -4
  21. package/docs/user-guide.md +23 -8
  22. package/install-codex.sh +28 -11
  23. package/package.json +1 -1
  24. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  25. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  26. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +79 -20
  27. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +1 -4
  28. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  29. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  30. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  31. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  32. package/runtime/js/cm-ai/drive-bootstrap.mjs +20 -10
  33. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  34. package/runtime/js/cm-ai/durable-runner-state.mjs +117 -14
  35. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  36. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  37. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  38. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  39. package/runtime/js/cm-ai/external-models.mjs +52 -0
  40. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  41. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  42. package/runtime/js/cm-ai/host-check.mjs +30 -4
  43. package/runtime/js/cm-ai/host-conversation-execution.mjs +50 -16
  44. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  45. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  46. package/runtime/js/cm-ai/host-qa-executor.mjs +2 -2
  47. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  48. package/runtime/js/cm-ai/host-session.mjs +1 -1
  49. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  50. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  51. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  52. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  53. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  54. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  55. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  56. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  57. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  58. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  59. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  60. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  61. package/runtime/js/cm-ai/review-package.mjs +11 -0
  62. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  63. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  64. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  65. package/runtime/js/cm-ai/task-runner.mjs +171 -25
  66. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  67. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  68. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  69. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  70. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  71. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  72. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  73. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  74. package/runtime/js/cm-fix/execution.mjs +183 -40
  75. package/runtime/js/cm-fix/final-review.mjs +18 -10
  76. package/runtime/js/cm-fix/host-review.mjs +25 -6
  77. package/runtime/js/cm-fix/host.mjs +4 -1
  78. package/runtime/js/cm-fix/layout.mjs +1 -1
  79. package/runtime/js/cm-fix/progress.mjs +4 -0
  80. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  81. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  82. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  83. package/runtime/js/cm-prd/review-time.mjs +29 -0
  84. package/runtime/js/cm-prd/session.mjs +53 -6
  85. package/runtime/js/cm-security/finalize.mjs +32 -0
  86. package/runtime/review.md +5 -0
  87. package/runtime/task-gates.md +6 -0
  88. package/runtime/workflow-config.md +10 -1
  89. package/scripts/cm-ai-batch-drive.mjs +50 -21
  90. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  91. package/scripts/cm-ai-batch-host.mjs +37 -14
  92. package/scripts/cm-ai-batch-run.mjs +71 -27
  93. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  94. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  95. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  96. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  97. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  98. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  99. package/scripts/cm-ai-drive.mjs +59 -25
  100. package/scripts/cm-ai-drive.test.mjs +97 -1
  101. package/scripts/cm-ai-host.mjs +64 -24
  102. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  103. package/scripts/cm-ai-progress.test.mjs +521 -0
  104. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  105. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  106. package/scripts/cm-ai-run.mjs +58 -14
  107. package/scripts/cm-ai-run.test.mjs +2 -1
  108. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  109. package/scripts/cm-check-drive.test.mjs +1 -0
  110. package/scripts/cm-check-runtime.sh +11 -0
  111. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  112. package/scripts/cm-claude-probe.test.mjs +1 -1
  113. package/scripts/cm-codex-plugin-metadata.py +83 -0
  114. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  115. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  116. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  117. package/scripts/cm-efficiency-offline.mjs +35 -0
  118. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  119. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  120. package/scripts/cm-efficiency-response.test.mjs +117 -0
  121. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  122. package/scripts/cm-external-batch-host.test.mjs +157 -0
  123. package/scripts/cm-external-fix-host.test.mjs +281 -0
  124. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  125. package/scripts/cm-external-group-models.test.mjs +60 -0
  126. package/scripts/cm-external-model-host.test.mjs +180 -0
  127. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  128. package/scripts/cm-external-models.test.mjs +89 -0
  129. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  130. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  131. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  132. package/scripts/cm-fix-drive.mjs +28 -13
  133. package/scripts/cm-fix-final-review.test.mjs +11 -6
  134. package/scripts/cm-fix-host.mjs +17 -10
  135. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  136. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  137. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  138. package/scripts/cm-host-qa-executor.test.mjs +21 -0
  139. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  140. package/scripts/cm-live-evidence.test.mjs +64 -0
  141. package/scripts/cm-log-event.mjs +8 -2
  142. package/scripts/cm-log-event.py +15 -0
  143. package/scripts/cm-model-setup.mjs +79 -0
  144. package/scripts/cm-prd-drive.mjs +32 -11
  145. package/scripts/cm-prd-drive.test.mjs +15 -0
  146. package/scripts/cm-prd-host.mjs +13 -4
  147. package/scripts/cm-release-smoke.sh +5 -1
  148. package/scripts/cm-runtime-i18n.mjs +15 -4
  149. package/scripts/cm-runtime-install.mjs +8 -4
  150. package/scripts/cm-runtime.mjs +116 -23
  151. package/scripts/cm-runtime.test.mjs +121 -12
  152. package/scripts/cm-security.test.mjs +32 -0
  153. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  154. package/scripts/cm-task-gate.mjs +146 -10
  155. package/scripts/cm-task-gate.py +1 -0
  156. package/scripts/cm-test-drive.mjs +10 -4
  157. package/scripts/cm-test-drive.test.mjs +14 -1
  158. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  159. package/scripts/cm-usage-report.py +22 -3
  160. package/scripts/cm-workflow-config.mjs +10 -1
  161. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  162. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  163. package/scripts/fixtures/process-cleanup.mjs +3 -1
  164. package/scripts/test-cm-native-usage.py +62 -0
  165. package/scripts/test-external-model-setup.py +91 -0
  166. package/scripts/test-model-configuration-write.py +201 -0
  167. package/scripts/test-npm-install.py +10 -1
  168. package/skills/cm-ai/SKILL.md +2 -2
  169. package/skills/cm-ai/references/N8-finish.md +5 -0
  170. package/skills/cm-ai/references/js-host.md +13 -5
  171. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  172. package/skills/cm-fix/SKILL.md +1 -1
  173. package/skills/cm-fix/references/js-host.md +30 -2
  174. package/skills/cm-runtime/SKILL.md +29 -6
  175. package/skills/cm-security/SKILL.md +4 -2
  176. package/skills/cm-security/references/scan-contract.md +1 -0
  177. package/templates/cm-workflow.yml +1 -1
@@ -20,6 +20,7 @@ import {captureReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
20
20
  import {boundReviewText,reviewResultForPaths} from '../runtime/js/cm-ai/review-runner.mjs';
21
21
  import {REVIEW_TEXT_LIMIT,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
22
22
  import {main as fixHostMain} from './cm-fix-host.mjs';
23
+ import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
23
24
 
24
25
  // Log mirrors and runtime declarations stay out of the invoking user's home.
25
26
  const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-gaps-home-'));
@@ -86,6 +87,39 @@ const result=run=>JSON.parse(run.stdout).result;
86
87
  const records=f=>JSON.parse(fs.readFileSync(f.store,'utf8')).records;
87
88
  const lastCheckpoint=f=>records(f).filter(row=>row.payload.type==='effect-checkpoint').at(-1).payload.checkpoint;
88
89
  const noRun=f=>assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution')),false,'preflight must not create a run');
90
+ test('single advance reaches live logic and browser QA only after independent fixture Review',async t=>{
91
+ const f=fixture(t);f.reviewer('approved');f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});f.develop({'target.mjs':'target.mjs'},'develop-a2.json');
92
+ const cases=['logic','browser'].map((kind,index)=>({id:`TC-00${index+1}`,origin:'user',kind,blocking:true,
93
+ acIds:[],taskIds:['T-001'],title:'Fixture observation',preconditions:[],steps:['Observe fixture'],expected:['value is 42'],cleanup:[]}));
94
+ fs.writeFileSync(path.join(f.specsDir,'1.work/test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases}));
95
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
96
+ fs.writeFileSync(path.join(f.root,'workflow.json'),JSON.stringify({documentationPaths:[],applicableAgentFiles:[],qa:{
97
+ commands:[{id:'fixture-check',caseIds:['TC-001'],command:[process.execPath,'-e','0']}],
98
+ environment:{kind:'web',carrier:'browser',target:'fixture',scope:'local'}}}));
99
+ f.write('qa-assess.json',{scores:{scope:2,risk:2,accumulation:2,boundary:2},changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
100
+ f.write('documentation-inspect.json',{status:'completed',reason:'Fixture inspected'});
101
+ const plan=f.plan({permissions:['--allow-review-attempt','1','--workflow-config','workflow.json','--allow-qa','--browser-qa','available'],
102
+ liveEvidence:{directory:'exchange',kinds:['qa_logic','qa_browser'],timeoutMs:1000}});
103
+ const out=await runLiveDriver(DRIVER,plan,'advance',row=>row.kind==='qa_logic'
104
+ ?{verdict:'SUPPORTED',evidence:['Fixture target.mjs exports 42']}
105
+ :{verdict:'BLOCKED',evidence:[],environment:row.payload.environment,cleanup:'not_needed'},{env:f.env});
106
+ assert.equal(out.status,0,out.stderr);assert.deepEqual(out.requests.map(r=>r.kind),['qa_logic','qa_browser']);
107
+ assert.equal(result(out).code,'qa_result_blocked');
108
+ });
109
+ test('single live verification precheck executes after checks and blocks before Review',async t=>{
110
+ const f=fixture(t);f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});
111
+ fs.writeFileSync(path.join(f.specsDir,'1.work/tasks.md'),'- [ ] T-001: fixture\n - 验证: value is 43\n');
112
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
113
+ const plan=f.plan({verificationPrecheck:true,liveEvidence:{directory:'exchange',kinds:['verification_precheck'],timeoutMs:1000}});
114
+ const out=await runLiveDriver(DRIVER,plan,'advance',row=>{
115
+ assert.equal(row.kind,'verification_precheck');
116
+ assert.match(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),/42/);
117
+ return {items:[{requirement:'value is 43',satisfied:false,evidence:'Actual fixture source exports 42'}]};
118
+ },{env:f.env});
119
+ assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
120
+ assert.equal(result(out).code,'verification_precheck_failed');
121
+ assert.equal(result(out).pendingAction,'resume');
122
+ });
89
123
 
90
124
  // ---- #24 run ID length -------------------------------------------------------------------------
91
125
  test('#24 a run ID shorter than 8 characters is refused before the driver launches a host',t=>{
@@ -285,6 +319,74 @@ test('#19 a live empty delivery blocks as a retryable develop_empty_changes and
285
319
  const intents=records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id);
286
320
  assert.deepEqual(intents,['develop-1','develop-1-retry-1']);
287
321
  });
322
+ const oversizedScope=['samples/one.bin','samples/two.bin','samples/three.bin'];
323
+ const writeOversizedScope=`fs.mkdirSync(cwd+'/samples',{recursive:true});for(const file of ${JSON.stringify(oversizedScope)})`
324
+ +`fs.writeFileSync(cwd+'/'+file,Buffer.alloc(750*1024,0x61));`;
325
+ const shrinkOversizedScope=`for(const file of ${JSON.stringify(oversizedScope)})fs.writeFileSync(cwd+'/'+file,'small\\n');`;
326
+ test('#19 a direct live host maps oversized review material to a retryable develop package block',t=>{
327
+ const f=fixture(t,{scope:oversizedScope});
328
+ const blocked=liveSession(f,{mode:'create',act:writeOversizedScope});
329
+ assert.equal(blocked.status,0,blocked.stderr);
330
+ assert.equal(result(blocked).state,'blocked',blocked.stdout);
331
+ assert.equal(result(blocked).code,'develop_package_too_large');
332
+ assert.equal(result(blocked).pendingAction,'resume');
333
+ assert.match(result(blocked).reason,/2097152/);
334
+ const retried=liveSession(f,{mode:'resume',act:shrinkOversizedScope});
335
+ assert.equal(retried.status,0,retried.stderr);
336
+ assert.equal(result(retried).state,'awaiting_review',retried.stdout);
337
+ const intents=records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id);
338
+ assert.deepEqual(intents,['develop-1','develop-1-retry-1']);
339
+ });
340
+ test('#19 a legacy unknown limit checkpoint resumes as a retryable develop package block',t=>{
341
+ const f=fixture(t,{scope:oversizedScope});
342
+ const blocked=liveSession(f,{mode:'create',act:writeOversizedScope});
343
+ assert.equal(blocked.status,0,blocked.stderr);
344
+ assert.equal(result(blocked).code,'develop_package_too_large',blocked.stdout);
345
+ // Reproduce the previous runner's durable checkpoint exactly: the successful
346
+ // developer call and passed checks were retained, but the terminal was unknown.
347
+ const state=JSON.parse(fs.readFileSync(f.store,'utf8'));
348
+ const last=state.records.at(-1);assert.equal(last.payload.type,'effect-checkpoint');
349
+ const legacy=value=>({...value,state:'unknown',code:'limit_exceeded',
350
+ reason:'limit_exceeded: samples/three.bin (material bytes 1536000+768000 > 2097152; scope, requirements and AGENTS.md content count)'});
351
+ const checkpoint=legacy(last.payload.checkpoint);
352
+ checkpoint.cache=checkpoint.cache.map(entry=>entry.effect.id===last.payload.effectId?{...entry,result:legacy(entry.result)}:entry);
353
+ const {digest:old,...body}=last;
354
+ const payload={...last.payload,checkpoint};const record={...body,payload};record.digest=digest({...body,payload});
355
+ const {revision,...rest}=state;rest.records=[...state.records.slice(0,-1),record];
356
+ fs.writeFileSync(f.store,JSON.stringify({...rest,revision:digest(rest)})+'\n');
357
+ const status=f.drive(f.plan({mode:'resume',answers:undefined,checks:undefined}),'status');
358
+ assert.equal(status.status,0,status.stderr);
359
+ assert.equal(result(status).state,'blocked',status.stdout);
360
+ assert.equal(result(status).code,'develop_package_too_large');
361
+ assert.equal(result(status).pendingAction,'resume');
362
+ const retried=liveSession(f,{mode:'resume',act:shrinkOversizedScope});
363
+ assert.equal(retried.status,0,retried.stderr);
364
+ assert.equal(result(retried).state,'awaiting_review',retried.stdout);
365
+ });
366
+ test('#19 a generic legacy limit after passed checks is not reclassified as review material',t=>{
367
+ const f=fixture(t,{scope:oversizedScope});
368
+ const blocked=liveSession(f,{mode:'create',act:writeOversizedScope});
369
+ assert.equal(blocked.status,0,blocked.stderr);
370
+ const state=JSON.parse(fs.readFileSync(f.store,'utf8')),last=state.records.at(-1);
371
+ const legacy=value=>({...value,state:'unknown',code:'limit_exceeded',reason:'limit_exceeded'});
372
+ const checkpoint=legacy(last.payload.checkpoint);
373
+ checkpoint.cache=checkpoint.cache.map(entry=>entry.effect.id===last.payload.effectId?{...entry,result:legacy(entry.result)}:entry);
374
+ const {digest:old,...body}=last;
375
+ const payload={...last.payload,checkpoint};const record={...body,payload};record.digest=digest({...body,payload});
376
+ const {revision,...rest}=state;rest.records=[...state.records.slice(0,-1),record];
377
+ fs.writeFileSync(f.store,JSON.stringify({...rest,revision:digest(rest)})+'\n');
378
+ const status=f.drive(f.plan({mode:'resume',answers:undefined,checks:undefined}),'status');
379
+ assert.equal(status.status,1,status.stderr);
380
+ assert.equal(result(status).state,'unknown',status.stdout);
381
+ assert.equal(result(status).code,'limit_exceeded');
382
+ assert.equal(result(status).pendingAction,'reconcile');
383
+ });
384
+ test('#19 legacy review material diagnostics allow parentheses in the reported path',async()=>{
385
+ const {reviewMaterialLimitReason}=await import('../runtime/js/cm-ai/review-package.mjs');
386
+ assert.equal(reviewMaterialLimitReason('limit_exceeded: samples/probe (draft).png '
387
+ +'(material bytes 1536000+768000 > 2097152; scope, requirements and AGENTS.md content count)'),true);
388
+ assert.equal(reviewMaterialLimitReason('limit_exceeded'),false);
389
+ });
288
390
  // Scope and requirements may overlap. A requirement must exist in every review
289
391
  // package, so deleting one is refused before launch (Codex review of 6f005df).
290
392
  test('#11 deleting a scope path that is also a requirement is refused before launch',t=>{
@@ -189,10 +189,10 @@ test('attempt 1 refuses existing instructions the host would not overwrite',t=>{
189
189
  const f=fixture(t,{scaffolded:true});f.writeRun('T-002',[...f.targets]);f.writeBootstrap(selection);prepareRules(f,1);
190
190
  const run=()=>f.drive(f.plan('T-002','create',rulesPermissions),'advance');
191
191
  fs.writeFileSync(path.join(f.codeProject,'AGENTS.md'),'# User-owned rules\n');
192
- assertRefusedBeforeLaunch(f,run(),/规范目标已存在: AGENTS\.md/);
192
+ assertRefusedBeforeLaunch(f,run(),/规范目标 AGENTS\.md 与本运行可信基准不一致/);
193
193
  // A T-001 Learning section is allowed; the draft must keep every other existing line.
194
194
  fs.writeFileSync(path.join(f.codeProject,'AGENTS.md'),'# User-owned rules\n\n## 项目教训\n\n- 保留骨架教训\n');
195
- assertRefusedBeforeLaunch(f,run(),/必须逐字保留当前 AGENTS\.md 中「## 项目教训」段以外的全部内容/);
195
+ assertRefusedBeforeLaunch(f,run(),/必须逐字保留当前「## 项目教训」段/);
196
196
  });
197
197
 
198
198
  test('init-verify commands never run unless the host itself accepted the launch and the task',t=>{
@@ -25,7 +25,7 @@
25
25
  // fix_repair, fix_retrospective; host-qa-fix-owner.mjs
26
26
  // forwards to cm-fix host.run/handle.
27
27
  // fix_action selected cm-fix step; host-qa-fix-owner.mjs fix_action.
28
- // status/cancel/abandon_review/fix_status/context_refresh: none; cm-ai-conversation-entry.mjs
28
+ // status/cancel/abandon_review/abandon_effect/bootstrap_review_recover/fix_status/context_refresh: none; cm-ai-conversation-entry.mjs
29
29
  // status/cancel/context_refresh; host-qa-fix-owner.mjs fix_status.
30
30
  // verification_precheck optional execution.verificationGate in
31
31
  // host-conversation-execution.mjs; CLI has no runner for it.
@@ -33,10 +33,11 @@
33
33
  // intentionally not advertised as cm-ai operations.
34
34
  // For unsupported evidence kinds, preflight refuses before the host starts.
35
35
  import fs from 'node:fs';
36
+ import {readLaunchExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
36
37
  import path from 'node:path';
37
38
  import {createHash} from 'node:crypto';
38
39
  import {fileURLToPath} from 'node:url';
39
- import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
40
+ import {createHostCheck,reportHostCheckProgress} from '../runtime/js/cm-ai/host-check.mjs';
40
41
  import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
41
42
  import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
42
43
  import {inspectCmAiQaTaskContext} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
@@ -54,13 +55,16 @@ import {inspectCmAiTaskLearningInput,createCmAiTaskLearningApplication,
54
55
  import {codeProjectPaths,resolveCodeProjects} from '../runtime/js/cm-ai/code-projects.mjs';
55
56
  import {parseHostInputLimit} from '../runtime/js/cm-ai/host-session.mjs';
56
57
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
58
+ import {readCloseoutReport} from '../runtime/js/cm-ai/knowledge-closeout.mjs';
57
59
  import {readRunnerHistory,attemptBaseline} from '../runtime/js/cm-ai/durable-runner-state.mjs';
58
60
  import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
59
61
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
60
62
  import {attemptAnswerName,inspectDriverBootstrap,readBootstrapRulesAnswers,createBootstrapRulesResponder} from '../runtime/js/cm-ai/drive-bootstrap.mjs';
63
+ import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
61
64
 
65
+ // PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
62
66
  const HOST=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
63
- const OPERATIONS=new Set(['advance','start','resume','status','cancel','abandon_review','abandon_effect','decision','complete','qa','qa_result',
67
+ const OPERATIONS=new Set(['advance','start','resume','status','cancel','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover','decision','complete','qa','qa_result',
64
68
  'fix_status','fix_advance','fix_action','fix_run','run_finalize','context_refresh','finish']);
65
69
  const ADVANCE=new Set(['advance','start','resume']);
66
70
  const PACKAGE_OPERATIONS=new Set(['decision','complete','qa','qa_result','context_refresh','finish','run_finalize']);
@@ -72,17 +76,18 @@ const FIX_ASKS={advance:['fix_learning','fix_diagnose'],author_tests:['fix_learn
72
76
  const FIX_ACTIONS=new Set(['red_test','baseline','author_tests','repair','regression','retrospective',
73
77
  'learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5',
74
78
  'post_review_regression','publish_dossier','walkthrough','finish','prepare_revision',
75
- 'cause_review_package','cause_review','abandon_step','abandon_review']);
79
+ 'cause_review_package','cause_review','reconcile_review','abandon_step','abandon_review']);
76
80
  const FILES={develop:'develop.json',qa_assess:'qa-assess.json',documentation_inspect:'documentation-inspect.json',
77
81
  documentation_sync:'documentation-sync.json',fix_learning:'learning.json',fix_diagnose:'diagnosis.json',
78
82
  fix_test_author:'test-edits.json',fix_repair:'repair-edits.json',fix_retrospective:'retrospective.json'};
79
- const PAIR_FLAGS=new Set(['--allow-review-attempt','--review-config','--workflow-config',
83
+ const PAIR_FLAGS=new Set(['--external-models-config','--allow-review-attempt','--review-config','--workflow-config',
80
84
  '--input-limit',
81
85
  '--protected-conversation-config','--protected-config','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure',
82
86
  '--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--browser-qa',
83
87
  '--bootstrap-config','--allow-provider-development-attempt','--supersede-reason','--spec-rebind-reason']);
84
- const FLAG_FLAGS=new Set(['--allow-development','--allow-qa','--allow-qa-fix-start','--auto-qa-fix',
85
- '--allow-bootstrap-write','--allow-abandon-review','--allow-abandon-effect','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
88
+ const FLAG_FLAGS=new Set(['--execution-optimizations','--external-models','--allow-development','--allow-qa','--allow-qa-fix-start','--auto-qa-fix',
89
+ '--verification-precheck',
90
+ '--allow-bootstrap-write','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
86
91
  '--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material',
87
92
  ...['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon','abandon-review',
88
93
  'test-author','repair','cause-review','final-review'].map(name=>`--allow-qa-fix-${name}`)]);
@@ -101,6 +106,11 @@ export const abandonEffectPlanError=(operation,plan,permissions)=>operation!=='a
101
106
  &&typeof plan.reason==='string'&&plan.reason.trim().length>0
102
107
  &&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)?null:
103
108
  'abandon_effect 需要 resume、--allow-abandon-effect 与单行 reason(最多 500 UTF-8 字节)';
109
+ export const bootstrapReviewRecoveryPlanError=(operation,plan,permissions)=>operation!=='bootstrap_review_recover'?null:
110
+ plan.mode==='resume'&&permissions.includes('--allow-bootstrap-review-recovery')
111
+ &&typeof plan.reason==='string'&&plan.reason.trim().length>0
112
+ &&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)?null:
113
+ 'bootstrap_review_recover 需要 resume、--allow-bootstrap-review-recovery 与单行 reason(最多 500 UTF-8 字节)';
104
114
  function requireShape(ok,label){if(!ok)stop(2,`答案格式错误:${label}`);}
105
115
  function exact(value,allowed,label){requireShape(object(value)&&Object.keys(value).every(key=>allowed.includes(key)),label);}
106
116
  function answerPath(root,file){return path.join(root,file);}
@@ -489,7 +499,9 @@ export function validateCmAiAnswer(kind,value,root){
489
499
  try{decideHostQaPolicy({assessment:value,pending:1,mergeEligible:false,unassessedTasks:1});}
490
500
  catch{stop(2,'答案格式错误:qa-assess.json');}
491
501
  }else if(kind==='documentation_inspect'){
492
- exact(value,['status','reason','at'],'documentation-inspect.json');
502
+ exact(value,['status','reason','at','closeout'],'documentation-inspect.json');
503
+ if(Object.hasOwn(value,'closeout'))try{readCloseoutReport(value.closeout);}
504
+ catch{stop(2,'答案格式错误:documentation-inspect.json.closeout');}
493
505
  requireShape(['completed','blocked'].includes(value.status)&&typeof value.reason==='string'
494
506
  &&value.reason.length<=200&&!/[\r\n\0]/.test(value.reason),'documentation-inspect.json');
495
507
  if(Object.hasOwn(value,'at'))requireShape(typeof value.at==='string'
@@ -521,7 +533,7 @@ export function validateCmAiAnswer(kind,value,root){
521
533
  }
522
534
  function load(){
523
535
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
524
- 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 字节)。\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'
536
+ 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 字节)。 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'
525
537
  +'develop.json.edits 每项是 scope 路径到下列之一:"内容文件"(写入;已有文件保留权限,新文件 0644)、{"file":"内容文件","mode":"0755"|"0644"}、{"mode":"0755"|"0644"}(只改已有文件权限)、{"delete":true}(删除已有文件)。改名 = 删旧路径 + 写新路径,两者都要在 scope 内;同时列在 requirements 里的路径不能删除。\n'
526
538
  +'启动前拒绝:单个 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'
527
539
  +'runId 需 8–128 个字符(运行日志要求),create 前检查。resume 时按存档里的当前轮次发送 identity,第 2 轮的 decision/complete/qa 等无需手改。\n');
@@ -530,6 +542,7 @@ function load(){
530
542
  const loaded=loadPlanFile({name:'cm-ai-drive.mjs',known:OPERATIONS});
531
543
  const {plan,operation,base}=loaded;
532
544
  requireFields(plan,['config','mode','hostContext','permissions']);
545
+ if(Object.hasOwn(plan,'verificationPrecheck')&&typeof plan.verificationPrecheck!=='boolean')stop(2,'verificationPrecheck 需要 boolean');
533
546
  try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
534
547
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
535
548
  if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
@@ -556,6 +569,8 @@ function load(){
556
569
  if(abandonError)stop(2,abandonError);
557
570
  const abandonEffectError=abandonEffectPlanError(operation,plan,permissions);
558
571
  if(abandonEffectError)stop(2,abandonEffectError);
572
+ const bootstrapRecoveryError=bootstrapReviewRecoveryPlanError(operation,plan,permissions);
573
+ if(bootstrapRecoveryError)stop(2,bootstrapRecoveryError);
559
574
  const config=path.resolve(base,plan.config),answers=plan.answers?path.resolve(base,plan.answers):null;
560
575
  if(!fs.existsSync(config))stop(2,`运行定义不存在: ${config}`);
561
576
  let definition;
@@ -596,11 +611,11 @@ function load(){
596
611
  else if(!providerMode)asks.push('develop');
597
612
  if(!protectedMode)asks.push('check');
598
613
  }
599
- if(plan.verificationPrecheck===true&&(ADVANCE.has(operation)||operation==='complete'))asks.push('verification_precheck');
614
+ if((plan.verificationPrecheck===true||permissions.includes('--verification-precheck'))&&(ADVANCE.has(operation)||operation==='complete'))asks.push('verification_precheck');
600
615
  if(operation==='complete'&&!protectedMode)asks.push('check');
601
616
  if((operation==='advance'||operation==='qa')&&workflow?.qa){asks.push('qa_assess');
602
617
  }
603
- if(operation==='advance'&&workflow?.qa){
618
+ if((operation==='advance'||operation==='qa')&&workflow?.qa){
604
619
  try{asks.push(...predictedQaAsks(definition,workflow.qa));}
605
620
  catch(error){stop(2,`QA 请求预测失败: ${error.code??error.message}`);}
606
621
  }
@@ -611,22 +626,29 @@ function load(){
611
626
  }
612
627
  if(['fix_advance','fix_run'].includes(operation))asks.push(...new Set(Object.values(FIX_ASKS).flat()));
613
628
  if(operation==='fix_action'){
629
+ if(plan.fixOperation==='reconcile_review'&&(plan.mode!=='resume'||!nonempty(plan.invocationId)))stop(2,'fix reconciliation requires resume and original invocationId');
614
630
  if(!FIX_ACTIONS.has(plan.fixOperation))stop(2,'fix_action 需要宿主支持的 fixOperation');
615
631
  const abandonFlag=plan.fixOperation==='abandon_review'?'--allow-qa-fix-abandon-review':'--allow-qa-fix-abandon';
616
632
  if(['abandon_step','abandon_review'].includes(plan.fixOperation)&&(!nonempty(plan.reason)
617
633
  ||!permissions.includes(abandonFlag)))stop(2,`${plan.fixOperation} 需要 reason 与 ${abandonFlag}`);
618
634
  asks.push(...(FIX_ASKS[plan.fixOperation]??[]));
619
635
  }
620
- if(['qa_logic','qa_browser','verification_precheck'].some(kind=>asks.includes(kind)))
621
- stop(2,`缺少真实执行 runner: ${asks.filter(kind=>['qa_logic','qa_browser','verification_precheck'].includes(kind)).join(', ')};不能从静态答案文件应答`);
636
+ let live;
637
+ try{live=driverLiveEvidence(plan,{base,protectedRoots:[definition.codeProject,...(definition.codeProjects??[]),definition.specsDir],
638
+ allowedKinds:['qa_logic','qa_browser','verification_precheck'],maxBytes:inputLimitFrom(permissions)});}
639
+ catch(error){stop(2,error.message);}
640
+ const missing=asks.filter(kind=>['qa_logic','qa_browser','verification_precheck'].includes(kind)&&!live.has(kind));
641
+ if(missing.length)stop(2,`缺少真实执行 runner: ${missing.join(', ')};不能从静态答案文件应答`);
642
+ const executionPolicy=readLaunchExecutionPolicy({definition,mode:plan.mode??'create',enabled:permissions.includes('--execution-optimizations')});
622
643
  if(asks.includes('check')){
623
644
  if(!Array.isArray(plan.checks)||plan.checks.length===0)stop(2,'步骤会反问 check,但 PLAN.checks 缺少真实命令列表');
624
645
  try{
625
646
  for(const item of plan.checks){
626
- if(!object(item)||Object.keys(item).some(key=>!['id','command','timeoutMs'].includes(key)))throw Error('PLAN.checks 每项只允许 id、command、timeoutMs');
647
+ if(!object(item)||Object.keys(item).some(key=>!['id','command','timeoutMs',...(executionPolicy?['sameExecutionAs']:[])].includes(key)))throw Error('PLAN.checks 每项只允许 id、command、timeoutMs');
627
648
  planCheckTimeout(plan,item);
628
649
  }
629
- createHostCheck({cwd:definition.codeProject,commands:plan.checks.map(({id,command})=>({id,command}))});
650
+ for(const [index,item] of plan.checks.entries())if(Object.hasOwn(item,'sameExecutionAs')&&planCheckTimeout(plan,item)!==planCheckTimeout(plan,plan.checks[index-1]))throw Error('sameExecutionAs requires the same timeout');
651
+ createHostCheck({cwd:definition.codeProject,reuseDeclared:executionPolicy!==null,commands:plan.checks.map(({timeoutMs,...item})=>item)});
630
652
  }
631
653
  catch(error){stop(2,`PLAN.checks 格式错误: ${error.code??error.message}`);}
632
654
  }
@@ -664,7 +686,7 @@ function load(){
664
686
  });
665
687
  if(answer.documentation_sync)for(const target of Object.keys(answer.documentation_sync.edits))
666
688
  if(!workflow.documentationPaths.includes(target))stop(2,`documentation-sync.json.edits 越过文档 scope: ${target}`);
667
- return {...loaded,definition,identity,permissions,config,answers,answer,developAnswers,
689
+ return {...loaded,definition,identity,permissions,config,answers,answer,developAnswers,live,executionPolicy,
668
690
  bootstrapRules:bootstrapAnswers&&createBootstrapRulesResponder({definition,plan,bootstrap,answers:bootstrapAnswers,
669
691
  // Same execution as the task checks: the host's specs sandbox in protected mode, else the driver's own.
670
692
  specsRoot:protectedMode?definition.specsDir:null,watch:[config,...permissionFiles]})};
@@ -696,20 +718,28 @@ export function qaFixAnswerFor(row,answer,answerRoot){
696
718
  }
697
719
  return value??null;
698
720
  }
699
- async function answerFor(row,answer){
721
+ async function answerFor(row,answer,paths,control){
722
+ if(loaded.live.has(row.kind))return loaded.live.answer(row,control);
700
723
  if(['init_generate','init_verify'].includes(row.kind))return loaded.bootstrapRules?.[row.kind](row)??null;
701
724
  const kind=row.kind,value=kind==='develop'
702
725
  ?loaded.developAnswers.get(row.payload.request?.identity?.attempt??row.payload.identity?.attempt)
703
726
  :answer[kind];
704
727
  if(kind==='check'){
705
728
  const results=[];
729
+ const groups=[];
706
730
  for(const command of loaded.plan.checks){
707
- const run=createHostCheck({cwd:loaded.definition.codeProject,commands:[{id:command.id,command:command.command}],
708
- timeoutMs:planCheckTimeout(loaded.plan,command),
709
- onOutput:({stream,chunk})=>{process.stderr.write(`[drive check ${command.id} ${stream}] ${chunk.toString('utf8')}`);}});
710
- const [item]=await run({identity:row.payload.identity},{signal:new AbortController().signal});
711
- results.push(item);
712
- if(item.outcome!=='passed')break;
731
+ const timeoutMs=planCheckTimeout(loaded.plan,command);
732
+ if(groups.at(-1)?.timeoutMs!==timeoutMs)groups.push({timeoutMs,commands:[]});
733
+ const {timeoutMs:ignored,...item}=command;groups.at(-1).commands.push(item);
734
+ }
735
+ for(const group of groups){
736
+ let currentId=group.commands[0].id;
737
+ const run=createHostCheck({cwd:loaded.definition.codeProject,commands:group.commands,
738
+ reuseDeclared:loaded.executionPolicy!==null,timeoutMs:group.timeoutMs,
739
+ onProgress:event=>{if(event.phase==='start')currentId=event.id;reportHostCheckProgress(event);},
740
+ onOutput:({stream,chunk})=>{process.stderr.write(`[drive check ${currentId} ${stream}] ${chunk.toString('utf8')}`);}});
741
+ const rows=await run({identity:row.payload.identity},control);results.push(...rows);
742
+ if(rows.some(item=>item.outcome!=='passed'))break;
713
743
  }
714
744
  return results;
715
745
  }
@@ -732,23 +762,27 @@ async function answerFor(row,answer){
732
762
  }
733
763
  export function buildCmAiDriveRequest(operation,plan,definition,identity=definition.identity){
734
764
  return {version:1,identity,
735
- ...(['abandon_review','abandon_effect'].includes(operation)?{reason:plan.reason}:{}),
765
+ ...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),
766
+ ...(['abandon_review','abandon_effect','bootstrap_review_recover'].includes(operation)?{reason:plan.reason}:{}),
736
767
  ...(PACKAGE_OPERATIONS.has(operation)?{packageDigest:plan.packageDigest}:{}),
737
768
  ...(TEST_RUN_OPERATIONS.has(operation)?{testRunId:plan.testRunId}:{}),
738
769
  ...(['fix_status','fix_advance','fix_action','fix_run'].includes(operation)?{
739
770
  packageDigest:plan.packageDigest,testRunId:plan.testRunId,
740
- ...(operation==='fix_action'?{fixOperation:plan.fixOperation,
771
+ ...(operation==='fix_action'?{fixOperation:plan.fixOperation,...(plan.fixOperation==='reconcile_review'?{invocationId:plan.invocationId}:{}),
741
772
  ...(['abandon_step','abandon_review'].includes(plan.fixOperation)?{reason:plan.reason}:{})}: {})}: {})};
742
773
  }
743
774
  export function buildCmAiDriveHostArgs(plan,permissions,config){
744
775
  return ['serve','--config',config,'--mode',plan.mode,'--host-context',plan.hostContext,
745
776
  '--allow-development',
777
+ ...(plan.verificationPrecheck===true&&!permissions.includes('--verification-precheck')?['--verification-precheck']:[]),
746
778
  ...(plan.originalHostContext?['--original-host-context',plan.originalHostContext]:[]),
747
779
  '--runtime',plan.runtime??'codex',...permissions.filter(flag=>flag!=='--allow-development')];
748
780
  }
749
781
  async function main(){
750
782
  loaded=load();
751
783
  const {plan,operation,definition,permissions,config,answer}=loaded;
784
+ if(operation==='reconcile_review'&&(plan.mode!=='resume'||!nonempty(plan.invocationId)))
785
+ stop(2,'reconcile_review requires resume and original invocationId');
752
786
  if(PACKAGE_OPERATIONS.has(operation)&&!(typeof plan.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(plan.packageDigest)))
753
787
  stop(2,`${operation} 需要 packageDigest(64 位十六进制)`);
754
788
  if(TEST_RUN_OPERATIONS.has(operation)&&!(operation==='qa_result'?nonempty(plan.testRunId)
@@ -9,7 +9,7 @@ import {buildManifest} from './cm-spec-manifest.mjs';
9
9
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
10
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
11
  import {cmInitRuleTargets} from '../runtime/js/cm-init/draft-generation.mjs';
12
- import {qaFixAnswerFor,projectDevelopAttempts} from './cm-ai-drive.mjs';
12
+ import {qaFixAnswerFor,projectDevelopAttempts,bootstrapReviewRecoveryPlanError,buildCmAiDriveRequest} from './cm-ai-drive.mjs';
13
13
 
14
14
  const DRIVER=fileURLToPath(new URL('./cm-ai-drive.mjs',import.meta.url));
15
15
  const identity={repositoryId:'drive-fixture',runId:'drive-run',taskId:'T-001',attempt:1};
@@ -197,6 +197,69 @@ function qaFixture(f,kinds,caseIds=[]){
197
197
  ...(kinds.some(item=>item.kind==='browser')?['--browser-qa','available']:[])]});
198
198
  }
199
199
 
200
+ for(const mode of ['report','legacy-answer','off'])
201
+ test(`closeout real driver completes the original workflow with ${mode}`,t=>{
202
+ const f=fixture(t);prepared(f);f.write('develop-a2.json',develop);
203
+ const plan=JSON.parse(fs.readFileSync(qaFixture(f,[]),'utf8'));
204
+ fs.unlinkSync(path.join(f.specsDir,'1.work','test-cases.json'));
205
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
206
+ const permissions=changesRequestedReview(f);
207
+ fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),path.join(f.bin,'codex'));
208
+ fs.chmodSync(path.join(f.bin,'codex'),0o700);
209
+ if(mode==='off'){
210
+ const p=path.join(f.root,'workflow.json'),workflow=JSON.parse(fs.readFileSync(p));
211
+ workflow.knowledgeCloseout=false;fs.writeFileSync(p,JSON.stringify(workflow));
212
+ }
213
+ const closeout={version:1,items:['code','runtime','documentation','rules','memory','residue'].map(area=>({area,
214
+ status:area==='memory'?'out_of_scope':'unverified',evidence:[],detail:'Controlled fixture; no semantic or account claim'}))};
215
+ f.write('documentation-inspect.json',{status:'completed',reason:'Controlled required-document fixture',
216
+ ...(mode==='report'?{closeout}:{})});
217
+ plan.permissions=['--workflow-config','workflow.json','--allow-qa',...permissions];
218
+ let result;
219
+ for(let n=0;n<4;n++){
220
+ const out=f.drive(f.plan({...plan,...(n?{mode:'resume',originalHostContext:'drive-host-a'}:{})}),'advance');
221
+ assert.equal(out.status,0,out.stderr);result=JSON.parse(out.stdout).result;
222
+ if(result.state==='run_done')break;
223
+ }
224
+ assert.equal(result.state,'run_done',JSON.stringify(result));
225
+ assert.equal(result.knowledgeCloseout.status,mode==='report'?'reported':mode==='off'?'disabled':'not_completed');
226
+ if(mode==='report')assert.deepEqual(result.knowledgeCloseout.items,closeout.items);
227
+ const state=JSON.parse(fs.readFileSync(f.store)),before=fs.readFileSync(path.join(f.codeProject,'target.mjs'));
228
+ assert.deepEqual(state.records[0].payload.config.knowledgeCloseout,{version:1,enabled:mode!=='off'});
229
+ assert.match(fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'),'utf8'),/- \[x\] T-001/);
230
+ const again=f.drive(f.plan({...plan,mode:'resume',originalHostContext:'drive-host-a'}),'advance');
231
+ assert.equal(again.status,0,again.stderr);assert.equal(JSON.parse(again.stdout).result.deduplicated,true);
232
+ const after=JSON.parse(fs.readFileSync(f.store));
233
+ assert.equal(after.records.filter(row=>row.payload.type==='review-invocation-started').length,1);
234
+ assert.deepEqual(after.records,state.records);assert.deepEqual(fs.readFileSync(path.join(f.codeProject,'target.mjs')),before);
235
+ });
236
+
237
+ test('progress R1: single driver forwards quiet QA command boundaries',t=>{
238
+ const f=fixture(t);prepared(f);f.write('develop-a2.json',develop);
239
+ const plan=JSON.parse(fs.readFileSync(qaFixture(f,[]),'utf8'));
240
+ fs.unlinkSync(path.join(f.specsDir,'1.work','test-cases.json'));
241
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],
242
+ specFiles:buildManifest(f.specsDir)}));
243
+ const permissions=changesRequestedReview(f);
244
+ fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),path.join(f.bin,'codex'));
245
+ fs.chmodSync(path.join(f.bin,'codex'),0o700);
246
+ f.write('qa-assess.json',{scores:{scope:2,risk:2,accumulation:2,boundary:2},
247
+ changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
248
+ const workflowPath=path.join(f.root,'workflow.json'),workflow=JSON.parse(fs.readFileSync(workflowPath,'utf8'));
249
+ workflow.qa.commands=[{id:'quiet-qa',command:[process.execPath,'-e','setTimeout(()=>process.exit(0),400)'],caseIds:[]}];
250
+ fs.writeFileSync(workflowPath,JSON.stringify(workflow));
251
+ plan.permissions=['--workflow-config','workflow.json','--allow-qa',...permissions];
252
+ let result,stderr='';
253
+ for(let n=0;n<4;n++){
254
+ const out=f.drive(f.plan({...plan,...(n?{mode:'resume',originalHostContext:'drive-host-a'}:{})}),'advance');
255
+ assert.equal(out.status,0,out.stderr);stderr+=out.stderr;result=JSON.parse(out.stdout).result;
256
+ if(result.code==='documentation_sync_blocked')break;
257
+ }
258
+ assert.equal(result.code,'documentation_sync_blocked',JSON.stringify(result));
259
+ assert.match(stderr,/开始检查.*quiet-qa/);assert.match(stderr,/检查结束.*quiet-qa.*passed/);
260
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.specsDir,'.cm-status.json'))).state,'qa_passed');
261
+ });
262
+
200
263
  test('create and advance run authored edits and actual check, then resume with original context',t=>{
201
264
  const f=fixture(t);prepared(f);
202
265
  const first=f.drive(f.plan(),'advance');assert.equal(first.status,0,first.stderr);
@@ -291,6 +354,22 @@ test('driver requires resume, flag and one-line reason for abandon_effect before
291
354
  }
292
355
  });
293
356
 
357
+ test('bootstrap review recovery driver requires a bound resume and sends only the reason',t=>{
358
+ const f=fixture(t);
359
+ for(const plan of [
360
+ {mode:'create',permissions:['--allow-bootstrap-review-recovery'],reason:'review package failed'},
361
+ {mode:'resume',permissions:[],reason:'review package failed'},
362
+ {mode:'resume',permissions:['--allow-bootstrap-review-recovery'],reason:'line one\nline two'}]){
363
+ assert.match(bootstrapReviewRecoveryPlanError('bootstrap_review_recover',plan,plan.permissions),/需要 resume/);
364
+ const run=f.drive(f.plan(plan),'bootstrap_review_recover');assert.equal(run.status,2,run.stderr);
365
+ assert.equal(fs.existsSync(f.store),false);
366
+ }
367
+ const plan={mode:'resume',permissions:['--allow-bootstrap-review-recovery'],reason:'Checked bound files and handoff'};
368
+ assert.equal(bootstrapReviewRecoveryPlanError('bootstrap_review_recover',plan,plan.permissions),null);
369
+ assert.deepEqual(buildCmAiDriveRequest('bootstrap_review_recover',plan,{identity}),
370
+ {version:1,identity,reason:plan.reason});
371
+ });
372
+
294
373
  test('missing develop answer is refused before store creation',t=>{
295
374
  const f=fixture(t);const run=f.drive(f.plan(),'advance');
296
375
  assert.equal(run.status,2);assert.match(run.stderr,/develop\.json/);assert.equal(fs.existsSync(f.store),false);
@@ -486,3 +565,20 @@ driveHost({host:${JSON.stringify(host)},args:[],cwd:${JSON.stringify(f.root)},op
486
565
  assert.deepEqual(JSON.parse(run.stdout).result.answer,
487
566
  {contextDigest:'context',status:'no_relevant_lesson',summary:'No applicable lesson'});
488
567
  });
568
+
569
+ test('new policy real driver reuses only declared checks and frozen resume keeps the policy',t=>{
570
+ const f=fixture(t);prepared(f);
571
+ const command=[process.execPath,'-e',"require('node:fs').appendFileSync("+JSON.stringify(path.join(f.root,'execution-count'))+",'x');console.log('tests 1\\npass 1')"];
572
+ const checks=[{id:'tests',command},{id:'ui',command,sameExecutionAs:'tests'}];
573
+ const plan=f.plan({permissions:['--execution-optimizations'],checks});
574
+ const first=f.drive(plan,'advance');assert.equal(first.status,0,first.stderr);assert.equal(JSON.parse(first.stdout).result.state,'awaiting_review',first.stdout+first.stderr);
575
+ assert.equal(fs.readFileSync(path.join(f.root,'execution-count'),'utf8'),'x');
576
+ const before=fs.readFileSync(f.store),snapshot=JSON.parse(before);assert.equal(snapshot.records[0].payload.config.executionPolicy.checkReuse,'declared-adjacent-v1');
577
+ const resume=f.plan({mode:'resume',checks});const status=f.drive(resume,'status');assert.equal(status.status,0,status.stderr);
578
+ assert.equal(fs.readFileSync(path.join(f.root,'execution-count'),'utf8'),'x');assert.deepEqual(fs.readFileSync(f.store),before);
579
+ });
580
+ test('legacy real driver rejects optimization aliases before any host or command starts',t=>{
581
+ const f=fixture(t);prepared(f);const command=[process.execPath,'-e',"require('node:fs').writeFileSync('marker','bad')"];
582
+ const result=f.drive(f.plan({checks:[{id:'one',command},{id:'two',command,sameExecutionAs:'one'}]}),'advance');
583
+ assert.notEqual(result.status,0);assert(!fs.existsSync(f.store));assert(!fs.existsSync(path.join(f.codeProject,'marker')));
584
+ });