@aibyzero/cm-workflow 0.12.0 → 0.13.2

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 (119) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +55 -1
  4. package/README.md +31 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/docs/installation.md +43 -1
  8. package/docs/js-workflow-control.md +63 -6
  9. package/docs/runtime-failover.md +97 -0
  10. package/docs/user-guide.md +37 -1
  11. package/install-codex.sh +5 -0
  12. package/install.ps1 +10 -2
  13. package/install.sh +5 -0
  14. package/package.json +2 -1
  15. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  17. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  20. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  21. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  25. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  26. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  28. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  29. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  31. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  32. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  33. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  34. package/runtime/js/cm-ai/host.mjs +1 -1
  35. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  36. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  37. package/runtime/js/cm-ai/review-package.mjs +76 -18
  38. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  39. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  40. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  41. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  42. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  43. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  44. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  45. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  46. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  47. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  48. package/runtime/js/cm-prd/session.mjs +19 -2
  49. package/runtime/js/cm-prd/summary.mjs +46 -20
  50. package/runtime/review.md +11 -1
  51. package/runtime/workflow-config.md +39 -2
  52. package/runtime/workflow-routing.md +6 -1
  53. package/scripts/cm-ai-admission.test.mjs +99 -0
  54. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  55. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  56. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  57. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  58. package/scripts/cm-ai-host.mjs +81 -12
  59. package/scripts/cm-ai-host.test.mjs +520 -5
  60. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  61. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  62. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  63. package/scripts/cm-ai-run.mjs +40 -13
  64. package/scripts/cm-ai-run.test.mjs +45 -9
  65. package/scripts/cm-check-host.test.mjs +1 -1
  66. package/scripts/cm-check-runtime.sh +51 -1
  67. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  68. package/scripts/cm-claude-probe.test.mjs +64 -1
  69. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  70. package/scripts/cm-claude-worker.test.mjs +110 -1
  71. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  72. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  73. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  74. package/scripts/cm-failover.mjs +288 -0
  75. package/scripts/cm-failover.test.mjs +184 -0
  76. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  77. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  78. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  79. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  80. package/scripts/cm-init-host.mjs +4 -4
  81. package/scripts/cm-init-host.test.mjs +12 -7
  82. package/scripts/cm-init-session.test.mjs +50 -0
  83. package/scripts/cm-log-event.mjs +34 -5
  84. package/scripts/cm-prd-completion.test.mjs +2 -2
  85. package/scripts/cm-prd-host.mjs +39 -3
  86. package/scripts/cm-prd-host.test.mjs +52 -0
  87. package/scripts/cm-prd-review-gate.mjs +11 -2
  88. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  89. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  90. package/scripts/cm-prd-summary.test.mjs +147 -0
  91. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  92. package/scripts/cm-review-inventory.test.mjs +189 -0
  93. package/scripts/cm-review-schema.test.mjs +35 -1
  94. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  95. package/scripts/cm-runtime-edit.mjs +104 -0
  96. package/scripts/cm-runtime-failover.test.mjs +130 -0
  97. package/scripts/cm-runtime-install.mjs +42 -0
  98. package/scripts/cm-runtime.mjs +113 -0
  99. package/scripts/cm-runtime.test.mjs +117 -0
  100. package/scripts/cm-spec-manifest.mjs +24 -21
  101. package/scripts/cm-spec-manifest.test.mjs +19 -0
  102. package/scripts/cm-workflow-config.mjs +113 -5
  103. package/scripts/cm-workflow-config.test.mjs +124 -1
  104. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  105. package/scripts/test-cm-prd-review-gate.py +30 -0
  106. package/scripts/test-shell-compat.sh +34 -0
  107. package/scripts/validate-public-repo.py +5 -0
  108. package/skills/cm-ai/references/N4-review.md +5 -4
  109. package/skills/cm-ai/references/js-host.md +36 -2
  110. package/skills/cm-check/SKILL.md +7 -3
  111. package/skills/cm-init/SKILL.md +4 -0
  112. package/skills/cm-init/references/js-host.md +2 -0
  113. package/skills/cm-init/references/runtime-declaration.md +26 -0
  114. package/skills/cm-prd/SKILL.md +3 -3
  115. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  116. package/skills/cm-prd/references/summary-card.md +7 -0
  117. package/skills/cm-runtime/SKILL.md +32 -0
  118. package/templates/auto-update/cm-update.sh +1 -1
  119. package/templates/cm-workflow.yml +16 -0
@@ -7,6 +7,9 @@ import {fileURLToPath} from 'node:url';
7
7
 
8
8
  export const CONFIG_FILENAMES=Object.freeze(['.cm-workflow.yml','.cm-workflow.yaml','.cm-workflow.json']);
9
9
  export const MAX_CONFIG_BYTES=64*1024;
10
+ // Out-of-band provenance keeps persisted config/role JSON contracts unchanged.
11
+ const RUNTIME_SOURCES=new WeakMap();
12
+ export const runtimesSource=config=>RUNTIME_SOURCES.get(config)??'none';
10
13
 
11
14
  const PROJECT_TYPES=new Set(['auto','java-backend','web-frontend','custom']);
12
15
  const WORKFLOWS=new Set(['cm-default','java-backend','web-frontend']);
@@ -22,6 +25,10 @@ const MODEL_POLICY_ALIASES=Object.freeze({'strict-Pro':'strict-pro'});
22
25
  const AUTO_FIX_POLICIES=new Set(['explicit','never','auto']);
23
26
  const DELIVERY_MODES=new Set(['diff','branch','draft-mr']);
24
27
  const RUNTIMES=new Set(['codex','claude','unknown']);
28
+ // Declared runtime availability. `unknown` is only the default for configs that
29
+ // never declared it; raw configs must pick codex, claude or both.
30
+ const DECLARABLE_RUNTIMES=new Set(['codex','claude','both']);
31
+ const CLI_ADAPTER_RUNTIME=Object.freeze({'codex-cli':'codex','claude-cli':'claude','claude-api':'claude'});
25
32
  const SECRET_KEY=/(?:api[_-]?key|access[_-]?token|secret|cookie|password|private[_-]?key|credential|authorization)/i;
26
33
  const SECRET_VALUE=/(?:-----BEGIN [^-]+ PRIVATE KEY-----|\b(?:AKIA|ASIA)[0-9A-Z]{16}\b|\bAIza[0-9A-Za-z_-]{20,}\b|\bsk[-_](?:ant-api\d{2}[-_])?[A-Za-z0-9_-]{12,}\b|\b(?:ghp|gho|ghu|ghs|ghr|github_pat)[-_][A-Za-z0-9_-]{8,}\b|\bxox[baprs][-_][A-Za-z0-9_-]{8,}\b|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b)/i;
27
34
  const IDENTIFIER=/^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$/;
@@ -33,6 +40,7 @@ export class ConfigError extends Error {
33
40
  const rawDefault={
34
41
  version:1,
35
42
  project:{type:'auto',workflow:'cm-default'},
43
+ runtimes:{available:'unknown'},
36
44
  roles:{
37
45
  analyst:{adapter:'current-ai',model:'default',source:'local'},
38
46
  planner:{adapter:'current-ai',model:'default',source:'local'},
@@ -276,13 +284,17 @@ function requireString(value,location,choices=null){
276
284
  }
277
285
 
278
286
  function validateRaw(value){
279
- const root=requireMapping(value,'config');rejectUnknown(root,new Set(['version','project','roles','policies']),'config');
287
+ const root=requireMapping(value,'config');rejectUnknown(root,new Set(['version','project','runtimes','roles','policies']),'config');
280
288
  if(typeof root.version!=='bigint'||root.version!==1n)throw new ConfigError('config.version must equal integer 1');
281
289
  if(Object.hasOwn(root,'project')){
282
290
  const project=requireMapping(root.project,'config.project');rejectUnknown(project,new Set(['type','workflow']),'config.project');
283
291
  if(Object.hasOwn(project,'type'))requireString(project.type,'config.project.type',PROJECT_TYPES);
284
292
  if(Object.hasOwn(project,'workflow'))requireString(project.workflow,'config.project.workflow',WORKFLOWS);
285
293
  }
294
+ if(Object.hasOwn(root,'runtimes')){
295
+ const runtimes=requireMapping(root.runtimes,'config.runtimes');rejectUnknown(runtimes,new Set(['available']),'config.runtimes');
296
+ if(Object.hasOwn(runtimes,'available'))requireString(runtimes.available,'config.runtimes.available',DECLARABLE_RUNTIMES);
297
+ }
286
298
  if(Object.hasOwn(root,'roles')){
287
299
  const roles=requireMapping(root.roles,'config.roles');rejectUnknown(roles,ROLE_NAMES,'config.roles');
288
300
  for(const [role,rawRole] of Object.entries(roles)){
@@ -330,6 +342,7 @@ function validateEffective(config){
330
342
  requireString(roleData.model_policy,'roles.external_expert.model_policy',MODEL_POLICIES);
331
343
  }
332
344
  }
345
+ validateRuntimeDeclaration(config);
333
346
  if(!Array.isArray(config.policies.tests)||config.policies.tests.length===0)throw new ConfigError('policies.tests must be a non-empty list');
334
347
  if(config.policies.tests.some(item=>typeof item!=='string'||!TEST_KINDS.has(item)))throw new ConfigError('policies.tests contains an unsupported test kind');
335
348
  if(typeof config.policies.generate_cases!=='boolean')throw new ConfigError('policies.generate_cases must be boolean');
@@ -337,6 +350,47 @@ function validateEffective(config){
337
350
  requireString(config.policies.delivery,'policies.delivery',DELIVERY_MODES);
338
351
  }
339
352
 
353
+ // A declared availability only constrains roles that name a concrete runtime.
354
+ // `current-ai` means "whatever tool I am sitting in" and is never judged here,
355
+ // so single-runtime users with default roles stay valid. This validates the
356
+ // declaration; it does not dispatch across runtimes (see workflow-routing.md).
357
+ function validateRuntimeDeclaration(config){
358
+ const available=config.runtimes?.available;
359
+ if(available===undefined||available==='unknown')return;
360
+ requireString(available,'runtimes.available',DECLARABLE_RUNTIMES);
361
+ for(const [role,roleData] of Object.entries(config.roles)){
362
+ const runtime=CLI_ADAPTER_RUNTIME[roleData.adapter];
363
+ if(runtime&&available!=='both'&&runtime!==available)
364
+ throw new ConfigError(`roles.${role}.adapter ${roleData.adapter} needs the ${runtime} runtime, but runtimes.available declares ${available}`);
365
+ }
366
+ const coder=CLI_ADAPTER_RUNTIME[config.roles.coder.adapter],reviewer=CLI_ADAPTER_RUNTIME[config.roles.reviewer.adapter];
367
+ if(available==='both'&&coder&&reviewer&&coder===reviewer)
368
+ throw new ConfigError(`roles.coder and roles.reviewer both resolve to ${coder}; with runtimes.available both, review must run on the other runtime`);
369
+ }
370
+
371
+ // Runtimes a caller may start a role on, derived from the declaration. Unknown
372
+ // declarations permit both so undeclared projects keep today's behavior.
373
+ export function declaredRuntimes(config){
374
+ const available=config?.runtimes?.available??'unknown';
375
+ if(available==='codex'||available==='claude')return Object.freeze({available,allowed:Object.freeze([available])});
376
+ return Object.freeze({available,allowed:Object.freeze(['codex','claude'])});
377
+ }
378
+ export function runtimeForAdapter(adapter){return CLI_ADAPTER_RUNTIME[adapter]??null;}
379
+
380
+ // Pure selection only. The host records cli-dispatch after process creation.
381
+ export function resolveProtectedRuntimes(config,runtime){
382
+ if(!['codex','claude'].includes(runtime))throw new ConfigError('invalid_runtime');
383
+ const declared=declaredRuntimes(config);
384
+ const coderRuntime=runtimeForAdapter(config.roles.coder.adapter)??runtime;
385
+ const reviewerRuntime=runtimeForAdapter(config.roles.reviewer.adapter)
386
+ ??(declared.allowed.length===1?declared.allowed[0]:coderRuntime==='codex'?'claude':'codex');
387
+ if(!declared.allowed.includes(coderRuntime)||!declared.allowed.includes(reviewerRuntime))
388
+ throw new ConfigError('runtime_not_declared');
389
+ if(declared.available==='both'&&coderRuntime===reviewerRuntime)
390
+ throw new ConfigError('cross_runtime_review_required');
391
+ return {coderRuntime,reviewerRuntime};
392
+ }
393
+
340
394
  function expandUser(raw){
341
395
  if(raw==='~')return os.homedir();
342
396
  if(raw.startsWith(`~${path.sep}`))return path.join(os.homedir(),raw.slice(2));
@@ -356,13 +410,62 @@ export function findConfig(projectRoot){
356
410
  return candidates[0]??null;
357
411
  }
358
412
 
413
+ // One preset contract for installers, the runtime tool and user defaults.
414
+ export const RUNTIME_PRESETS=deepFreeze({
415
+ 'codex-only':{available:'codex',coder:'codex-cli',reviewer:'codex-cli'},
416
+ 'claude-only':{available:'claude',coder:'claude-cli',reviewer:'claude-cli'},
417
+ 'codex-codes':{available:'both',coder:'codex-cli',reviewer:'claude-cli'},
418
+ 'claude-codes':{available:'both',coder:'claude-cli',reviewer:'codex-cli'},
419
+ });
420
+ export function runtimePreset(preset){
421
+ if(!Object.hasOwn(RUNTIME_PRESETS,preset))throw new ConfigError('preset must be one of: '+Object.keys(RUNTIME_PRESETS).join(', '));
422
+ const value=RUNTIME_PRESETS[preset];
423
+ return {runtimes:{available:value.available},roles:{
424
+ coder:{adapter:value.coder,source:'subscription'},reviewer:{adapter:value.reviewer,source:'subscription'},
425
+ }};
426
+ }
427
+ export function userRuntimesPath(){
428
+ return path.join(path.resolve(expandUser(process.env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'))),'runtimes.yml');
429
+ }
430
+ export function readConfigText(file){
431
+ try{
432
+ const stat=fs.statSync(file);
433
+ if(!stat.isFile())throw new ConfigError('configuration must be a regular file');
434
+ if(stat.size>MAX_CONFIG_BYTES)throw new ConfigError(`configuration exceeds ${MAX_CONFIG_BYTES} bytes`);
435
+ return new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(fs.readFileSync(file));
436
+ }catch(error){throw new ConfigError(`${file}: ${error.message}`);}
437
+ }
438
+ export function parseUserRuntimes(text){
439
+ try{
440
+ if(Buffer.byteLength(text)>MAX_CONFIG_BYTES)throw new ConfigError('file exceeds configuration size limit');
441
+ if(SECRET_VALUE.test(text))throw new ConfigError('secret-like value is forbidden');
442
+ const raw=requireMapping(parseDocument('runtimes.yml',text),'user');
443
+ walkForSecrets(raw,'user');rejectUnknown(raw,new Set(['runtimes','preset']),'user');
444
+ const runtimes=requireMapping(raw.runtimes,'user.runtimes');
445
+ rejectUnknown(runtimes,new Set(['available']),'user.runtimes');
446
+ requireString(runtimes.available,'user.runtimes.available',DECLARABLE_RUNTIMES);
447
+ requireString(raw.preset,'user.preset',new Set(Object.keys(RUNTIME_PRESETS)));
448
+ if(runtimePreset(raw.preset).runtimes.available!==runtimes.available)
449
+ throw new ConfigError('user.runtimes.available conflicts with user.preset');
450
+ return raw;
451
+ }catch(error){throw new ConfigError(`runtimes.yml: ${error.message}`);}
452
+ }
453
+ export function loadUserRuntimes(){
454
+ const file=userRuntimesPath();
455
+ try{fs.lstatSync(file);}catch(error){
456
+ if(error.code==='ENOENT'||error.code==='ENOTDIR')return null;
457
+ throw new ConfigError(`user.runtimes: ${error.message}`);
458
+ }
459
+ return parseUserRuntimes(readConfigText(file));
460
+ }
461
+
359
462
  export function loadConfig(input){
360
463
  if(!object(input)||!Object.hasOwn(input,'projectRoot')
361
464
  ||Object.keys(input).some(key=>!['projectRoot','configPath','text'].includes(key)))throw new ConfigError('invalid config input');
362
465
  const root=realDirectory(input.projectRoot,'project root');
363
466
  let configPath=Object.hasOwn(input,'configPath')?path.resolve(expandUser(input.configPath)):findConfig(root);
364
467
  let text=Object.hasOwn(input,'text')?input.text:null;
365
- if(text===null&&configPath===null)return clone(DEFAULT_CONFIG);
468
+ if(text===null&&configPath===null){text='version: 1';configPath='.cm-workflow.yml';}
366
469
  if(text===null){
367
470
  try{
368
471
  const stat=fs.statSync(configPath);if(!stat.isFile())throw new Error('not-file');
@@ -371,13 +474,18 @@ export function loadConfig(input){
371
474
  }catch(error){if(error instanceof ConfigError)throw error;throw new ConfigError(`cannot read configuration ${configPath}: ${error.message}`);}
372
475
  }else{
373
476
  if(typeof text!=='string')throw new ConfigError('configuration text must be a string');
477
+ if(Buffer.byteLength(text)>MAX_CONFIG_BYTES)throw new ConfigError(`configuration text exceeds ${MAX_CONFIG_BYTES} bytes`);
374
478
  configPath??='.cm-workflow.yml';
375
479
  }
376
480
  if(SECRET_VALUE.test(text))throw new ConfigError('configuration contains a secret-like value');
377
481
  try{
378
482
  const raw=parseDocument(configPath,text);walkForSecrets(raw);validateRaw(raw);
379
483
  const normalizedRaw={...raw,version:Number(raw.version)};
380
- const effective=deepMerge(DEFAULT_CONFIG,normalizedRaw),policy=effective.roles.external_expert.model_policy;
484
+ const projectDeclared=raw.runtimes?.available!==undefined;
485
+ const user=projectDeclared?null:loadUserRuntimes();
486
+ const defaults=user?deepMerge(DEFAULT_CONFIG,runtimePreset(user.preset)):DEFAULT_CONFIG;
487
+ const effective=deepMerge(defaults,normalizedRaw),policy=effective.roles.external_expert.model_policy;
488
+ RUNTIME_SOURCES.set(effective,projectDeclared?'project':user?'user':'none');
381
489
  if(Object.hasOwn(MODEL_POLICY_ALIASES,policy))effective.roles.external_expert.model_policy=MODEL_POLICY_ALIASES[policy];
382
490
  validateEffective(effective);return effective;
383
491
  }catch(error){if(error instanceof ConfigError)throw error;if(error instanceof RangeError)throw new ConfigError('configuration nesting is too deep');throw error;}
@@ -449,9 +557,9 @@ export function main(argv=process.argv.slice(2)){
449
557
  catch(error){process.stderr.write(`FAIL: ${error.message}\n`);return 1;}
450
558
  if(args.printRole&&!args.role){process.stderr.write('FAIL: --print-role requires --role\n');return 2;}
451
559
  if(args.role){
452
- const role=resolveRole(config,args.role,args.runtime),body=stableJson(role);
560
+ const role=resolveRole(config,args.role,args.runtime),body=stableJson({...role,runtimes_source:runtimesSource(config)});
453
561
  process.stdout.write(args.printRole?`${body}\n`:`workflow role: ${body}\n`);
454
- }else if(args.printEffective)process.stdout.write(`${stableJson(config)}\n`);
562
+ }else if(args.printEffective)process.stdout.write(`${stableJson({...config,runtimes_source:runtimesSource(config)})}\n`);
455
563
  else process.stdout.write('workflow config: PASSED\n');
456
564
  return 0;
457
565
  }
@@ -38,7 +38,12 @@ policies:
38
38
 
39
39
  const fixture=async fn=>{
40
40
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-workflow-config-js-')));
41
- try{return await fn(root);}finally{fs.rmSync(root,{recursive:true,force:true});}
41
+ const old=process.env.CM_WORKFLOW_HOME;
42
+ process.env.CM_WORKFLOW_HOME=path.join(root,'user');
43
+ try{return await fn(root);}finally{
44
+ if(old===undefined)delete process.env.CM_WORKFLOW_HOME;else process.env.CM_WORKFLOW_HOME=old;
45
+ fs.rmSync(root,{recursive:true,force:true});
46
+ }
42
47
  };
43
48
 
44
49
  test('JS config authority preserves defaults, YAML merge, canonical aliases, and route states',()=>fixture(async root=>{
@@ -179,3 +184,121 @@ test('frozen Python authority vectors preserve numeric token and equals-form beh
179
184
  assert.equal(emptyProject.status,0);
180
185
  assert.equal(JSON.parse(emptyProject.stdout).version,1);
181
186
  }));
187
+
188
+ // --- runtimes.available 声明 ---
189
+ const withRuntimes=(available,coder,reviewer)=>`version: 1
190
+ runtimes:
191
+ available: ${available}
192
+ roles:
193
+ coder:
194
+ adapter: ${coder}
195
+ model: default
196
+ source: subscription
197
+ reviewer:
198
+ adapter: ${reviewer}
199
+ model: default
200
+ source: subscription`;
201
+
202
+ test('runtimes.available 缺省为 unknown,四个预设都能通过校验',()=>fixture(async root=>{
203
+ const {loadConfig,declaredRuntimes}=await import('./cm-workflow-config.mjs');
204
+ const none=loadConfig({projectRoot:root,text:'version: 1'});
205
+ assert.equal(none.runtimes.available,'unknown');
206
+ assert.deepEqual(declaredRuntimes(none),{available:'unknown',allowed:['codex','claude']});
207
+ for(const [available,coder,reviewer] of [['codex','codex-cli','codex-cli'],['claude','claude-cli','claude-cli'],
208
+ ['both','codex-cli','claude-cli'],['both','claude-cli','codex-cli']]){
209
+ const config=loadConfig({projectRoot:root,text:withRuntimes(available,coder,reviewer)});
210
+ assert.equal(config.runtimes.available,available);
211
+ assert.equal(config.roles.coder.adapter,coder);
212
+ }
213
+ assert.deepEqual(declaredRuntimes(loadConfig({projectRoot:root,text:withRuntimes('codex','codex-cli','codex-cli')})),
214
+ {available:'codex',allowed:['codex']});
215
+ }));
216
+
217
+ test('声明只有一家时,角色不能指向另一家',()=>fixture(async root=>{
218
+ const {loadConfig}=await import('./cm-workflow-config.mjs');
219
+ assert.throws(()=>loadConfig({projectRoot:root,text:withRuntimes('codex','codex-cli','claude-cli')}),
220
+ /roles\.reviewer\.adapter claude-cli needs the claude runtime, but runtimes\.available declares codex/);
221
+ assert.throws(()=>loadConfig({projectRoot:root,text:withRuntimes('claude','codex-cli','claude-cli')}),
222
+ /roles\.coder\.adapter codex-cli needs the codex runtime/);
223
+ }));
224
+
225
+ test('声明两家都有时,写代码和审代码不能落在同一家',()=>fixture(async root=>{
226
+ const {loadConfig}=await import('./cm-workflow-config.mjs');
227
+ assert.throws(()=>loadConfig({projectRoot:root,text:withRuntimes('both','codex-cli','codex-cli')}),
228
+ /roles\.coder and roles\.reviewer both resolve to codex/);
229
+ // current-ai 表示「我所在的工具」,无法判定归属,不参与该检查。
230
+ assert.doesNotThrow(()=>loadConfig({projectRoot:root,text:withRuntimes('both','codex-cli','current-ai')}));
231
+ assert.doesNotThrow(()=>loadConfig({projectRoot:root,text:'version: 1\nruntimes:\n available: both'}));
232
+ }));
233
+
234
+ test('runtimes 字段只接受 available,取值只接受 codex/claude/both',()=>fixture(async root=>{
235
+ const {loadConfig,runtimeForAdapter}=await import('./cm-workflow-config.mjs');
236
+ assert.throws(()=>loadConfig({projectRoot:root,text:'version: 1\nruntimes:\n available: unknown'}),/must be one of: both, claude, codex/);
237
+ assert.throws(()=>loadConfig({projectRoot:root,text:'version: 1\nruntimes:\n available: gemini'}),/must be one of/);
238
+ assert.throws(()=>loadConfig({projectRoot:root,text:'version: 1\nruntimes:\n preset: codex-codes'}),/config\.runtimes has unknown field\(s\): preset/);
239
+ assert.throws(()=>loadConfig({projectRoot:root,text:'version: 1\nruntimes: both'}),/config\.runtimes must be a mapping/);
240
+ assert.equal(runtimeForAdapter('codex-cli'),'codex');assert.equal(runtimeForAdapter('claude-api'),'claude');
241
+ assert.equal(runtimeForAdapter('current-ai'),null);
242
+ }));
243
+
244
+ test('--print-effective 输出包含 runtimes 声明,CLI 拒绝矛盾配置并给出字段路径',()=>fixture(async root=>{
245
+ fs.writeFileSync(path.join(root,'.cm-workflow.yml'),withRuntimes('both','codex-cli','claude-cli'));
246
+ const ok=spawnSync(process.execPath,[entryPath,'--project',root,'--print-effective'],{encoding:'utf8'});
247
+ assert.equal(ok.status,0,ok.stderr);
248
+ assert.equal(JSON.parse(ok.stdout).runtimes.available,'both');
249
+ fs.writeFileSync(path.join(root,'.cm-workflow.yml'),withRuntimes('codex','codex-cli','claude-cli'));
250
+ const bad=spawnSync(process.execPath,[entryPath,'--project',root],{encoding:'utf8'});
251
+ assert.notEqual(bad.status,0);
252
+ assert.match(bad.stderr+bad.stdout,/roles\.reviewer\.adapter/);
253
+ }));
254
+
255
+ test('protected runtime selection obeys all declarations without claiming process dispatch',async()=>{
256
+ const {loadConfig,resolveRole,resolveProtectedRuntimes}=await import('./cm-workflow-config.mjs');
257
+ for(const [available,coder,reviewer] of [['codex','codex','codex'],['claude','claude','claude'],['both','codex','claude'],['both','claude','codex']]){
258
+ const config=loadConfig({projectRoot:scriptsRoot,configPath:'fixture.json',text:JSON.stringify({version:1,runtimes:{available},
259
+ roles:{coder:{adapter:`${coder}-cli`},reviewer:{adapter:`${reviewer}-cli`}}})});
260
+ for(const runtime of ['codex','claude']){
261
+ assert.deepEqual(resolveProtectedRuntimes(config,runtime),{coderRuntime:coder,reviewerRuntime:reviewer});
262
+ assert.equal(resolveRole(config,'coder',runtime).route_state,coder===runtime?'current-runtime':'declared-adapter');
263
+ }
264
+ }
265
+ // Defense in depth for the late-bound current-ai and unvalidated input cases.
266
+ const config=loadConfig({projectRoot:scriptsRoot,configPath:'fixture.json',text:JSON.stringify({version:1,runtimes:{available:'both'},
267
+ roles:{coder:{adapter:'current-ai'},reviewer:{adapter:'codex-cli'}}})});
268
+ assert.throws(()=>resolveProtectedRuntimes(config,'codex'),/cross_runtime_review_required/);
269
+ assert.deepEqual(resolveProtectedRuntimes(config,'claude'),{coderRuntime:'claude',reviewerRuntime:'codex'});
270
+ config.runtimes.available='claude';
271
+ assert.throws(()=>resolveProtectedRuntimes(config,'claude'),/runtime_not_declared/);
272
+ config.roles.reviewer.adapter='current-ai';
273
+ assert.deepEqual(resolveProtectedRuntimes(config,'claude'),{coderRuntime:'claude',reviewerRuntime:'claude'});
274
+ });
275
+
276
+
277
+ test('user defaults supply preset roles, project fields win, declarations bypass user file',()=>fixture(async root=>{
278
+ const {loadConfig,resolveRole,runtimesSource}=await import('./cm-workflow-config.mjs');
279
+ fs.mkdirSync(process.env.CM_WORKFLOW_HOME);
280
+ const file=path.join(process.env.CM_WORKFLOW_HOME,'runtimes.yml');
281
+ fs.writeFileSync(file,'runtimes: {available: both}\npreset: claude-codes\n');
282
+ const inherited=loadConfig({projectRoot:root});
283
+ assert.equal(runtimesSource(inherited),'user');assert.equal(inherited.runtimes.available,'both');
284
+ assert.equal(inherited.roles.coder.adapter,'claude-cli');assert.equal(inherited.roles.reviewer.adapter,'codex-cli');
285
+ assert.equal(runtimesSource(inherited),'user');
286
+ const partial=loadConfig({projectRoot:root,text:'version: 1\nroles: {coder: {model: custom}}\n'});
287
+ assert.equal(partial.roles.coder.model,'custom');assert.equal(partial.roles.coder.source,'subscription');
288
+ assert.throws(()=>loadConfig({projectRoot:root,text:'version: 1\nroles: {coder: {adapter: codex-cli}}'}),/both resolve to codex/);
289
+ fs.writeFileSync(file,'runtimes: {available: nope}\npreset: invalid\n');
290
+ assert.throws(()=>loadConfig({projectRoot:root}),/user.runtimes.available/);
291
+ const project=loadConfig({projectRoot:root,text:'version: 1\nruntimes: {available: codex}'});
292
+ assert.equal(runtimesSource(project),'project');assert.equal(project.roles.coder.adapter,'current-ai');
293
+ for(const text of ['runtimes: {available: both}\npreset: invalid',
294
+ 'runtimes: {available: codex}\npreset: claude-only','runtimes: {available: both}\npreset: codex-codes\nroles: {}',
295
+ 'preset: codex-only','runtimes: {available: codex}']){
296
+ fs.writeFileSync(file,text);assert.throws(()=>loadConfig({projectRoot:root}),/runtimes.yml:.*user/);
297
+ }
298
+ fs.writeFileSync(file,'runtimes: {available: codex}\npreset: codex-only');
299
+ for(const args of [['--print-effective'],['--role','coder','--print-role']]){
300
+ const result=spawnSync(process.execPath,[entryPath,'--project',root,...args],{encoding:'utf8'});
301
+ assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).runtimes_source,'user');
302
+ }
303
+ fs.unlinkSync(file);assert.equal(runtimesSource(loadConfig({projectRoot:root})),'none');
304
+ }));
@@ -1,4 +1,5 @@
1
- # Test-only frozen pre-migration implementation; never a production fallback.
1
+ # Test-only pre-migration oracle; runtime-mark fallback reuses the manifest oracle.
2
+ # Never a production fallback.
2
3
  #!/usr/bin/env python3
3
4
  """Guard one-attempt PRD review dispatch and crash-safe finding disposition."""
4
5
 
@@ -6,6 +7,7 @@ from __future__ import annotations
6
7
 
7
8
  import argparse
8
9
  import hashlib
10
+ import importlib.util
9
11
  import json
10
12
  import os
11
13
  import re
@@ -16,6 +18,13 @@ from pathlib import Path
16
18
  from typing import Any
17
19
 
18
20
 
21
+ _manifest_spec = importlib.util.spec_from_file_location(
22
+ "prd_manifest_oracle", Path(__file__).with_name("spec-manifest-python-oracle.py")
23
+ )
24
+ _manifest = importlib.util.module_from_spec(_manifest_spec)
25
+ _manifest_spec.loader.exec_module(_manifest)
26
+
27
+
19
28
  FEATURE = re.compile(r"^[^<>:\"/\\|?*\x00-\x1f]+$")
20
29
  SHA256 = re.compile(r"^[0-9a-f]{64}$")
21
30
  STAGES = {"design", "split"}
@@ -208,7 +217,13 @@ def load_receipt(path: Path, *, stage: str, feature: str, evidence: Path) -> dic
208
217
  if not artifact.is_file():
209
218
  raise GateError(f"PRD review artifact is missing or unsafe: {relative}")
210
219
  if digest(artifact) != item["sha256"]:
211
- raise GateError(f"PRD review artifact changed after disposition: {relative}")
220
+ try:
221
+ artifact.read_bytes().decode("utf-8")
222
+ except UnicodeDecodeError as exc:
223
+ raise GateError(f"PRD review artifact changed after disposition: {relative}") from exc
224
+ if artifact.suffix != ".md" or _manifest.file_digest(artifact) != item["sha256"]:
225
+ raise GateError(f"PRD review artifact changed after disposition: {relative}")
226
+ value["runtimeMarksNormalized"] = True
212
227
  return value
213
228
 
214
229
 
@@ -227,6 +242,7 @@ def inspect(args: argparse.Namespace) -> dict[str, Any]:
227
242
  "feature": args.feature,
228
243
  "outcome": "completed",
229
244
  "disposition": value["disposition"],
245
+ **({"runtimeMarksNormalized": True} if value.get("runtimeMarksNormalized") else {}),
230
246
  }
231
247
 
232
248
 
@@ -47,11 +47,41 @@ def invoke(*args: str, expected_exit: int = 0) -> dict[str, object]:
47
47
  return json.loads(result.stdout) if result.stdout.strip() else {"stderr": result.stderr}
48
48
 
49
49
 
50
+ def runtime_mark_fixtures(root: Path) -> None:
51
+ evidence = root / ".reviews" / "prd-marks-split-r1.md"
52
+ receipt = evidence.with_name("prd-marks-split-disposition.json")
53
+ evidence.write_text(
54
+ "---\nat: 2026-09-08T00:00:00Z\nreviewer: codex-subagent\n"
55
+ "independent: true\nscope:\n - tasks.md\n---\nSynthetic review\n", encoding="utf-8"
56
+ )
57
+ originals = {"tasks.md": "- [ ] T-001: Guide\n", "requirements.md": "- [ ] [AC-001] Guide\n",
58
+ "test-cases.json": '{"cases":[]}\n'}
59
+ for name, content in originals.items():
60
+ (root / name).write_text(content, encoding="utf-8")
61
+ flags = ["--stage", "split", "--feature", "marks", "--evidence", str(evidence), "--receipt", str(receipt)]
62
+ artifacts = [value for name in originals for value in ("--artifact", str(root / name))]
63
+ invoke("record", *flags, *artifacts, "--disposition", "no_findings", "--finding-count", "0", "--unresolved-count", "0")
64
+ receipt_bytes = receipt.read_bytes()
65
+ assert "runtimeMarksNormalized" not in invoke("inspect", *flags)
66
+ for mark in ("x", "X"):
67
+ for name in ("tasks.md", "requirements.md"):
68
+ (root / name).write_text(originals[name].replace("[ ]", f"[{mark}]"), encoding="utf-8")
69
+ result = invoke("inspect", *flags)
70
+ assert result["outcome"] == "completed" and result["runtimeMarksNormalized"] is True
71
+ for name in originals:
72
+ saved = (root / name).read_bytes()
73
+ (root / name).write_bytes(saved + b" ")
74
+ assert "changed after disposition" in invoke("inspect", *flags, expected_exit=1)["stderr"]
75
+ (root / name).write_bytes(saved)
76
+ assert receipt.read_bytes() == receipt_bytes
77
+
78
+
50
79
  def main() -> int:
51
80
  with tempfile.TemporaryDirectory(prefix="cm-prd-review-gate-") as raw:
52
81
  root = Path(raw)
53
82
  reviews = root / ".reviews"
54
83
  reviews.mkdir()
84
+ runtime_mark_fixtures(root)
55
85
  artifact = root / "design.md"
56
86
  artifact.write_text("# design v1\n", encoding="utf-8")
57
87
  evidence = reviews / "prd-1.login-design-r1.md"
@@ -6,6 +6,7 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
6
6
  TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cm-shell-compat.XXXXXX")"
7
7
  trap 'rm -rf "$TMP_ROOT"' EXIT HUP INT TERM
8
8
  FAILURES=0
9
+ export CM_WORKFLOW_HOME="$TMP_ROOT/user-config"
9
10
 
10
11
  fail() {
11
12
  echo "FAIL: $*" >&2
@@ -175,6 +176,35 @@ else
175
176
  fail "Claude Bash installer must complete an isolated atomic install"
176
177
  fi
177
178
 
179
+ # Runtime declaration must never be inferred or overwritten in non-interactive installs.
180
+ runtime_config_home="$claude_success/home"
181
+ if [ -e "${runtime_config_home}/.cm-workflow/runtimes.yml" ] ||
182
+ grep -q '你手上有哪个 AI 工具' "$TMP_ROOT/claude-success.out"; then
183
+ fail "--yes must skip runtime declaration without writing"
184
+ fi
185
+ claude_noninteractive="$TMP_ROOT/claude-noninteractive"
186
+ runtime_config_home="$claude_noninteractive/home"
187
+ mkdir -p "${runtime_config_home}/.cm-workflow"
188
+ printf '%s\n' 'runtimes: {available: both}' 'preset: codex-codes' > "${runtime_config_home}/.cm-workflow/runtimes.yml"
189
+ cp "${runtime_config_home}/.cm-workflow/runtimes.yml" "$TMP_ROOT/runtime-before.yml"
190
+ if HOME="$runtime_config_home" CLAUDE_HOME="$claude_noninteractive/.claude" \
191
+ CM_WORKFLOW_HOME="${runtime_config_home}/.cm-workflow" \
192
+ /bin/bash "$ROOT/install.sh" </dev/null > "$TMP_ROOT/claude-noninteractive.out" 2>&1 &&
193
+ cmp -s "$TMP_ROOT/runtime-before.yml" "${runtime_config_home}/.cm-workflow/runtimes.yml" &&
194
+ ! grep -q '保留?' "$TMP_ROOT/claude-noninteractive.out"; then
195
+ :
196
+ else
197
+ cat "$TMP_ROOT/claude-noninteractive.out" >&2
198
+ fail "non-TTY install must preserve the existing user runtime declaration"
199
+ fi
200
+ for prompt_arg in '' '--yes'; do
201
+ HOME="$runtime_config_home" CM_WORKFLOW_HOME="${runtime_config_home}/.cm-workflow" \
202
+ "$REAL_NODE" "$ROOT/scripts/cm-runtime-install.mjs" $prompt_arg </dev/null > "$TMP_ROOT/runtime-prompt.out" 2>&1 ||
203
+ fail "shared installer prompt must skip without a TTY"
204
+ cmp -s "$TMP_ROOT/runtime-before.yml" "${runtime_config_home}/.cm-workflow/runtimes.yml" ||
205
+ fail "shared skipped installer prompt must preserve user declaration bytes"
206
+ done
207
+
178
208
  claude_optional_blocked="$TMP_ROOT/claude-optional-blocked"
179
209
  mkdir -p "$claude_optional_blocked/home"
180
210
  printf '%s\n' 'occupied' > "$claude_optional_blocked/home/.cm-workflow"
@@ -357,6 +387,10 @@ if command -v pwsh >/dev/null 2>&1; then
357
387
  fi
358
388
  fi
359
389
 
390
+ if ! command -v pwsh >/dev/null 2>&1; then
391
+ echo "PowerShell runtime declaration fixtures: SKIPPED (pwsh unavailable)"
392
+ fi
393
+
360
394
  if [ "$FAILURES" -ne 0 ]; then
361
395
  echo "shell compatibility fixtures: FAILED ($FAILURES)" >&2
362
396
  exit 1
@@ -20,6 +20,7 @@ CORE_SKILLS = (
20
20
  "cm-fix",
21
21
  "cm-refactor",
22
22
  "cm-check",
23
+ "cm-runtime",
23
24
  )
24
25
  CM_AI_RUNTIME = (
25
26
  "cm-ai-admission.mjs",
@@ -92,6 +93,10 @@ REQUIRED = (
92
93
  "scripts/test-cm-usage-report.py",
93
94
  "scripts/test-cm-openai-compatible-call.py",
94
95
  "scripts/test-task-gate.py",
96
+ "scripts/cm-runtime.mjs",
97
+ "scripts/cm-runtime-edit.mjs",
98
+ "scripts/cm-runtime-install.mjs",
99
+ "scripts/cm-runtime.test.mjs",
95
100
  "scripts/cm-workflow-config.mjs",
96
101
  "scripts/cm-workflow-config.test.mjs",
97
102
  "scripts/cm_workflow_config.py",
@@ -31,10 +31,11 @@ N3 生成下一次 handoff,避免已校验的证据与实际代码失配。
31
31
 
32
32
  1. `codex-subagent`:用当前运行时的 no-history/fresh-context 选项(如 `fork_turns: none`)新建独立 Codex 子代理/线程,只接收任务范围、验收标准、diff 和验证结果
33
33
  2. `codex-cli`:子代理不可用时,启动隔离的非交互 Codex CLI 审查会话;禁止它修改文件
34
- 3. 两者都不可用:保持待审,记录通道失败原因,不进入 N5;`self-degraded` 只作诊断,不能批准完成
34
+ 3. `claude-cli`:按项目声明选中 Claude 时,使用 protected host 的全新 CLI 审查进程,匹配诊断并逐轮授权;双家声明要求 coder 与 reviewer 不同家,单家使用同家的全新上下文
35
+ 4. 所选独立通道不可用:保持待审,记录通道失败原因,不进入 N5;`self-degraded` 只作诊断,不能批准完成
35
36
 
36
37
  通道故障不伪造代码 finding,也不消耗实现审查轮次;有效阻塞 finding 不能靠换
37
- 审查者洗掉。当前 gate 只支持上述 Codex 通道,Claude-native 适配未验证前不得冒充。
38
+ 审查者洗掉。`claude-cli` 只有在 protected host 实际启动独立审查进程,并经 V3 登记、回收匹配凭证后,才可写 `independent: true`;声明、诊断或文本自报均不得冒充。真实模型实跑仍待验收。
38
39
 
39
40
  审查输入只包含**本 task 的 diff**,不得将整个未分类 working tree 当作任务 diff。审查者必须:
40
41
 
@@ -70,7 +71,7 @@ N3 生成下一次 handoff,避免已校验的证据与实际代码失配。
70
71
 
71
72
  ```yaml
72
73
  ---
73
- reviewer: codex-subagent | codex-cli | self-degraded
74
+ reviewer: codex-subagent | codex-cli | claude-cli | self-degraded
74
75
  independent: true | false
75
76
  task: T-xxx
76
77
  attempt: 1
@@ -89,7 +90,7 @@ scope:
89
90
  `handoff_sha256` 必须逐字使用 `check-n4` 的输出。`scope` 必须逐项覆盖 handoff
90
91
  里的全部 `changed_files`;正文必须写实际 findings 或明确的「零发现」。
91
92
  `approved` 必须写 `blocking_findings: 0`;其他 verdict 至少为 1。
92
- `self-degraded` 必须写 `independent: false`,并用非空 `degraded_reason` 记录前两个
93
+ `self-degraded` 必须写 `independent: false`,并用非空 `degraded_reason` 记录所选独立
93
94
  通道为何不可用。
94
95
  历史自审凭证可审计,但 `independent: false` 即使写了 approved 也不能授权新完成。
95
96
  **无有效独立凭证或 verdict 不是 approved = 不得完成**,N5 必须执行 `mark-done`,
@@ -49,12 +49,21 @@ Claude 诊断只做回环请求捕获,`stopped_by_probe` 表示诊断自身终
49
49
  ## Codex 单任务:显式受保护执行
50
50
 
51
51
  不新增模型调用的方案:单任务和批次均可传`--protected-conversation-config {文件}`,配置固定为
52
- `{checkCommands,timeoutMs}`,命令须已获准。兼容Codex/Claude当前会话,保留原runtime与Review授权。
52
+ `{checkCommands,timeoutMs}`,命令须已获准;`timeoutMs` 同时约束检查命令与 Codex/Claude 审查进程。
53
+ 审查传输超时且没有结果事件时,记录 `pending_review/review_transport_timeout`,可用 `--mode resume` 后 advance,
54
+ 同一 attempt 最多重派一次,重新取得 Review 授权、grant 与 invocation;第二次超时为 `blocked/review_transport_timeout`。
55
+ 已有最终消息(即使截断)的超时仍需 reconcile,旧 unknown 历史不自动改类。兼容Codex/Claude当前会话,保留原runtime与Review授权。
53
56
  develop若有`editMode:"protected-text-v1"`,只读并返回`{status:"succeeded",value:{原开发/Learning结果},edits:[{path,beforeSha256,content}]}`;
54
57
  使用scope内expected摘要,正文完整UTF-8,null删除;不得先自行写文件或执行命令。失败返回原status/code,blocked不能带改动。
55
58
  固定沙箱负责应用提案和原检查,不再请求宿主check;文档同步包含在同次develop提案。原64KiB通道不变,二进制/超限明确阻断。
56
59
  本机Codex sandbox不调用模型,也不改变Claude身份。其余QA/文档核验/子fix权限不变,不与下述protected-config混用。
57
60
 
61
+ 开发结果先通过完整 value/Learning 合同校验,再由沙箱落盘;本地校验失败记录 `failed` / `invalid_result`,原校验码保留在 `result.reason`。
62
+ 当前会话返回 `blocked` / `developer_result_invalid` 时,修正回复后用原配置、身份和 runId 以 `--mode resume` 启动并 `advance`,同一 attempt 重新 develop,不消耗 provider 轮次。
63
+ `no_new_lesson` 必须 `candidates:[]` 且 `reason:null`(实跑事故:非空 reason 曾在文件落盘后抛错,被误记为 unknown,原 runId 无法恢复)。
64
+ 重送已落盘提案时核对新的 expected 哈希:提案内容与磁盘一致才作为同一次实现继续;不一致返回 `protected_edit_stale`,保留文件并报告冲突,不能强制覆盖。
65
+ worker 异常、超时或传输歧义仍是 `unknown`,旧 unknown 历史不自动重分类;其他 blocked 原因也不能使用此重试入口。
66
+
58
67
  用户已授权本任务该轮真实 Codex 开发调用及发送范围时,可选普通单任务入口的
59
68
  `--protected-config {文件} --allow-provider-development-attempt 1`。这是原生受保护子进程,
60
69
  不是当前会话直接改文件,不会因同仓布局自动切换;普通“开始开发”或`--allow-development`本身不授权外发。
@@ -68,6 +77,21 @@ R1要求修改但尚未授权第2轮时保留changes_requested,不登记开发
68
77
  当前会话不重复处理develop/check或手写凭证。补授权后沿原mode resume,不换runId。
69
78
 
70
79
  首次create可同时提供原`--workflow-config`;有QA配置须另带`--allow-qa`,恢复保持原配置与授权。
80
+ 原无workflow或`qa:null`且任务已为`fixture_completed`时,可在`--mode resume`显式提供
81
+ 含QA的`--workflow-config`与`--allow-qa`,一次性附加N6;原definition/scope/requirements/identity、
82
+ host-context、开发/审查配置仍须匹配。journal追加不可重复/修改的`qa-attached`,运行日志写
83
+ `decision/qa_attach`;后续恢复须保持已绑定配置及重新授权,`qa`仍要求`qa_assess`等原宿主请求。
84
+ 不重跑开发/审查,不将任务完成当作QA通过(事故:create漏配workflow曾使feature强制QA无法补做)。
85
+ QA 的 `qa_assess/qa_logic/qa_browser` 请求独立计时,workflow 的 `qa.timeoutMs` 可设 1–60000 毫秒,
86
+ 省略为 60000;超时记 `host_request_timeout` 并阻断,不把已有命令 PASS 用来覆盖超时。
87
+ 宿主读取 JSONL 时必须处理当前缓冲区内的全部完整行,再等下一个数据块;处理单行后不能
88
+ 提前 return(事故:确认和 TC-007 请求合并到一个数据块,旧驱动只读确认而悬空等待)。
89
+ 无 complete 的 N6 中断只能由用户显式重跑:保留原配置,`--mode resume --allow-qa --rerun-unknown-qa`,
90
+ 之后 `advance`;运行日志先记 `test_run/abandoned`,新 testRunId 保持原 qaRound,不重跑开发/审查。
91
+ 已记录 case_complete 必须全为 PASS(允许零条),且无 case_blocked;abandoned 的 partial_pass_cases 记录旧 PASS 用例。
92
+ 所有用例仍全部重跑,旧 PASS 证据文件只作历史保留。任一 FAIL/BLOCKED、固定报告
93
+ `{testRunId}-execution.md` 或未清理资源都不满足恢复条件;保留 unknown/阻断供人工核对,
94
+ 不删报告或日志来获得重跑资格,不伪造 complete。仅写了 abandoned 后再中断可沿同一授权入口恢复。
71
95
  QA命令复用同一specs只读沙箱。最终任务的documentationPaths必须已在批准scope内,
72
96
  在同一次受保护开发调用中同步,随后进入原检查/handoff/Review;不派发宿主documentation_sync,也不增加模型轮次。
73
97
  宿主仍处理qa_assess/qa_logic/qa_browser及只读documentation_inspect;不得借这些请求改代码、规格或指令。
@@ -86,7 +110,7 @@ QA命令复用同一specs只读沙箱。最终任务的documentationPaths必须
86
110
 
87
111
  0.bootstrap按原骨架→规范任务顺序。单任务bootstrap-config为`{selection:null}`或原cm-init选择;
88
112
  批次bootstraps映射到具体feature/task,另传allow-bootstrap-write。原任务批准和逐轮独立Review不能省略。
89
- 先按产品文档配置完整固定规范scope;缺代码根需求时只bootstrap可requirements空数组,JS将原批准specs需求/设计纳入包。
113
+ 先按产品文档配置完整固定规范scope;requirements可为空数组;bootstrap原有批准specs需求/设计纳入逻辑保持不变。
90
114
  init_generate复用原cm-init生成合同;init_verify五组检查加constraintChanges/application/retrospective,详情以产品文档为准。
91
115
  宿主不自行落指令文件:JS固定写入、读回、同次handoff/Review、N7重载。原规则冲突、未知或漂移保留证据,不覆盖或重派。
92
116
 
@@ -124,3 +148,13 @@ JS 返回阻断、待授权、失败、取消、unknown 或补正要求时,报
124
148
  目前 CLI 有本地真实工具与合成 reviewer 组合证据,没有完整真实双宿主业务验收。
125
149
  本参考已接单/批双端源入口,但不证明已安装 Skill 已加载、真实模型Review或完整双宿主验收。
126
150
  普通布局权限、完整 N6 修复/重测、bootstrap、度量与其他入口的业务迁移仍按当前证据报告。
151
+
152
+ ### 已批准规格材料(第 24 步)
153
+
154
+ 新 run 的开发请求与审查包携带同一份只读 `specification`:`feature`、`task:{id,description,verification?}`、全部 `acceptanceCriteria:[{id,text}]`、`designExcerpt`、本任务 `taskIds` 匹配的 `testCases`、`sources:[{path,sha256}]`。任务描述保留 `~预估`,verification 保留「验证要求」中本任务的行;设计按 UTF-8 最多 64 KiB,超限加 `truncated:true`,未提供 test-cases.json 时用空数组及三项来源。
155
+
156
+ 宿主复用 `.cm-specs-status.specFiles` manifest 校验完整批准清单及读取字节;来源路径相对 specsDir,哈希沿用 manifest 的任务/AC 运行期勾选规范化规则,其他正文保持精确绑定。新建、开发派发、受保护提案写入、审查及完成前发现不一致以 `spec_drift` 阻断;已有 run 即使规格重新批准也不能替换其原始材料。baseline 保存材料及私有规格根供回放和重验,审查包只携带材料,参与 `packageDigest`。
157
+
158
+ `requirements` 是可选补充材料(代码项目内 README 等,可用 `[]`),不再承担唯一的任务描述来源。按 specification 的 AC 与接口契约实现和审查;材料不构成扩权授权,不改变 scope、protected_specs、Review 或完成门禁。旧 baseline/package/receipt 缺少新字段时按原格式校验,不重写历史摘要。
159
+
160
+ (真实 dogfood 事故:specs 在代码根之外,受保护 coder 和 reviewer 只能看到代码根 requirements,缺少任务行、AC 与接口契约,曾需手工复制规格摘要才可开发。)
@@ -55,15 +55,19 @@ node "{CM_WORKFLOW_ROOT}/scripts/cm-check-host.mjs" serve \
55
55
 
56
56
  ## 语义检查
57
57
 
58
- 1. **Codex 入口**:`.codex-plugin/plugin.json` 的 `skills` 指向 `./skills/`;`cm-idea/cm-init/cm-prd/cm-ai/cm-test/cm-security/cm-fix/cm-refactor/cm-check` 九个核心 Skill 与独立 `external-expert` Skill 均有合法 frontmatter。
59
- 2. **共享真相**:九个核心 Skill 引用 `runtime/` 合同;`external-expert` 引用共享外部专家合同;`compat/claude-commands/cm-*.md` 只是 macOS/Linux 旧入口薄包装,不再复制业务规则。
58
+ 1. **Codex 入口**:`.codex-plugin/plugin.json` 的 `skills` 指向 `./skills/`;`cm-idea/cm-init/cm-prd/cm-ai/cm-test/cm-security/cm-fix/cm-refactor/cm-check/cm-runtime` 十个核心 Skill 与独立 `external-expert` Skill 均有合法 frontmatter。
59
+ 2. **共享真相**:十个核心 Skill 引用 `runtime/` 合同;`external-expert` 引用共享外部专家合同;`compat/claude-commands/cm-*.md` 只是 macOS/Linux 旧入口薄包装,不再复制业务规则。
60
60
  3. **流程链路**:`cm-ai` 的 N1–N8 引用全部存在;`cm-prd` 的 greenfield/brownfield/change-mode 全部存在;`cm-idea` 引用 `idea-to-prd`;`cm-prd/cm-ai/cm-test/cm-qa-engineer` 共用 `runtime/test-contract.md`;`cm-prd/cm-ai/cm-test/cm-security/cm-fix/cm-refactor/external-expert` 共用 `runtime/logging.md` 与统一 writer;`cm-test --generate-cases` 生成校验后的 inferred 草稿并硬停止。
61
- 4. **角色链路**:N3 引用的 `cm-*-engineer/manager/expert` Skill 存在;Claude `agents/` 中每个兼容角色能找到对应工种 Skill。Codex 不依赖这些 `.md` agent 文件。
61
+ 4. **角色链路**:N3 引用的 `cm-*-engineer/manager/expert` Skill 存在;Claude `agents/` 中每个兼容角色能找到对应工种 Skill。Codex 不依赖这些 `.md` agent 文件;配套完整性核对用户级 `runtimes.yml` 的安装器/cm-runtime 生成方与 cm-workflow-config 消费方,cm-runtime 是独立工具、不配工种。
62
62
  5. **状态与审查**:`.cm-specs-status`、`.cm-status.json`、`.cm-run.json`、`tasks.md`、可选 `test-cases.json`、`METRICS.md`、`LESSONS.md`、`运行日志.jsonl` 及 `.reviews/` 的生成方与消费方配对;项目日志保持权威,全局日志只是私有可重建镜像;N4 凭证头包含 reviewer/independent/task/round/at/scope;`cm-fix` 收口前机械检查修后审查凭证;`.external/` 不得冒充 N4/N5 凭证。
63
63
  6. **模板路径**:所有 `{CM_WORKFLOW_ROOT}/templates/...` 引用都对应真实文件,重点核对 `templates/rules/`、`templates/ui-lens/`、`templates/hooks/`、`templates/refactor/`。
64
64
  7. **版本**:根 `VERSION` 与 plugin manifest 一致;README 不得宣称不存在的入口或安装路径。
65
65
  8. **私有调用清零**:Codex 核心 Skill 不得残留 `TaskCreate`、`TodoWrite`、`codex:review`、`~/.claude/commands`;兼容包装中出现 `/cm:*` 是合法的 macOS/Linux 旧入口。
66
66
 
67
+ 传入 `--project` 时机械检查额外输出「运行时声明对照」:按项目 > 用户级默认 > 未声明读取
68
+ `runtimes.available`,声明的一家若本机 CLI 不可解析只打 `WARN`(可解析≠配额可用,不算失败);
69
+ 并逐行打印 coder/reviewer 的 `route_state`,`declared-adapter` 标「已声明未派发」。这是诊断,不是授权。
70
+
67
71
  外部能力只做降级提示,不应导致插件自检失败:状态条、后台定时更新器、子代理、隔离 CLI
68
72
  审查通道与 external-expert 浏览器 transport 都是可选增强。浏览器不可用时必须能输出
69
73
  手工 handoff packet,不能把可选通道缺失报成核心运行时失败。