@aibyzero/cm-workflow 0.13.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +28 -2
  4. package/VERSION +1 -1
  5. package/docs/installation.md +18 -3
  6. package/docs/js-workflow-control.md +2 -0
  7. package/docs/user-guide.md +16 -0
  8. package/install.ps1 +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +1 -0
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -22
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +4 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +40 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +103 -23
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -4
  16. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +5 -2
  17. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  18. package/runtime/js/cm-ai/developer-adapter.mjs +17 -5
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +7 -2
  20. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  21. package/runtime/js/cm-ai/execution-store.mjs +25 -5
  22. package/runtime/js/cm-ai/host-check.mjs +20 -1
  23. package/runtime/js/cm-ai/host-conversation-execution.mjs +5 -4
  24. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +43 -21
  26. package/runtime/js/cm-ai/host-qa-policy.mjs +3 -1
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +41 -3
  28. package/runtime/js/cm-ai/task-runner.mjs +1 -0
  29. package/runtime/js/cm-ai/worker-claude-developer.mjs +2 -1
  30. package/runtime/js/cm-fix/cause-package.mjs +3 -1
  31. package/runtime/js/cm-fix/dossier.mjs +7 -2
  32. package/runtime/js/cm-fix/reproduce.mjs +26 -5
  33. package/runtime/js/cm-init/draft-generation.mjs +3 -2
  34. package/runtime/js/cm-init/draft-inspection.mjs +17 -3
  35. package/runtime/js/cm-init/review-evidence.mjs +1 -1
  36. package/runtime/js/cm-prd/summary.mjs +6 -8
  37. package/runtime/js/cm-security/finalize.mjs +164 -0
  38. package/runtime/js/specs-status.mjs +66 -0
  39. package/scripts/cm-ai-admission.mjs +46 -7
  40. package/scripts/cm-ai-admission.test.mjs +50 -0
  41. package/scripts/cm-ai-batch-host.mjs +72 -10
  42. package/scripts/cm-ai-batch-host.test.mjs +128 -4
  43. package/scripts/cm-ai-batch-run.mjs +351 -17
  44. package/scripts/cm-ai-batch-run.test.mjs +190 -13
  45. package/scripts/cm-ai-bootstrap.test.mjs +10 -3
  46. package/scripts/cm-ai-host.mjs +38 -21
  47. package/scripts/cm-ai-host.test.mjs +75 -5
  48. package/scripts/cm-ai-multi-root.test.mjs +7 -1
  49. package/scripts/cm-ai-nested-execution.test.mjs +8 -2
  50. package/scripts/cm-ai-run.mjs +25 -15
  51. package/scripts/cm-ai-run.test.mjs +48 -0
  52. package/scripts/cm-blocked-reason.test.mjs +104 -0
  53. package/scripts/cm-capability-gate.test.mjs +179 -0
  54. package/scripts/cm-check-host.test.mjs +7 -1
  55. package/scripts/cm-codex-developer-adapter.test.mjs +70 -0
  56. package/scripts/cm-fix-cause-package.test.mjs +18 -1
  57. package/scripts/cm-fix-execution.test.mjs +31 -0
  58. package/scripts/cm-fix-host-review.test.mjs +9 -2
  59. package/scripts/cm-fix-host.test.mjs +2 -1
  60. package/scripts/cm-fix-observation-dossier.test.mjs +2 -0
  61. package/scripts/cm-fix-qa-source.test.mjs +1 -3
  62. package/scripts/cm-fix-reproduce.test.mjs +53 -2
  63. package/scripts/cm-fix-review-recovery.test.mjs +4 -3
  64. package/scripts/cm-host-check.test.mjs +22 -0
  65. package/scripts/cm-host-qa-executor.test.mjs +302 -3
  66. package/scripts/cm-host-qa-policy.test.mjs +34 -0
  67. package/scripts/cm-init-draft-generation.test.mjs +24 -3
  68. package/scripts/cm-init-draft-inspection.test.mjs +80 -0
  69. package/scripts/cm-init-host.mjs +2 -2
  70. package/scripts/cm-init-host.test.mjs +3 -1
  71. package/scripts/cm-init-session.test.mjs +37 -0
  72. package/scripts/cm-log-event.mjs +28 -7
  73. package/scripts/cm-prd-completion.test.mjs +7 -1
  74. package/scripts/cm-prd-design-phase.test.mjs +2 -1
  75. package/scripts/cm-prd-host.test.mjs +3 -2
  76. package/scripts/cm-prd-session-recovery.test.mjs +5 -4
  77. package/scripts/cm-runtime-i18n.mjs +32 -0
  78. package/scripts/cm-runtime-install.mjs +49 -23
  79. package/scripts/cm-runtime.mjs +45 -17
  80. package/scripts/cm-runtime.test.mjs +101 -0
  81. package/scripts/cm-security.mjs +12 -4
  82. package/scripts/cm-security.test.mjs +109 -0
  83. package/scripts/cm-specs-status.test.mjs +130 -0
  84. package/scripts/cm-workflow-config.mjs +4 -0
  85. package/scripts/test-shell-compat.sh +0 -0
  86. package/skills/cm-ai/references/N1-init.md +20 -15
  87. package/skills/cm-ai/references/N6-qa-eval.md +9 -4
  88. package/skills/cm-ai/references/js-host.md +10 -0
  89. package/skills/cm-fix/SKILL.md +5 -4
  90. package/skills/cm-fix/references/js-host.md +13 -0
  91. package/skills/cm-idea/SKILL.md +2 -0
  92. package/skills/cm-init/references/runtime-declaration.md +2 -0
  93. package/skills/cm-prd/SKILL.md +9 -8
  94. package/skills/cm-prd/references/spec-self-check.md +1 -0
  95. package/skills/cm-runtime/SKILL.md +23 -2
  96. package/skills/cm-security/SKILL.md +11 -6
  97. package/skills/cm-security/references/scan-contract.md +45 -1
@@ -8,6 +8,9 @@ import {fileURLToPath} from 'node:url';
8
8
  import {ConfigError,findConfig,loadConfig,readConfigText,parseUserRuntimes,
9
9
  userRuntimesPath,runtimePreset,RUNTIME_PRESETS,resolveRole,runtimesSource} from './cm-workflow-config.mjs';
10
10
  import {editRuntimeDeclaration} from './cm-runtime-edit.mjs';
11
+ import {runtimeLanguage,runtimeText as t} from './cm-runtime-i18n.mjs';
12
+ import {askRuntimePreset,runtimeQuestions,PromptCancelled} from './cm-runtime-install.mjs';
13
+ export {askRuntimePreset} from './cm-runtime-install.mjs';
11
14
  import {probeRuntimes} from './cm-failover.mjs';
12
15
 
13
16
  const scripts=path.dirname(fileURLToPath(import.meta.url));
@@ -29,10 +32,10 @@ export function atomicRuntimeWrite(file,text,{before=null,privateFile=false}={})
29
32
  fs.renameSync(temporary,file);
30
33
  }finally{if(stat(temporary))fs.unlinkSync(temporary);}
31
34
  }
32
- export function writeUserRuntime(preset){
35
+ export function writeUserRuntime(preset,{lang=runtimeLanguage()}={}){
33
36
  const declaration=runtimePreset(preset),file=userRuntimesPath();
34
37
  safeTarget(file);
35
- const text=`# 用 cm-runtime set --user <preset> 修改用户级默认。\nruntimes: {available: ${declaration.runtimes.available}}\npreset: ${preset}\n`;
38
+ const text=`# ${t('comment',lang)}\nruntimes: {available: ${declaration.runtimes.available}}\npreset: ${preset}\n`;
36
39
  parseUserRuntimes(text);
37
40
  atomicRuntimeWrite(file,text,{before:stat(file)?fs.readFileSync(file):null,privateFile:true});
38
41
  return file;
@@ -54,7 +57,7 @@ export function setProjectRuntime(project,preset){
54
57
  loadConfig({projectRoot:root,configPath:file,text});
55
58
  atomicRuntimeWrite(file,text,{before});return file;
56
59
  }
57
- export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',probe=probeRuntimes}={}){
60
+ export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',probe=probeRuntimes,lang=runtimeLanguage()}={}){
58
61
  const config=loadConfig({projectRoot:project});
59
62
  const preset=Object.keys(RUNTIME_PRESETS).find(name=>{
60
63
  const value=runtimePreset(name);
@@ -64,12 +67,12 @@ export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',pro
64
67
  const lines=[`runtimes.available: ${config.runtimes.available}`,`preset: ${preset}`,`runtimes_source: ${runtimesSource(config)}`];
65
68
  for(const role of ['coder','reviewer']){
66
69
  const resolved=resolveRole(config,role,runtime);
67
- lines.push(`${role}: adapter=${resolved.adapter} source=${resolved.source} route_state=${resolved.route_state}${resolved.route_state==='declared-adapter'?'(已声明未派发)':''}`);
70
+ lines.push(`${role}: adapter=${resolved.adapter} source=${resolved.source} route_state=${resolved.route_state}${resolved.route_state==='declared-adapter'?t('declared',lang):''}`);
68
71
  }
69
72
  const wanted=config.runtimes.available==='both'?['codex','claude']:config.runtimes.available==='unknown'?[]:[config.runtimes.available];
70
73
  for(const result of probe(wanted))lines.push(result.available
71
- ?`${result.runtime} CLI: 可解析(可解析≠配额可用)`
72
- :`WARN: runtimes.available 声明 ${config.runtimes.available},但本机 ${result.runtime} CLI 不可解析(可解析≠配额可用)`);
74
+ ?t('cli',lang,{runtime:result.runtime})
75
+ :t('warning',lang,{available:config.runtimes.available,runtime:result.runtime}));
73
76
  return lines.join('\n');
74
77
  }
75
78
  function logSet(preset,source,project){
@@ -87,11 +90,38 @@ function logSet(preset,source,project){
87
90
  }
88
91
  throw new ConfigError('preference saved, decision log failed: Python 3.9+ lock adapter unavailable');
89
92
  }
90
- const USAGE='cm-runtime show [--project PATH]\ncm-runtime set <preset> [--project PATH]\ncm-runtime set --user <preset>\ncm-runtime unset --user';
91
- export function main(argv=process.argv.slice(2)){
93
+ const COMMANDS='cm-runtime show [--project PATH]\ncm-runtime set <preset> [--project PATH]\ncm-runtime set --user <preset>\ncm-runtime unset --user';
94
+ export async function interactiveRuntime(project,{input=process.stdin,output=process.stdout,lang=runtimeLanguage()}={}){
95
+ const root=projectDirectory(project),existing=findConfig(root),file=existing??path.join(root,'.cm-workflow.yml');
96
+ const questions=runtimeQuestions(input,output,lang),ask=questions.ask;
92
97
  try{
93
- if(argv.length===1&&['--help','-h'].includes(argv[0])){console.log(USAGE);return 0;}
94
- const [command,...args]=argv;let project=process.cwd(),user=false,preset=null,projectSeen=false;
98
+ const fallback=existing?'1':'2';let scope;
99
+ do{scope=await ask(t('scope',lang,{project:file,user:userRuntimesPath(),default:fallback}));scope=scope||fallback;}while(!['1','2'].includes(scope));
100
+ const user=scope==='2';
101
+ if(!user&&!existing)output.write(t('create',lang,{file}));
102
+ const preset=await askRuntimePreset(ask,lang);
103
+ const target=user?userRuntimesPath():file;
104
+ const current=user?(stat(target)?readConfigText(target):t('absent',lang)):showRuntime(root,{lang,probe:()=>[]});
105
+ output.write(t('preview',lang,{file:target,preset,current}));
106
+ let confirm;
107
+ do{confirm=(await ask(t('confirm',lang))).toLowerCase();}while(!['','y','n'].includes(confirm));
108
+ if(confirm==='n')throw new PromptCancelled();
109
+ saveRuntime(root,preset,user,lang,output);
110
+ output.write(showRuntime(root,{lang})+'\n');return 0;
111
+ }catch(error){if(error instanceof PromptCancelled){output.write(t('cancelled',lang));return 0;}throw error;}
112
+ finally{questions.close();}
113
+ }
114
+ function saveRuntime(project,preset,user,lang,output){
115
+ runtimePreset(preset);project=projectDirectory(project);
116
+ const file=user?writeUserRuntime(preset,{lang}):setProjectRuntime(project,preset);
117
+ logSet(preset,user?'user':'project',project);
118
+ output.write(t('saved',lang,{file,preset,source:user?'user':'project'})+'\n');
119
+ }
120
+ export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,lang=runtimeLanguage()}={}){
121
+ const USAGE=t('help',lang)+'\n'+COMMANDS;
122
+ try{
123
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(USAGE+'\n');return 0;}
124
+ const command=argv[0]?.startsWith('--')?undefined:argv[0];const args=command?argv.slice(1):argv;let project=process.cwd(),user=false,preset=null,projectSeen=false;
95
125
  for(let i=0;i<args.length;i++){
96
126
  if(args[i]==='--user'&&!user){user=true;continue;}
97
127
  if(args[i]==='--project'&&!projectSeen&&args[i+1]&&!args[i+1].startsWith('--')){project=args[++i];projectSeen=true;continue;}
@@ -99,15 +129,13 @@ export function main(argv=process.argv.slice(2)){
99
129
  throw new ConfigError(USAGE);
100
130
  }
101
131
  if(user&&projectSeen)throw new ConfigError('--user cannot be combined with --project');
102
- if(command==='show'&&!user){console.log(showRuntime(project));return 0;}
132
+ if(!command&&!user){if(!input.isTTY||!output.isTTY){output.write(USAGE+'\n');return 2;}return await interactiveRuntime(project,{input,output,lang});}
133
+ if(command==='show'&&!user){output.write(showRuntime(project,{lang})+'\n');return 0;}
103
134
  if(command==='set'&&preset){
104
- runtimePreset(preset);project=projectDirectory(project);
105
- const file=user?writeUserRuntime(preset):setProjectRuntime(project,preset);
106
- logSet(preset,user?'user':'project',project);
107
- console.log(`Saved ${file}: ${preset} (${user?'user':'project'}); existing runs unchanged`);return 0;
135
+ saveRuntime(project,preset,user,lang,output);return 0;
108
136
  }
109
- if(command==='unset'&&user){const file=userRuntimesPath();safeTarget(file);if(stat(file))fs.unlinkSync(file);console.log(`Removed user default: ${file}; project declarations still take precedence`);return 0;}
137
+ if(command==='unset'&&user){const file=userRuntimesPath();safeTarget(file);if(stat(file))fs.unlinkSync(file);output.write(t('removed',lang,{file})+'\n');return 0;}
110
138
  throw new ConfigError(USAGE);
111
139
  }catch(error){console.error(`cm-runtime: ${error.message}`);return 1;}
112
140
  }
113
- if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
141
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=await main();
@@ -115,3 +115,104 @@ test('candidate over the shared file size limit is rejected before atomic replac
115
115
  assert.throws(()=>setProjectRuntime(root,'codex-codes'),/exceeds/);
116
116
  assert.equal(fs.readFileSync(file,'utf8'),original);
117
117
  }));
118
+
119
+ // Pseudo TTY streams still use the production node:readline implementation.
120
+ async function wizardFixture(fn){
121
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-runtime-wizard-')));
122
+ const previous={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
123
+ process.env.CM_WORKFLOW_HOME=path.join(root,'user');process.env.CM_WORKFLOW_LOG_HOME=path.join(root,'logs');
124
+ try{await fn(root);}finally{
125
+ for(const [key,value] of Object.entries(previous)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
126
+ fs.rmSync(root,{recursive:true,force:true});
127
+ }
128
+ }
129
+ import {PassThrough} from 'node:stream';
130
+ import {main,askRuntimePreset as wizardPreset} from './cm-runtime.mjs';
131
+ import {askRuntimePreset as installerPreset,promptRuntime} from './cm-runtime-install.mjs';
132
+ import {runtimeLanguage} from './cm-runtime-i18n.mjs';
133
+ function tty(){
134
+ const input=new PassThrough(),output=new PassThrough();input.isTTY=output.isTTY=true;
135
+ let text='';output.on('data',chunk=>{text+=chunk;});
136
+ return {input,output,text:()=>text};
137
+ }
138
+ async function wizard(root,answers,lang='en'){
139
+ const io=tty();const running=main(['--project',root],{...io,lang});
140
+ io.input.end(answers);const code=await running;return {code,text:io.text()};
141
+ }
142
+ test('wizard and installer share the same preset question function',()=>assert.equal(wizardPreset,installerPreset));
143
+ test('language priority, explicit overrides, locales, Intl and English fallback',()=>{
144
+ for(const [env,expected] of [
145
+ [{CM_WORKFLOW_LANG:'en',LC_ALL:'zh_CN.UTF-8'},'en'],
146
+ [{CM_WORKFLOW_LANG:'zh',LC_ALL:'en_US.UTF-8'},'zh'],
147
+ [{LC_ALL:'en_US.UTF-8',LC_MESSAGES:'zh_CN.UTF-8'},'en'],
148
+ [{LC_MESSAGES:'zh_CN.UTF-8',LANG:'en_US.UTF-8'},'zh'],
149
+ [{LANG:'zh_CN.UTF-8'},'zh'],[{LANG:'en_US.UTF-8'},'en'],
150
+ [{LANG:'C'},'en'],[{},'en'],
151
+ ])assert.equal(runtimeLanguage(env,()=>undefined),expected);
152
+ assert.equal(runtimeLanguage({},()=> 'zh-TW'),'zh');
153
+ assert.equal(runtimeLanguage({},()=>{throw new Error('Intl unavailable');}),'en');
154
+ });
155
+ test('TTY project wizard changes exactly five fields, logs decision and shows result',()=>wizardFixture(async root=>{
156
+ const file=path.join(root,'.cm-workflow.yml');
157
+ const before='\ufeff# keep\r\nversion: 1\r\nruntimes: {available: codex}\r\nroles:\r\n coder: {adapter: current-ai, source: local, model: default} # keep coder\r\n reviewer: {adapter: current-ai, source: local, model: default}\r\n';
158
+ const initial=before;
159
+ fs.writeFileSync(file,initial);
160
+ const result=await wizard(root,'1\n3\n1\nY\n');assert.equal(result.code,0,result.text);
161
+ assert.equal(fs.readFileSync(file,'utf8'),initial.replace('available: codex','available: both').replace('adapter: current-ai','adapter: codex-cli').replace('adapter: current-ai','adapter: claude-cli').replaceAll('source: local','source: subscription'));
162
+ assert.match(result.text,/Which AI tools do you have/);assert.match(result.text,/Who writes code/);
163
+ assert.match(result.text,/preset: codex-codes/);assert.match(result.text,/runtimes_source: project/);
164
+ const logs=fs.readdirSync(path.join(root,'logs','runs'),{recursive:true}).filter(x=>x.endsWith('.jsonl'));
165
+ assert.equal(logs.length,1);const event=JSON.parse(fs.readFileSync(path.join(root,'logs','runs',logs[0]),'utf8'));
166
+ assert.equal(event.event,'decision');assert.equal(event.preset,'codex-codes');
167
+ }));
168
+ test('missing project defaults to user scope and Chinese preset/comment/output',()=>wizardFixture(async root=>{
169
+ const result=await wizard(root,'\n2\nY\n','zh');assert.equal(result.code,0);
170
+ assert(!fs.existsSync(path.join(root,'.cm-workflow.yml')));
171
+ assert.match(fs.readFileSync(path.join(root,'user','runtimes.yml'),'utf8'),/# 用 cm-runtime.*\npreset: claude-only/s);
172
+ assert.match(result.text,/你手上有哪个 AI 工具/);assert.match(result.text,/确认?/);assert.match(result.text,/runtimes_source: user/);
173
+ }));
174
+ test('three empty mandatory answers, refusal, EOF and SIGINT do not write',()=>wizardFixture(async root=>{
175
+ for(const answers of ['2\n\n\n\n','2\n1\nn\n','2\n']){
176
+ const result=await wizard(root,answers);assert.equal(result.code,0);assert.match(result.text,/Cancelled/);assert.deepEqual(fs.readdirSync(root),[]);
177
+ }
178
+ const io=tty(),running=main(['--project',root],io);process.emit('SIGINT');
179
+ assert.equal(await running,0);assert.match(io.text(),/Cancelled/);assert.deepEqual(fs.readdirSync(root),[]);
180
+ }));
181
+ test('explicit project creation, existing-project scope default and invalid choice retry',()=>wizardFixture(async root=>{
182
+ const created=await wizard(root,'1\nwrong\n1\ny\n');assert.equal(created.code,0);assert.match(created.text,/Will create project configuration/);
183
+ const changed=await wizard(root,'\n3\n2\n\n');assert.equal(changed.code,0);assert.match(changed.text,/preset: claude-codes/);
184
+ assert.equal(loadConfig({projectRoot:root}).roles.coder.adapter,'claude-cli');
185
+ }));
186
+ test('non-TTY no command exits 2 with usage and no writes',()=>fixture((root,run)=>{
187
+ const result=run();assert.equal(result.status,2);assert.match(result.stdout,/cm-runtime/);assert.deepEqual(fs.readdirSync(root),[]);
188
+ }));
189
+ test('installer yes skips even TTY; culture selects shared English or Chinese text',()=>wizardFixture(async root=>{
190
+ for(const culture of ['en-US','zh-CN']){
191
+ const io=tty();await promptRuntime(['--yes','--lang',culture],io.input,io.output);
192
+ assert.equal(io.text(),'');assert.deepEqual(fs.readdirSync(root),[]);
193
+ }
194
+ }));
195
+ test('human diagnostics translate while structured fields and user file data stay identical',()=>wizardFixture(async root=>{
196
+ writeUserRuntime('codex-codes',{lang:'en'});
197
+ const options={probe:()=>[{runtime:'codex',available:true},{runtime:'claude',available:false}]};
198
+ const en=showRuntime(root,{...options,lang:'en'}),zh=showRuntime(root,{...options,lang:'zh'});
199
+ assert.equal(en.split('\n').slice(0,3).join('\n'),zh.split('\n').slice(0,3).join('\n'));
200
+ assert.match(en,/declared, not dispatched/);assert.match(zh,/已声明未派发/);
201
+ assert.match(en,/presence does not prove quota/);assert.match(zh,/可解析≠配额可用/);
202
+ assert.match(fs.readFileSync(path.join(root,'user','runtimes.yml'),'utf8'),/# Use cm-runtime/);
203
+ }));
204
+ test('installer culture reaches shared prompts and comments; explicit override wins',()=>wizardFixture(async root=>{
205
+ const keys=['CM_WORKFLOW_LANG','LC_ALL','LC_MESSAGES','LANG'];
206
+ const saved=Object.fromEntries(keys.map(key=>[key,process.env[key]]));
207
+ try{
208
+ for(const key of keys)delete process.env[key];
209
+ for(const [culture,override,expected] of [['zh-CN',undefined,'zh'],['en-US',undefined,'en'],['zh-CN','en','en']]){
210
+ if(override)process.env.CM_WORKFLOW_LANG=override;else delete process.env.CM_WORKFLOW_LANG;
211
+ const io=tty(),running=promptRuntime(['--lang',culture],io.input,io.output);
212
+ io.input.end('3\n2\n');await running;
213
+ assert.match(io.text(),expected==='zh'?/你手上有哪个 AI 工具/:/Which AI tools do you have/);
214
+ const file=path.join(root,'user','runtimes.yml');assert.match(fs.readFileSync(file,'utf8'),expected==='zh'?/# 用 cm-runtime/:/# Use cm-runtime/);
215
+ fs.unlinkSync(file);
216
+ }
217
+ }finally{for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}}
218
+ }));
@@ -3,27 +3,35 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {fileURLToPath} from 'node:url';
5
5
  import {scan} from '../runtime/js/cm-security/scan.mjs';
6
+ import {finalize} from '../runtime/js/cm-security/finalize.mjs';
6
7
 
7
8
  export function main(argv){
8
9
  let project=process.cwd();const options={};const seen=new Set();
9
10
  for(let i=0;i<argv.length;i++){
10
11
  const key=argv[i];
11
- if(key==='--help')return {help:'cm-security.mjs [--project PATH] [--all] [--inventory] [--semgrep-rules EXTERNAL_FILE] [--osv-db EXTERNAL_CACHE_DIR]'};
12
+ if(key==='--help')return {help:'cm-security.mjs [--project PATH] [--all] [--inventory] [--semgrep-rules EXTERNAL_FILE] [--osv-db EXTERNAL_CACHE_DIR] | [--project PATH] --finalize --scan EXTERNAL_JSON --review EXTERNAL_JSON'};
12
13
  if(seen.has(key))throw new Error('duplicate_argument');seen.add(key);
13
14
  if(key==='--all')options.all=true;
14
15
  else if(key==='--inventory')options.inventoryOnly=true;
15
- else if(['--project','--semgrep-rules','--osv-db'].includes(key)){
16
+ else if(key==='--finalize')options.finalize=true;
17
+ else if(['--project','--semgrep-rules','--osv-db','--scan','--review'].includes(key)){
16
18
  const value=argv[++i];if(!value||value.startsWith('--'))throw new Error('argument_value_required');
17
19
  if(key==='--project')project=value;
18
- else options[key==='--semgrep-rules'?'semgrepRules':'osvDb']=value;
20
+ else options[({'--semgrep-rules':'semgrepRules','--osv-db':'osvDb','--scan':'scanFile','--review':'reviewFile'})[key]]=value;
19
21
  }else throw new Error('unknown_argument');
20
22
  }
23
+ if(options.finalize){
24
+ if(options.all||options.inventoryOnly||options.semgrepRules||options.osvDb)throw new Error('finalize_mode_conflict');
25
+ if(!options.scanFile||!options.reviewFile)throw new Error('finalize_inputs_required');
26
+ return finalize(fs.realpathSync(project),options);
27
+ }
28
+ if(options.scanFile||options.reviewFile)throw new Error('finalize_mode_required');
21
29
  return scan(fs.realpathSync(project),options);
22
30
  }
23
31
  if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
24
32
  try{
25
33
  const result=main(process.argv.slice(2));console.log(JSON.stringify(result,null,2));
26
- process.exitCode=result.help?0:result.result==='BLOCKED'?2:result.findings?.length?1:result.result==='NO_CHANGES'?0:3;
34
+ process.exitCode=result.help?0:result.result==='BLOCKED'?2:(result.findingsCount||result.findings?.length)?1:result.result==='NO_CHANGES'?0:3;
27
35
  }catch(error){
28
36
  // Do not echo paths, input values, source snippets or scanner stderr from exceptions.
29
37
  console.log(JSON.stringify({result:'BLOCKED',coverage:'PARTIAL',reason:/^[a-z0-9_]+$/.test(error.message)?error.message:'scan_failed'}));
@@ -201,3 +201,112 @@ test('empty initial scope never overrides concurrent source drift with NO_CHANGE
201
201
  try{const r=scan(f.project);assert.equal(r.sourceUnchanged,false);assert.equal(r.result,'BLOCKED');}
202
202
  finally{fs.mkdtempSync=original;}
203
203
  });
204
+
205
+ // Controlled scanner metadata makes FULL reachable without installed scanners or
206
+ // pretending that the real OSV freshness/coverage gap has been resolved.
207
+ function finalizeFixture(t,{all=true}={}){
208
+ const f=fixture(t);isolatedPath(t,f);
209
+ f.put('other.py','other\n');f.git('add','.');f.git('commit','-m','second path');
210
+ if(!all){f.git('switch','main');}
211
+ const report=scan(f.project,{all});
212
+ report.tools=report.tools.map(row=>({...row,status:'NO_FINDINGS',reason:null}));
213
+ const review={version:1,scanDigest:report.digest,paths:report.selected.map(file=>({path:file,status:'reviewed',findings:[]}))};
214
+ const scanFile=path.join(f.base,'scan.json'),reviewFile=path.join(f.base,'review.json');
215
+ const run=(r=review,s=report,{cli=false}={})=>{
216
+ fs.writeFileSync(scanFile,JSON.stringify(s));fs.writeFileSync(reviewFile,JSON.stringify(r));
217
+ const args=['--project',f.project,'--finalize','--scan',scanFile,'--review',reviewFile];
218
+ let value,code,stdout;
219
+ if(cli){const child=spawnSync(process.execPath,[path.join(root,'scripts/cm-security.mjs'),...args],{encoding:'utf8'});
220
+ code=child.status;stdout=child.stdout;value=JSON.parse(stdout);
221
+ }else value=main(args);
222
+ const output=value.reportPath?JSON.parse(fs.readFileSync(value.reportPath,'utf8')):null;
223
+ if(value.reportPath)t.after(()=>fs.rmSync(path.dirname(value.reportPath),{recursive:true,force:true}));
224
+ return {value,output,code,stdout};
225
+ };
226
+ return {...f,report,review,run,scanFile,reviewFile};
227
+ }
228
+
229
+ test('finalize coverage requires every selected path and rejects unknown or malformed review input',t=>{
230
+ const f=finalizeFixture(t);
231
+ assert.equal(f.run().value.coverage,'FULL');
232
+ const missing={...f.review,paths:f.review.paths.slice(1)};
233
+ let r=f.run(missing);assert.equal(r.value.coverage,'PARTIAL');
234
+ assert.ok(r.value.gaps.some(row=>row.path==='app.py'&&row.reason==='not_reported'));
235
+ assert.equal(r.output.aiReview,'completed');
236
+ r=f.run({...f.review,paths:[{path:'app.py',status:'not_reviewed',reason:'SOURCE_OR_SECRET_SENTINEL'},f.review.paths[1]]});
237
+ assert.equal(r.value.coverage,'PARTIAL');assert.ok(!JSON.stringify(r.value).includes('SOURCE_OR_SECRET_SENTINEL'));assert.equal(r.output.review.paths[0].reason,'SOURCE_OR_SECRET_SENTINEL');
238
+ for(const mutate of [
239
+ r=>r.paths.push({path:'unknown.py',status:'reviewed',findings:[]}),
240
+ r=>r.paths.push(r.paths[0]),r=>{r.result='NO_CHANGES';},r=>{r.aiReview='completed';},
241
+ r=>{r.scanDigest='0'.repeat(64);},r=>{r.paths[0].reason='not allowed';},
242
+ r=>{r.paths[0]={path:'app.py',status:'not_reviewed'};},
243
+ r=>{r.paths[0]={path:'app.py',status:'not_reviewed',reason:'\0'};},
244
+ r=>{r.paths[0]={path:'app.py',status:'not_reviewed',reason:'界'.repeat(334)};},
245
+ r=>{r.paths=Array(2001).fill(r.paths[0]);},
246
+ ]){
247
+ const input=structuredClone(f.review);mutate(input);
248
+ assert.throws(()=>f.run(input),/review_path_unknown|review_path_duplicate|invalid_report_shape|review_digest_mismatch|invalid_review_string|report_array_limit/);
249
+ }
250
+ const unknown=f.run({...f.review,paths:[{path:'unknown.py',status:'reviewed',findings:[]}]},f.report,{cli:true});
251
+ assert.equal(unknown.code,2);assert.equal(unknown.value.reason,'review_path_unknown');
252
+ for(const update of [s=>{s.gaps.push({path:'app.py',reason:'index_oversize'});},
253
+ s=>{s.tools[0].reason='unscanned_files';},s=>{s.tools[0].status='ERROR';}]){
254
+ const s=structuredClone(f.report);update(s);assert.equal(f.run(f.review,s).value.coverage,'PARTIAL');
255
+ }
256
+ assert.throws(()=>f.run(f.review,{...f.report,rawOutput:'SOURCE_OR_SECRET_SENTINEL'}),/invalid_report_shape/);
257
+ f.run();f.put('inside.json',JSON.stringify(f.review));
258
+ assert.throws(()=>main(['--project',f.project,'--finalize','--scan',f.scanFile,'--review',path.join(f.project,'inside.json')]),/external_regular/);
259
+ const link=path.join(f.base,'linked.json');fs.symlinkSync(f.reviewFile,link);
260
+ assert.throws(()=>main(['--project',f.project,'--finalize','--scan',f.scanFile,'--review',link]),/external_regular/);
261
+ assert.throws(()=>main(['--project',f.project,'--finalize','--scan',f.scanFile,'--review',f.base]),/external_regular/);
262
+ assert.throws(()=>main(['--finalize','--all','--scan',f.scanFile,'--review',f.reviewFile]),/mode_conflict/);
263
+ assert.throws(()=>main(['--finalize']),/inputs_required/);
264
+ assert.throws(()=>main(['--scan',f.scanFile]),/mode_required/);
265
+ });
266
+
267
+ test('finalize detects the second drift window and retains the original scan window',t=>{
268
+ const f=finalizeFixture(t);f.put('app.py','changed after scan\n');
269
+ let r=f.run(f.review,f.report,{cli:true});
270
+ assert.equal(r.code,2);assert.equal(r.value.result,'BLOCKED');assert.equal(r.value.coverage,'PARTIAL');
271
+ assert.equal(r.value.sourceUnchanged,false);assert.ok(r.value.gaps.some(g=>g.reason==='source_changed_during_review'));
272
+ assert.equal(r.output.sourceWindows.scan.sourceUnchanged,true);assert.equal(r.output.sourceWindows.review.sourceUnchanged,false);
273
+ f.put('app.py','print("base")\n');
274
+ const blocked={...f.report,result:'BLOCKED',sourceUnchanged:false,gaps:[{reason:'source_changed'}]};
275
+ r=f.run(f.review,blocked,{cli:true});assert.equal(r.code,2);
276
+ assert.equal(r.output.sourceWindows.scan.sourceUnchanged,false);assert.equal(r.output.sourceWindows.review.sourceUnchanged,true);
277
+ assert.equal(r.value.sourceUnchanged,false);assert.ok(r.value.gaps.some(g=>g.reason==='source_changed'));
278
+ f.git('branch','-m','renamed-feature');
279
+ // all-tracked binds HEAD, not branch name. Default scope binds its comparison too.
280
+ const defaultScan=scan(f.project),review={version:1,scanDigest:defaultScan.digest,paths:defaultScan.selected.map(file=>({path:file,status:'reviewed',findings:[]}))};
281
+ f.git('branch','-m','another-feature');r=f.run(review,defaultScan,{cli:true});assert.equal(r.code,2);
282
+ assert.ok(r.value.gaps.some(g=>g.reason==='source_changed_during_review'));
283
+ });
284
+
285
+ test('finalize verdicts stay conservative, finding prose stays in the private report, and empty scope is NO_CHANGES',t=>{
286
+ const f=finalizeFixture(t);let r=f.run(f.review,f.report,{cli:true});
287
+ assert.equal(r.code,3);assert.equal(r.value.result,'REVIEWED_PARTIAL');assert.equal(r.value.coverage,'FULL');
288
+ assert.deepEqual(Object.keys(r.value).sort(),['result','coverage','reportPath','gaps','findingsCount','sourceUnchanged'].sort());
289
+ assert.ok(path.relative(f.project,r.value.reportPath).startsWith('..'+path.sep));
290
+ if(process.platform!=='win32')assert.equal(fs.statSync(r.value.reportPath).mode&0o777,0o600);
291
+ const finding={severity:'high',location:'app.py:1',attacker:'SOURCE_OR_SECRET_SENTINEL',vector:'SOURCE_OR_SECRET_SENTINEL',
292
+ existingControls:'SOURCE_OR_SECRET_SENTINEL',impact:'SOURCE_OR_SECRET_SENTINEL',confidence:'static-inference',recommendation:'SOURCE_OR_SECRET_SENTINEL'};
293
+ const review=structuredClone(f.review);review.paths[0].findings=[finding];
294
+ r=f.run(review,f.report,{cli:true});assert.equal(r.code,1);assert.equal(r.value.result,'FINDINGS');assert.equal(r.value.findingsCount,1);
295
+ assert.ok(!r.stdout.includes('SOURCE_OR_SECRET_SENTINEL'));assert.deepEqual(r.output.review.paths[0].findings[0],finding);
296
+ for(const patch of [{extra:'secret'},{severity:'critical'},{confidence:'guessed'},{location:'other.py:1'},{impact:'\u0001'},{impact:' '}]){
297
+ const bad=structuredClone(review);Object.assign(bad.paths[0].findings[0],patch);assert.throws(()=>f.run(bad));
298
+ }
299
+ const many=structuredClone(review);many.paths[0].findings=Array(201).fill(finding);assert.throws(()=>f.run(many),/report_array_limit/);
300
+ const toolFinding={path:'app.py',revision:'worktree',line:1,tool:'gitleaks',rule:'fixture-rule',severity:'high',verification:'candidate'};
301
+ r=f.run(f.review,{...f.report,result:'FINDINGS',findings:[toolFinding]},{cli:true});assert.equal(r.code,1);assert.equal(r.value.findingsCount,1);
302
+ for(let i=0;i<9;i++)f.put(`extra${i}.py`,'fixture\n');
303
+ f.git('add','.');f.git('commit','-m','finding count fixture');
304
+ const largeScan=scan(f.project,{all:true});
305
+ const tooMany={version:1,scanDigest:largeScan.digest,paths:largeScan.selected.map(file=>({path:file,status:'reviewed',
306
+ findings:Array.from({length:182},()=>({...finding,location:`${file}:1`}))}))};
307
+ assert.throws(()=>f.run(tooMany,largeScan),/review_findings_limit/);
308
+ f.git('switch','main');const empty=scan(f.project),emptyReview={version:1,scanDigest:empty.digest,paths:[]};
309
+ r=f.run(emptyReview,empty,{cli:true});assert.equal(r.code,0);assert.equal(r.value.result,'NO_CHANGES');
310
+ assert.equal(r.value.coverage,'PARTIAL');assert.equal(r.output.aiReview,'completed');
311
+ f.put('app.py','drift from empty scope\n');r=f.run(emptyReview,empty,{cli:true});assert.equal(r.code,2);assert.equal(r.value.result,'BLOCKED');
312
+ });
@@ -0,0 +1,130 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {createHash} from 'node:crypto';
9
+ import {readSpecsStatus,writeSpecsStatus} from '../runtime/js/specs-status.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {claimPrdReview} from './cm-prd-review-gate.mjs';
12
+ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
13
+ import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
14
+ import {recordPrdHostDisposition} from '../runtime/js/cm-prd/review-disposition.mjs';
15
+ import {createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
16
+ const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
17
+ const at='2026-09-18T00:00:00.000Z';
18
+ const keys=['status','summaryDigest','at','features','specFiles','testCases','approval'];
19
+ function feature(specs,name='1.guide'){
20
+ const target=path.join(specs,name);fs.mkdirSync(target,{recursive:true});
21
+ const docs=[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Read guide'},
22
+ {path:'design.md',content:'## 方案摘要\nDocumentation'},{path:'tasks.md',content:'- [ ] T-001: Guide'}];
23
+ for(const doc of docs)fs.writeFileSync(path.join(target,doc.path),doc.content);
24
+ return docs;
25
+ }
26
+ function fixture(t){
27
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-specs-status-')));
28
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
29
+ const specs=path.join(root,'specs'),code=path.join(root,'code');
30
+ fs.mkdirSync(specs);fs.mkdirSync(code);fs.writeFileSync(path.join(code,'README.md'),'existing');feature(specs);
31
+ const target=path.join(specs,'.cm-specs-status');
32
+ const raw=value=>fs.writeFileSync(target,JSON.stringify(value));
33
+ const value=()=>JSON.parse(fs.readFileSync(target,'utf8'));
34
+ const run=(...args)=>{
35
+ const child=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,...args],{encoding:'utf8'});
36
+ assert.equal(child.signal,null,child.stderr);
37
+ return {exit:child.status,result:child.stdout?JSON.parse(child.stdout):null,stderr:child.stderr};
38
+ };
39
+ const initial=(status='awaiting_review')=>({status,summaryDigest:'A1'.repeat(32),at,features:['1.guide'],
40
+ specFiles:buildManifest(specs),testCases:[],approval:null});
41
+ return {root,specs,code,target,raw,value,run,initial};
42
+ }
43
+
44
+ test('shared status storage roundtrips canonically and reads legacy metadata without granting authority',t=>{
45
+ const f=fixture(t),expected=f.initial();
46
+ assert.deepEqual(readSpecsStatus(f.specs),{kind:'missing'});
47
+ assert.deepEqual(writeSpecsStatus(f.specs,expected),expected);
48
+ assert.deepEqual(readSpecsStatus(f.specs),{kind:'valid',value:expected});
49
+ assert.deepEqual(Object.keys(f.value()),keys);
50
+ if(process.platform!=='win32')assert.equal(fs.statSync(f.target).mode&0o777,0o600);
51
+ const old={...expected,status:'approved',via:'old top-level metadata',approval:{response:'开始',at,via:'old model',runtime:'old'}};
52
+ f.raw(old);const read=readSpecsStatus(f.specs);
53
+ assert.equal(read.kind,'valid');assert.equal(read.value.via,undefined);
54
+ assert.deepEqual(read.value.approval,{response:'开始',at});
55
+ writeSpecsStatus(f.specs,read.value);
56
+ assert.deepEqual(Object.keys(f.value()),keys);assert.equal(JSON.stringify(f.value()).includes('via'),false);
57
+ const before=fs.readFileSync(f.target);
58
+ assert.throws(()=>writeSpecsStatus(f.specs,{...expected,approval:{response:'开始',at}}),/spec_status_invalid/);
59
+ assert.deepEqual(fs.readFileSync(f.target),before);
60
+ assert.throws(()=>writeSpecsStatus(f.specs,expected,{beforeRename:()=>{throw new Error('inputs_changed');}}),/inputs_changed/);
61
+ assert.deepEqual(fs.readFileSync(f.target),before);
62
+ assert.deepEqual(fs.readdirSync(f.specs).sort(),['.cm-specs-status','1.guide']);
63
+ fs.unlinkSync(f.target);const external=path.join(f.root,'outside.json');fs.writeFileSync(external,JSON.stringify(expected));
64
+ fs.symlinkSync(external,f.target);assert.equal(readSpecsStatus(f.specs).kind,'invalid');
65
+ });
66
+
67
+ test('--approve writes only the three permitted reasons with explicit human input and reruns admission',t=>{
68
+ const f=fixture(t),approve=['--approve','--approval-response','开始'];
69
+ f.raw(f.initial());
70
+ assert.equal(f.run('--approval-response','开始').result.reason,'approval_write_required');
71
+ let result=f.run(...approve);assert.equal(result.exit,0);assert.equal(result.result.state,'ready');
72
+ assert.deepEqual(Object.keys(f.value()),keys);assert.equal(f.value().approval.response,'开始');
73
+ assert.equal(f.value().approval.at,f.value().at);
74
+ feature(f.specs,'2.appendix');
75
+ assert.equal(f.run('--approval-response','开始').result.reason,'spec_features_changed');
76
+ result=f.run(...approve);assert.equal(result.exit,0);assert.equal(result.result.state,'ready');
77
+ assert.deepEqual(f.value().features,['1.guide','2.appendix']);assert.deepEqual(f.value().specFiles,buildManifest(f.specs));
78
+ // Legacy stale testCases reaches the third allowlisted reason without spec drift.
79
+ f.raw({...f.value(),testCases:[{path:'1.guide/test-cases.json',sha256:'b'.repeat(64)}]});
80
+ assert.equal(f.run('--approval-response','开始').result.reason,'test_cases_changed');
81
+ result=f.run(...approve);assert.equal(result.exit,0);assert.equal(result.result.state,'ready');
82
+ for(const args of [['--approve','--yes'],['--approve','--approval-response','继续'],['--approve']]){
83
+ f.raw({...f.value(),status:'awaiting_review',approval:null});const before=fs.readFileSync(f.target);
84
+ const original=f.run(...args.filter(arg=>arg!=='--approve')).result;
85
+ result=f.run(...args);assert.equal(result.exit,1);assert(result.result.approveRefused);
86
+ const {approveRefused,...rest}=result.result;assert.deepEqual(rest,original);
87
+ assert.deepEqual(fs.readFileSync(f.target),before);
88
+ }
89
+ result=f.run(...approve);assert.equal(result.result.state,'ready');
90
+ for(const args of [approve,['--approve','--yes','--approval-response','开始'],[...approve,'--code-project',path.join(f.root,'missing')]]){
91
+ const before=fs.readFileSync(f.target);result=f.run(...args);assert.notEqual(result.exit,0);
92
+ assert.deepEqual(fs.readFileSync(f.target),before);
93
+ }
94
+ fs.appendFileSync(path.join(f.specs,'1.guide/design.md'),'\nChanged design');
95
+ const before=fs.readFileSync(f.target),original=f.run('--approval-response','开始').result;
96
+ assert.equal(original.reason,'spec_drift');assert.equal(original.state,'blocked');
97
+ result=f.run(...approve);assert.equal(result.exit,1);assert.equal(result.result.approveRefused,'spec_drift');
98
+ const {approveRefused,...rest}=result.result;assert.deepEqual(rest,original);
99
+ assert.deepEqual(fs.readFileSync(f.target),before);
100
+ });
101
+
102
+ test('cm-prd summary digest survives approval exactly and legacy absence becomes null',async t=>{
103
+ const f=fixture(t),docs=feature(f.specs),name='1.guide';fs.mkdirSync(path.join(f.specs,'.reviews'));
104
+ const prepared=preparePrdReview({specs:f.specs,stage:'split',feature:name,
105
+ draft:{draftDigest:'a'.repeat(64),features:[{name:'guide',directory:name,documents:docs}]}});
106
+ claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest});
107
+ publishPrdReview({specs:f.specs,reviewPackage:prepared.reviewPackage,packageDigest:prepared.packageDigest,authorContextId:'author',
108
+ response:{reviewer:'codex-subagent',contextId:'fixture-reviewer',independent:true,at,
109
+ result:{verdict:'approved',packageDigest:prepared.packageDigest,examinedPaths:docs.map(doc=>`${name}/${doc.path}`).sort(),
110
+ findings:[],summary:'Synthetic fixture review; not a real independent review'}}});
111
+ recordPrdHostDisposition({specs:f.specs,stage:'split',feature:name,packageDigest:prepared.packageDigest,decisions:[],writeEnabled:true,
112
+ artifacts:docs.map(doc=>({path:`${name}/${doc.path}`,sha256:createHash('sha256').update(doc.content).digest('hex')}))});
113
+ const summary=await createPrdSummaryOwner({summarize:async({evidenceDigest})=>({evidenceDigest,
114
+ deliveryForm:'Documentation',estimatedTime:'Unknown',openQuestions:'None in fixture',risks:'Synthetic',contextScope:'Targeted',
115
+ platformReadiness:'Not applicable',uiBaseline:'None',designRisk:[{feature:name,
116
+ signals:{greenfieldAdr:false,architectureOrDataFlow:false,newRuntimeDependencyOrToolchain:false,publicContractDataOrSecurity:false,fiveOrMoreFunctions:false},
117
+ evidence:['Synthetic documentation fixture']}]})})(f.specs);
118
+ assert.equal(summary.readyForAwaitingReview,true);
119
+ assert.equal(publishPrdAwaitingReview({specs:f.specs,summary,writeEnabled:true}).status,'awaiting_review');
120
+ assert.equal(f.value().summaryDigest,summary.summaryDigest);assert.equal(f.value().approval,null);
121
+ const approve=()=>f.run('--approve','--approval-response',' 开始 ');
122
+ assert.equal(approve().result.state,'ready');assert.equal(f.value().summaryDigest,summary.summaryDigest);
123
+ assert.equal(f.value().approval.response,' 开始 ');
124
+ // Uppercase hex must not be normalized either.
125
+ f.raw({...f.initial(),summaryDigest:'AB'.repeat(32)});
126
+ assert.equal(approve().result.state,'ready');assert.equal(f.value().summaryDigest,'AB'.repeat(32));
127
+ const legacy=f.initial();delete legacy.summaryDigest;delete legacy.approval;f.raw(legacy);
128
+ assert.equal(approve().result.state,'ready');assert.equal(f.value().summaryDigest,null);
129
+ fs.unlinkSync(f.target);assert.equal(approve().result.state,'ready');assert.equal(f.value().summaryDigest,null);
130
+ });
@@ -345,6 +345,10 @@ function validateEffective(config){
345
345
  validateRuntimeDeclaration(config);
346
346
  if(!Array.isArray(config.policies.tests)||config.policies.tests.length===0)throw new ConfigError('policies.tests must be a non-empty list');
347
347
  if(config.policies.tests.some(item=>typeof item!=='string'||!TEST_KINDS.has(item)))throw new ConfigError('policies.tests contains an unsupported test kind');
348
+ // Reverse coherence: declaring browser tests requires the role that serves them.
349
+ // The existing rule only prevents other roles from claiming the browser adapter.
350
+ if(config.policies.tests.includes('browser')&&config.roles.browser_qa?.adapter!=='browser')
351
+ throw new ConfigError('policies.tests includes browser but roles.browser_qa.adapter is not browser');
348
352
  if(typeof config.policies.generate_cases!=='boolean')throw new ConfigError('policies.generate_cases must be boolean');
349
353
  requireString(config.policies.auto_fix,'policies.auto_fix',AUTO_FIX_POLICIES);
350
354
  requireString(config.policies.delivery,'policies.delivery',DELIVERY_MODES);
File without changes
@@ -13,7 +13,7 @@
13
13
  只接受其结构化 `state`、`reason`、`features`、`nextTask` 作为 N1/N2 选择结果;非零退出或
14
14
  `state: blocked` 必须停止,不能退回人工目测放行。多个代码项目逐一经过同一 admission,
15
15
  任一项目阻断或下一任务不一致时整体阻断。若规格尚待审批,先按下方入口闸取得真实
16
- 人工决定并更新 `.cm-specs-status`,然后重新运行本命令;普通“继续”不得改写审批状态。
16
+ 人工决定并调用下方 `--approve` 写入口(内部会重跑准入);普通“继续”不得改写审批状态。
17
17
  2. 使用 admission 返回的编号 feature 顺序,不再另写一套扫描/依赖选择规则;进入
18
18
  每个 feature 时保存完整目录名为 `FEATURE_DIR`(如 `1.login`),仅把去掉编号的
19
19
  名称保存为 `FEATURE_SLUG`(如 `login`)。前者只用于规格文件路径,后者用于
@@ -41,23 +41,28 @@
41
41
 
42
42
  ## 规格审批入口闸(先于一切预检)
43
43
 
44
- 读取 `{SPECS_DIR}/.cm-specs-status`:
44
+ 以 JS admission 的结果为准;模型不得自行拼写或修改 `.cm-specs-status`:
45
45
 
46
- - `approved` → 直接继续(断点续跑不重复问)
47
- - `awaiting_review` 或文件缺失(旧版 specs)→ 把规格摘要卡打给用户(specs 里没有摘要卡就现场汇总:feature 数/任务数/交付形态/风险点),**等用户明确回复"开始"**;回复后运行 `cm-spec-manifest.py`,把当前 `specFiles` 写入状态并更新为 `approved`。**泛化授权语不构成审批**("按最优解处理""继续""你看着办"这类话授权的是执行方式,不是规格内容)——收到时必须回问一次:"规格摘要卡确认开始吗?"(实跑失守:diff-lens 把"按照你分析的最优解去处理"直接视为审批通过)
48
- - 已是 `approved` 但缺少 `specFiles`(旧版审批位)→ 无法证明批准的是当前三件套;展示一次摘要卡并重新取得明确“开始”,随后补全 manifest。不得静默背书。
49
- - 启动参数含 `--yes` → 跳过此问直接基于当前文件生成 manifest 并更新为 approved(只适合刚人审完立刻开跑的场景)
46
+ - `ready` / `complete` → 沿用现有准入结果;旧版无 `specFiles` 的文件仍可读取,不在本节点自行补造批准证据。
47
+ - `awaiting_spec_approval` → 展示规格摘要卡(无卡时可现场汇总,但不得据此生成或替换 `summaryDigest`),等用户明确回复“开始”。泛化授权语(“继续”“按最优解处理”“你看着办”)不构成审批,须回问“规格摘要卡确认开始吗?”(实跑失守:泛化授权曾被误视为审批通过)。
48
+ - 取得明确回复后运行以下写入口,`--approval-response` 传用户原话;多个代码项目全部传入:
50
49
 
51
- 只有实际把状态从非 approved 改为 approved 时才写
52
- `spec_lifecycle/approved`;已有 approved 状态不重复伪造审批事件。
50
+ ```bash
51
+ node "{CM_WORKFLOW_ROOT}/scripts/cm-ai-admission.mjs" \
52
+ --specs-dir "{SPECS_DIR}" --code-project "{CODE_PROJECT_ONE}" \
53
+ [--code-project "{CODE_PROJECT_TWO}" ...] \
54
+ --approve --approval-response "{用户原话}"
55
+ ```
53
56
 
54
- 批准后真跑
55
- `python3 {CM_WORKFLOW_ROOT}/scripts/cm-spec-manifest.py {SPECS_DIR} --status-file {SPECS_DIR}/.cm-specs-status`。
56
- 任一 requirements/design/tasks/test-cases 新增、删除或**规格语义哈希**变化 → 将状态
57
- 恢复为 `awaiting_review`,写 `spec_lifecycle/changed` 并要求用 `$cm-prd --change`
58
- 说明变更。N5/N6 将明确的任务与 AC checkbox 从 `[ ]` 改为 `[x]` 属于运行状态,
59
- `cm-spec-manifest.py` 会规范化后比较,不得把正常进度误判成规格漂移;文案、ID、
60
- `[DROPPED]`/`[CHANGED]`、普通 checklist、设计和测试合同仍须完整保护。
57
+ - `--approve` 不接受 `--yes`;只读调用的 `--yes` 也不写审批位。
58
+ - 只有 `awaiting_spec_approval` + `explicit` 且 reason 为 `approval_write_required`、`spec_features_changed` 或 `test_cases_changed` 才写;其余返回原准入结果及 `approveRefused`,不得手改 JSON 绕过。
59
+ - `blocked/spec_drift` → 保留原状态,要求用 `$cm-prd --change` 说明变更并重新发布摘要;不得自动改成 `awaiting_review` 或刷新 manifest。manifest 先于测试合同校验,测试合同修改也可能先触发 `spec_drift`。
60
+
61
+ 共享 JS writer 生成 `features`、`specFiles`、`testCases` 和审批记录,原样沿用旧 `summaryDigest`,缺失时写 `null`。
62
+ 写完返回重跑准入的结果;只有 `ready` 才进入开发,写成 approved 不代表其他检查已通过。
63
+ 只有本次审批写入成功才记录 `spec_lifecycle/approved`;拒绝或只读查询不伪造审批事件。
64
+ 需要单独核验批准 manifest 时,可只读运行 `python3 {CM_WORKFLOW_ROOT}/scripts/cm-spec-manifest.py {SPECS_DIR} --status-file {SPECS_DIR}/.cm-specs-status`;失败不授权改写。
65
+ N5/N6 的任务与 AC checkbox 变化仍由现有 manifest 规范化处理,文案、ID、设计和测试合同变化继续受准入保护。
61
66
 
62
67
  > 这是**入口授权门**(人把关方案端),不属于"暂停仅灾难级"约束的中途暂停,也不计入 METRICS 人工介入。实跑教训:没有这道闸,prd 生成完会被一句"继续"顺势带进开发,人审形同虚设。
63
68
 
@@ -12,6 +12,10 @@ commands/logic 及 API、数据库回归;`web-frontend` 优先 commands/browse
12
12
  类型;`test-cases.json` 中 blocking case 即使类型未列出也必须执行,环境不可用则
13
13
  `BLOCKED`,不得把配置当作跳过已审批验收的许可。
14
14
 
15
+ feature 未完成时,只执行 taskIds 全部已完成且未 dropped 的用例,其余记入 `deferred_cases`,延后到 feature 收尾;延后用例不计入执行数量,也不派发宿主请求。feature 中途无可执行项时产生一条显式 `BLOCKED` 行,id 为 `no-applicable-cases`,不得以零测试宣称通过。
16
+
17
+ 最新已 complete 的 QA 若为纯宿主/环境证据 BLOCKED、failed=0 且 qaRound<3,可按 [JS 宿主入口](js-host.md) 显式 `--rerun-blocked-qa --allow-qa` 恢复,以 superseded 关联下一轮全量重跑;产品 FAIL、commands 阻断与未 complete 不适用,完成后同步 N6 状态镜像。
18
+
15
19
  ## 评分(1-5 分,总分 ≥ 8 触发)
16
20
 
17
21
  | 维度 | 1 分 | 5 分 |
@@ -27,7 +31,7 @@ commands/logic 及 API、数据库回归;`web-frontend` 优先 commands/browse
27
31
  - API 接口变更(**收尾合并豁免**:下一个任务就是本 feature 最后一个任务时,可合并至 feature 级 QA 一次执行——避免背靠背双跑全量;合并决策记运行日志 `decision` 事件。实跑教训:后端 feature 几乎每任务都改 API,逐任务触发 QA 成本失衡)
28
32
  - 数据库 migration
29
33
  - 认证/授权/支付逻辑
30
- - 连续 5 个 task 未触发过 QA
34
+ - 连续 5 个 task 未触发过 QA(缺少 N6 历史行的计数仅含尚未完成 feature 的已完成任务;自上次 triggered 以来的 skipped 任务语义不变)
31
35
 
32
36
  ## 跳过
33
37
 
@@ -57,11 +61,12 @@ QA 新增或修正测试也属于该 fix diff,不能在旁路写入。修复
57
61
  审查、提交与日志证据。
58
62
 
59
63
  实际触发 QA 时按 `../../../runtime/logging.md` 写 `test_run/start` 与
60
- `test_run/complete`,只记录模式、用例/通过/失败/阻塞数量、结论和报告路径;
64
+ `test_run/complete`,记录模式、用例/通过/失败/阻塞数量、结论和报告路径;start 与固定执行报告另列 `deferred_cases`(id 与未完成 taskIds);
61
65
  测试输出、截图和浏览器日志仍留在 `.reviews/`。
62
66
 
63
- feature 存在 `test-cases.json` 时按 `runtime/test-contract.md` 消费:正式项目命令
64
- 仍照常执行;browser cases 由 `cm-qa-engineer` 逐条模拟并保存截图/日志;
67
+ feature 存在 `test-cases.json` 时按 `runtime/test-contract.md` 消费:中途 QA 的命令按
68
+ 选中 logic 用例映射,无用例映射的独立命令沿用配置策略;browser cases 由
69
+ `cm-qa-engineer` 逐条模拟并保存截图/日志;
65
70
  N4 中的 `INSUFFICIENT_EVIDENCE` 必须在本节点补运行时证据或保持 `BLOCKED`。
66
71
  任一 blocking case 为 `FAIL`/`BLOCKED` 时不得宣称 QA 通过。
67
72