@aibyzero/cm-workflow 0.12.0 → 0.13.3

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 (121) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +60 -1
  4. package/README.md +36 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/docs/installation.md +58 -1
  8. package/docs/js-workflow-control.md +63 -6
  9. package/docs/runtime-failover.md +97 -0
  10. package/docs/user-guide.md +50 -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 +9 -2
  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 +527 -6
  60. package/scripts/cm-ai-multi-root.test.mjs +16 -4
  61. package/scripts/cm-ai-nested-execution.test.mjs +18 -5
  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 +8 -2
  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-fix-host-review.test.mjs +7 -1
  77. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  78. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  79. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  80. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  81. package/scripts/cm-init-host.mjs +4 -4
  82. package/scripts/cm-init-host.test.mjs +12 -7
  83. package/scripts/cm-init-session.test.mjs +50 -0
  84. package/scripts/cm-log-event.mjs +34 -5
  85. package/scripts/cm-prd-completion.test.mjs +9 -3
  86. package/scripts/cm-prd-host.mjs +39 -3
  87. package/scripts/cm-prd-host.test.mjs +52 -0
  88. package/scripts/cm-prd-review-gate.mjs +11 -2
  89. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  90. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  91. package/scripts/cm-prd-summary.test.mjs +147 -0
  92. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  93. package/scripts/cm-review-inventory.test.mjs +189 -0
  94. package/scripts/cm-review-schema.test.mjs +35 -1
  95. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  96. package/scripts/cm-runtime-edit.mjs +104 -0
  97. package/scripts/cm-runtime-failover.test.mjs +130 -0
  98. package/scripts/cm-runtime-i18n.mjs +32 -0
  99. package/scripts/cm-runtime-install.mjs +68 -0
  100. package/scripts/cm-runtime.mjs +141 -0
  101. package/scripts/cm-runtime.test.mjs +218 -0
  102. package/scripts/cm-spec-manifest.mjs +24 -21
  103. package/scripts/cm-spec-manifest.test.mjs +19 -0
  104. package/scripts/cm-workflow-config.mjs +113 -5
  105. package/scripts/cm-workflow-config.test.mjs +124 -1
  106. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  107. package/scripts/test-cm-prd-review-gate.py +30 -0
  108. package/scripts/test-shell-compat.sh +34 -0
  109. package/scripts/validate-public-repo.py +5 -0
  110. package/skills/cm-ai/references/N4-review.md +5 -4
  111. package/skills/cm-ai/references/js-host.md +36 -2
  112. package/skills/cm-check/SKILL.md +7 -3
  113. package/skills/cm-init/SKILL.md +4 -0
  114. package/skills/cm-init/references/js-host.md +2 -0
  115. package/skills/cm-init/references/runtime-declaration.md +26 -0
  116. package/skills/cm-prd/SKILL.md +3 -3
  117. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  118. package/skills/cm-prd/references/summary-card.md +7 -0
  119. package/skills/cm-runtime/SKILL.md +53 -0
  120. package/templates/auto-update/cm-update.sh +1 -1
  121. package/templates/cm-workflow.yml +16 -0
@@ -0,0 +1,130 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {ROLE_ROUTING,selectRuntime,candidateOrder,describeSelection,isRuntime,
4
+ RuntimeFailoverError} from '../runtime/js/cm-ai/runtime-failover.mjs';
5
+
6
+ const all=()=>true, none=()=>false, only=(runtime)=>(candidate)=>candidate===runtime;
7
+
8
+ test('角色主从表:开发主 codex,审查主 claude,且主备互异',()=>{
9
+ assert.equal(ROLE_ROUTING.developer.primary,'codex');
10
+ assert.equal(ROLE_ROUTING.developer.standby,'claude');
11
+ assert.equal(ROLE_ROUTING.reviewer.primary,'claude');
12
+ assert.equal(ROLE_ROUTING.reviewer.standby,'codex');
13
+ for(const {primary,standby} of Object.values(ROLE_ROUTING)){
14
+ assert.ok(isRuntime(primary)&&isRuntime(standby));
15
+ assert.notEqual(primary,standby);
16
+ }
17
+ });
18
+
19
+ test('路由表被冻结,调用方不能就地改写主从',()=>{
20
+ assert.throws(()=>{ROLE_ROUTING.developer={primary:'claude',standby:'codex'};},TypeError);
21
+ assert.throws(()=>{ROLE_ROUTING.reviewer.primary='codex';},TypeError);
22
+ });
23
+
24
+ test('候选顺序:显式请求优先,另一端永远兜底',()=>{
25
+ assert.deepEqual(candidateOrder('developer'),['codex','claude']);
26
+ assert.deepEqual(candidateOrder('reviewer'),['claude','codex']);
27
+ assert.deepEqual(candidateOrder('reviewer','codex'),['codex','claude']);
28
+ assert.deepEqual(candidateOrder('developer','claude'),['claude','codex']);
29
+ });
30
+
31
+ test('两端都可用时不切换,且如实标记 switched=false',()=>{
32
+ const dev=selectRuntime({role:'developer',probe:all});
33
+ assert.equal(dev.runtime,'codex');assert.equal(dev.switched,false);assert.equal(dev.reason,null);
34
+ const review=selectRuntime({role:'reviewer',probe:all});
35
+ assert.equal(review.runtime,'claude');assert.equal(review.switched,false);
36
+ });
37
+
38
+ test('主端不可达时切到备端并带上切换原因',()=>{
39
+ const review=selectRuntime({role:'reviewer',probe:only('codex')});
40
+ assert.equal(review.runtime,'codex');
41
+ assert.equal(review.switched,true);
42
+ assert.equal(review.from,'claude');
43
+ assert.match(review.reason,/claude unreachable/);
44
+ assert.deepEqual(review.rejected,[{runtime:'claude',reason:'unreachable'}]);
45
+ });
46
+
47
+ test('显式请求的运行时不可用时,切换以请求端为起点',()=>{
48
+ const dev=selectRuntime({role:'developer',requested:'claude',probe:only('codex')});
49
+ assert.equal(dev.runtime,'codex');assert.equal(dev.from,'claude');assert.equal(dev.switched,true);
50
+ });
51
+
52
+ test('allowed 收窄时不越界选路(单家声明只允许 codex)',()=>{
53
+ const review=selectRuntime({role:'reviewer',allowed:['codex'],probe:all});
54
+ assert.equal(review.runtime,'codex');
55
+ assert.equal(review.switched,true);
56
+ assert.deepEqual(review.rejected,[{runtime:'claude',reason:'not_allowed'}]);
57
+ });
58
+
59
+ test('两端都不可用时抛错,绝不返回不可用的运行时',()=>{
60
+ assert.throws(()=>selectRuntime({role:'developer',probe:none}),
61
+ (error)=>error instanceof RuntimeFailoverError&&error.code==='no_runtime_available'
62
+ &&/codex=unreachable/.test(error.message)&&/claude=unreachable/.test(error.message));
63
+ });
64
+
65
+ test('allowed 排除主端且备端不可达时同样阻塞',()=>{
66
+ assert.throws(()=>selectRuntime({role:'reviewer',allowed:['codex'],probe:none}),
67
+ /no runtime available for reviewer/);
68
+ });
69
+
70
+ test('非法输入被拒绝而不是回退到默认值',()=>{
71
+ assert.throws(()=>selectRuntime({role:'qa',probe:all}),/unknown failover role/);
72
+ assert.throws(()=>selectRuntime({role:'developer',requested:'gemini',probe:all}),/unsupported runtime/);
73
+ assert.throws(()=>selectRuntime({role:'developer',probe:null}),/probe must be a function/);
74
+ assert.throws(()=>selectRuntime({role:'developer',probe:()=>'yes'}),/probe must return a boolean/);
75
+ assert.throws(()=>selectRuntime({role:'developer',allowed:[],probe:all}),/non-empty list/);
76
+ assert.throws(()=>selectRuntime({role:'developer',allowed:['gemini'],probe:all}),/non-empty list/);
77
+ });
78
+
79
+ test('切换必须可读地播报,不能静默',()=>{
80
+ assert.equal(describeSelection(selectRuntime({role:'developer',probe:all})),
81
+ 'developer: codex(未切换)');
82
+ assert.equal(describeSelection(selectRuntime({role:'reviewer',probe:only('codex')})),
83
+ 'reviewer: claude → codex(原因: claude unreachable)');
84
+ });
85
+
86
+ test('探测只调用到选中候选为止,不做多余探测',()=>{
87
+ const seen=[];
88
+ selectRuntime({role:'developer',probe:(runtime)=>{seen.push(runtime);return true;}});
89
+ assert.deepEqual(seen,['codex']);
90
+ });
91
+
92
+ // --- host 接线 ---
93
+ import {main as hostMain} from './cm-ai-host.mjs';
94
+
95
+ function runHost(argv){
96
+ const chunks=[];
97
+ const sink={write:(text)=>{chunks.push(text);return true;}};
98
+ return hostMain(argv,{input:process.stdin,output:sink,error:sink})
99
+ .then(code=>({code,text:chunks.join('')}));
100
+ }
101
+
102
+ const base=['serve','--config','/nonexistent.json','--mode','create',
103
+ '--host-context','h1','--allow-development'];
104
+
105
+ test('--failover 与 --protected-config 互斥(protected 预先绑定两家角色)',async()=>{
106
+ const {code,text}=await runHost([...base,'--failover','--protected-config','/nonexistent2.json']);
107
+ assert.equal(code,1);
108
+ assert.match(text,/failover_unsupported_in_protected_mode/);
109
+ });
110
+
111
+ test('--failover 是布尔开关,不吞掉后面的参数',async()=>{
112
+ // --allow-qa 未配 workflow.qa 时必须报 invalid_arguments;若 --failover 把它
113
+ // 当成取值吞掉,这条检查就不会触发,测试随之失败。
114
+ const {code,text}=await runHost([...base,'--failover','--allow-qa']);
115
+ assert.equal(code,1);
116
+ assert.match(text,/invalid_arguments/);
117
+ assert.doesNotMatch(text,/failover_unsupported/);
118
+ });
119
+
120
+ test('不传 --failover 时不进入选路,既有行为不变',async()=>{
121
+ const {code,text}=await runHost([...base,'--protected-config','/nonexistent2.json']);
122
+ assert.equal(code,1);
123
+ assert.doesNotMatch(text,/failover/);
124
+ });
125
+
126
+ test('未知参数仍被拒绝,--failover 没有放宽参数白名单',async()=>{
127
+ const {code,text}=await runHost([...base,'--failover-now']);
128
+ assert.equal(code,1);
129
+ assert.match(text,/invalid_arguments/);
130
+ });
@@ -0,0 +1,32 @@
1
+ // Human-readable runtime text only; persisted keys and preset identifiers stay stable.
2
+ export function runtimeLanguage(env=process.env,intlLocale=()=>Intl.DateTimeFormat().resolvedOptions().locale){
3
+ if(['zh','en'].includes(env.CM_WORKFLOW_LANG))return env.CM_WORKFLOW_LANG;
4
+ const locale=env.LC_ALL||env.LC_MESSAGES||env.LANG;
5
+ if(locale)return /^zh/i.test(locale)?'zh':'en';
6
+ try{return /^zh/i.test(intlLocale()||'')?'zh':'en';}catch{return 'en';}
7
+ }
8
+ export const messages={
9
+ tools:{zh:'你手上有哪个 AI 工具?[1] 只有 Codex [2] 只有 Claude [3] 两个都有: ',en:'Which AI tools do you have? [1] Codex only [2] Claude only [3] Both: '},
10
+ coder:{zh:'谁写代码?[1] Codex(Claude 审,推荐) [2] Claude(Codex 审): ',en:'Who writes code? [1] Codex (Claude reviews, recommended) [2] Claude (Codex reviews): '},
11
+ scope:{zh:'改哪一层?[1] 当前项目({project}) [2] 用户级默认({user}) [{default}]: ',en:'Which scope? [1] Current project ({project}) [2] User default ({user}) [{default}]: '},
12
+ create:{zh:'将从模板新建项目配置:{file}\n',en:'Will create project configuration from the template: {file}\n'},
13
+ current:{zh:'当前用户级默认: {available} / {preset}\n',en:'Current user default: {available} / {preset}\n'},
14
+ invalid:{zh:'当前用户级默认无效: {error}\n',en:'Invalid user default: {error}\n'},
15
+ keep:{zh:'保留?[Y/n] ',en:'Keep it? [Y/n] '},
16
+ preview:{zh:'将写入: {file}\n预设: {preset}\n当前值:\n{current}\n',en:'Will write: {file}\nPreset: {preset}\nCurrent value:\n{current}\n'},
17
+ absent:{zh:'未声明',en:'Undeclared'},
18
+ confirm:{zh:'确认?[Y/n] ',en:'Confirm? [Y/n] '},
19
+ cancelled:{zh:'已放弃,未修改运行时声明。\n',en:'Cancelled; runtime declaration unchanged.\n'},
20
+ installed:{zh:'✓ 用户级运行时默认已写入 {file} ({preset})\n',en:'✓ User runtime default saved to {file} ({preset})\n'},
21
+ comment:{zh:'用 cm-runtime set --user <preset> 修改用户级默认。',en:'Use cm-runtime set --user <preset> to change the user default.'},
22
+ declared:{zh:'(已声明未派发)',en:' (declared, not dispatched)'},
23
+ cli:{zh:'{runtime} CLI: 可解析(可解析≠配额可用)',en:'{runtime} CLI: resolvable (presence does not prove quota)'},
24
+ warning:{zh:'WARN: runtimes.available 声明 {available},但本机 {runtime} CLI 不可解析(可解析≠配额可用)',en:'WARN: runtimes.available declares {available}, but {runtime} CLI is not resolvable (presence does not prove quota)'},
25
+ saved:{zh:'已保存 {file}: {preset} ({source});已有 run 不变',en:'Saved {file}: {preset} ({source}); existing runs unchanged'},
26
+ removed:{zh:'已删除用户默认: {file};项目声明仍优先',en:'Removed user default: {file}; project declarations still take precedence'},
27
+ help:{zh:'cm-runtime [--project PATH]:无参数在 TTY 下进入交互向导;非 TTY 显示用法并退出 2。',en:'cm-runtime [--project PATH]: no command opens the interactive wizard in a TTY; non-TTY prints usage and exits 2.'},
28
+ failed:{zh:'运行时声明未完成: {error}',en:'Runtime declaration incomplete: {error}'},
29
+ };
30
+ export function runtimeText(key,lang=runtimeLanguage(),values={}){
31
+ return messages[key][lang].replace(/\{(\w+)\}/g,(_,name)=>String(values[name]??`{${name}}`));
32
+ }
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ // Shared post-install prompt. Skipped on --yes or redirected input/output.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {createInterface} from 'node:readline';
7
+ import {userRuntimesPath,readConfigText,parseUserRuntimes} from './cm-workflow-config.mjs';
8
+ import {writeUserRuntime} from './cm-runtime.mjs';
9
+ import {runtimeLanguage,runtimeText as t} from './cm-runtime-i18n.mjs';
10
+
11
+ export class PromptCancelled extends Error {}
12
+ // Queue lines so injected streams and pasted answers cannot lose later responses.
13
+ export function runtimeQuestions(input,output,lang=runtimeLanguage()){
14
+ const rl=createInterface({input,output,terminal:false});
15
+ const queue=[];let pending=null,closed=false,cancelled=false;
16
+ rl.on('line',line=>{if(pending){const resolve=pending;pending=null;resolve(line);}else queue.push(line);});
17
+ const close=()=>{closed=true;if(pending){pending(null);pending=null;}};
18
+ rl.on('close',close);
19
+ const interrupt=()=>{cancelled=true;queue.length=0;rl.close();close();};
20
+ rl.on('SIGINT',interrupt);process.on('SIGINT',interrupt);
21
+ return {
22
+ async ask(question){
23
+ if(cancelled||closed&&!queue.length)throw new PromptCancelled();
24
+ output.write(question);
25
+ const answer=queue.length?queue.shift():await new Promise(resolve=>{pending=resolve;});
26
+ if(answer===null||cancelled)throw new PromptCancelled();
27
+ return answer.trim();
28
+ },
29
+ close(){process.removeListener('SIGINT',interrupt);rl.close();},
30
+ };
31
+ }
32
+ export async function askRuntimePreset(ask,lang=runtimeLanguage()){
33
+ let choice,empty=0;
34
+ do{
35
+ choice=await ask(t('tools',lang));
36
+ if(choice===''){if(++empty===3)throw new PromptCancelled();}else empty=0;
37
+ }while(!['1','2','3'].includes(choice));
38
+ if(choice!=='3')return choice==='1'?'codex-only':'claude-only';
39
+ let coder;
40
+ do{coder=await ask(t('coder',lang));}while(!['','1','2'].includes(coder));
41
+ return coder==='2'?'claude-codes':'codex-codes';
42
+ }
43
+ export async function promptRuntime(argv=process.argv.slice(2),input=process.stdin,output=process.stdout){
44
+ const args=[...argv];let culture;
45
+ const index=args.indexOf('--lang');
46
+ if(index>=0){culture=args[index+1];if(!culture||culture.startsWith('--'))throw new Error('missing --lang value');args.splice(index,2);}
47
+ if(args.some(arg=>arg!=='--yes'))throw new Error('usage: cm-runtime-install.mjs [--yes] [--lang CULTURE]');
48
+ if(args.includes('--yes')||!input.isTTY||!output.isTTY)return;
49
+ const lang=runtimeLanguage({...process.env,...(culture?{LANG:culture}:{})});
50
+ const questions=runtimeQuestions(input,output,lang),ask=questions.ask;
51
+ try{
52
+ const file=userRuntimesPath();
53
+ if(fs.existsSync(file)){
54
+ try{
55
+ const current=parseUserRuntimes(readConfigText(file));
56
+ output.write(t('current',lang,{available:current.runtimes.available,preset:current.preset}));
57
+ }catch(error){output.write(t('invalid',lang,{error:error.message}));}
58
+ const keep=await ask(t('keep',lang));
59
+ if(keep!=='n'&&keep!=='N')return;
60
+ }
61
+ const preset=await askRuntimePreset(ask,lang);
62
+ output.write(t('installed',lang,{file:writeUserRuntime(preset,{lang}),preset}));
63
+ }catch(error){if(error instanceof PromptCancelled)output.write(t('cancelled',lang));else throw error;}
64
+ finally{questions.close();}
65
+ }
66
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
67
+ try{await promptRuntime();}catch(error){console.error(t('failed',undefined,{error:error.message}));process.exitCode=1;}
68
+ }
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ // Standalone runtime preferences; never mutates an existing run or dispatches AI.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {ConfigError,findConfig,loadConfig,readConfigText,parseUserRuntimes,
9
+ userRuntimesPath,runtimePreset,RUNTIME_PRESETS,resolveRole,runtimesSource} from './cm-workflow-config.mjs';
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';
14
+ import {probeRuntimes} from './cm-failover.mjs';
15
+
16
+ const scripts=path.dirname(fileURLToPath(import.meta.url));
17
+ function stat(file){try{return fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}}
18
+ function safeTarget(file){
19
+ const parent=path.dirname(file),dir=stat(parent),target=stat(file);
20
+ if(dir&&(dir.isSymbolicLink()||!dir.isDirectory()))throw new ConfigError(`refusing non-directory or symlink parent: ${parent}`);
21
+ if(target&&(target.isSymbolicLink()||!target.isFile()))throw new ConfigError(`refusing non-file or symlink target: ${file}`);
22
+ }
23
+ export function atomicRuntimeWrite(file,text,{before=null,privateFile=false}={}){
24
+ safeTarget(file);
25
+ fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
26
+ const temporary=path.join(path.dirname(file),`.runtimes-${randomUUID()}.tmp`);
27
+ try{
28
+ fs.writeFileSync(temporary,text,{flag:'wx',mode:privateFile?0o600:(stat(file)?.mode??0o644)&0o777});
29
+ safeTarget(file);
30
+ const current=stat(file)?fs.readFileSync(file):null;
31
+ if(before===null?current!==null:current===null||!current.equals(before))throw new ConfigError('configuration changed during edit; retry from current file');
32
+ fs.renameSync(temporary,file);
33
+ }finally{if(stat(temporary))fs.unlinkSync(temporary);}
34
+ }
35
+ export function writeUserRuntime(preset,{lang=runtimeLanguage()}={}){
36
+ const declaration=runtimePreset(preset),file=userRuntimesPath();
37
+ safeTarget(file);
38
+ const text=`# ${t('comment',lang)}\nruntimes: {available: ${declaration.runtimes.available}}\npreset: ${preset}\n`;
39
+ parseUserRuntimes(text);
40
+ atomicRuntimeWrite(file,text,{before:stat(file)?fs.readFileSync(file):null,privateFile:true});
41
+ return file;
42
+ }
43
+ function projectDirectory(raw){
44
+ const root=fs.realpathSync(path.resolve(raw));
45
+ if(!fs.statSync(root).isDirectory())throw new ConfigError('project must be a directory');
46
+ return root;
47
+ }
48
+ export function setProjectRuntime(project,preset){
49
+ const root=projectDirectory(project),declaration=runtimePreset(preset);
50
+ // Reject broken links/directories too, even though findConfig only finds files.
51
+ for(const name of ['.cm-workflow.yml','.cm-workflow.yaml','.cm-workflow.json'])safeTarget(path.join(root,name));
52
+ const existing=findConfig(root),file=existing??path.join(root,'.cm-workflow.yml');
53
+ const before=existing?fs.readFileSync(file):null;
54
+ const original=readConfigText(existing??path.join(scripts,'../templates/cm-workflow.yml'));
55
+ loadConfig({projectRoot:root,configPath:file,text:original});
56
+ const text=editRuntimeDeclaration(original,file,declaration);
57
+ loadConfig({projectRoot:root,configPath:file,text});
58
+ atomicRuntimeWrite(file,text,{before});return file;
59
+ }
60
+ export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',probe=probeRuntimes,lang=runtimeLanguage()}={}){
61
+ const config=loadConfig({projectRoot:project});
62
+ const preset=Object.keys(RUNTIME_PRESETS).find(name=>{
63
+ const value=runtimePreset(name);
64
+ return config.runtimes.available===value.runtimes.available
65
+ &&['coder','reviewer'].every(role=>['adapter','source'].every(field=>config.roles[role][field]===value.roles[role][field]));
66
+ })??(runtimesSource(config)==='none'?'none':'custom');
67
+ const lines=[`runtimes.available: ${config.runtimes.available}`,`preset: ${preset}`,`runtimes_source: ${runtimesSource(config)}`];
68
+ for(const role of ['coder','reviewer']){
69
+ const resolved=resolveRole(config,role,runtime);
70
+ lines.push(`${role}: adapter=${resolved.adapter} source=${resolved.source} route_state=${resolved.route_state}${resolved.route_state==='declared-adapter'?t('declared',lang):''}`);
71
+ }
72
+ const wanted=config.runtimes.available==='both'?['codex','claude']:config.runtimes.available==='unknown'?[]:[config.runtimes.available];
73
+ for(const result of probe(wanted))lines.push(result.available
74
+ ?t('cli',lang,{runtime:result.runtime})
75
+ :t('warning',lang,{available:config.runtimes.available,runtime:result.runtime}));
76
+ return lines.join('\n');
77
+ }
78
+ function logSet(preset,source,project){
79
+ // Reuse cm-log-event.mjs through its required Python platform lock adapter.
80
+ // No specs/run pointer: this decision is independent of any in-flight run.
81
+ const args=[path.join(scripts,'cm-log-event.py'),'--workflow','cm-runtime','--event','decision','--phase','route',
82
+ '--runtime','local','--project-root',project,'--detail','runtime preference set',
83
+ '--data-json',JSON.stringify({preset,source})];
84
+ for(const python of process.env.CM_PYTHON_BIN?[process.env.CM_PYTHON_BIN]:['python3','python']){
85
+ const result=spawnSync(python,args,{encoding:'utf8',timeout:30000,env:{...process.env,
86
+ CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME||path.join(path.dirname(userRuntimesPath()),'logs')}});
87
+ if(result.error?.code==='ENOENT')continue;
88
+ if(result.status===0)return;
89
+ throw new ConfigError(`preference saved, decision log failed: ${result.stderr?.trim()||result.error?.message||result.status}`);
90
+ }
91
+ throw new ConfigError('preference saved, decision log failed: Python 3.9+ lock adapter unavailable');
92
+ }
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;
97
+ try{
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;
125
+ for(let i=0;i<args.length;i++){
126
+ if(args[i]==='--user'&&!user){user=true;continue;}
127
+ if(args[i]==='--project'&&!projectSeen&&args[i+1]&&!args[i+1].startsWith('--')){project=args[++i];projectSeen=true;continue;}
128
+ if(command==='set'&&!preset&&!args[i].startsWith('--')){preset=args[i];continue;}
129
+ throw new ConfigError(USAGE);
130
+ }
131
+ if(user&&projectSeen)throw new ConfigError('--user cannot be combined with --project');
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;}
134
+ if(command==='set'&&preset){
135
+ saveRuntime(project,preset,user,lang,output);return 0;
136
+ }
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;}
138
+ throw new ConfigError(USAGE);
139
+ }catch(error){console.error(`cm-runtime: ${error.message}`);return 1;}
140
+ }
141
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=await main();
@@ -0,0 +1,218 @@
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 {loadConfig,runtimePreset,runtimesSource,resolveRole,MAX_CONFIG_BYTES} from './cm-workflow-config.mjs';
9
+ import {setProjectRuntime,writeUserRuntime,showRuntime} from './cm-runtime.mjs';
10
+ import {editRuntimeDeclaration} from './cm-runtime-edit.mjs';
11
+ import {json as strictJson} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+
13
+ const scripts=path.dirname(fileURLToPath(import.meta.url));
14
+ function fixture(fn){
15
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-runtime-')));
16
+ const old=process.env.CM_WORKFLOW_HOME;
17
+ process.env.CM_WORKFLOW_HOME=path.join(root,'user');
18
+ const env={...process.env,HOME:root,CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
19
+ const run=(...args)=>spawnSync(process.execPath,[path.join(scripts,'cm-runtime.mjs'),...args],{cwd:root,env,encoding:'utf8'});
20
+ try{return fn(root,run,env);}finally{if(old===undefined)delete process.env.CM_WORKFLOW_HOME;else process.env.CM_WORKFLOW_HOME=old;fs.rmSync(root,{recursive:true,force:true});}
21
+ }
22
+
23
+ test('show is read-only; missing CLI only warns; explicit preset commands work without TTY',()=>fixture((root,run,env)=>{
24
+ const show=run('show');assert.equal(show.status,0,show.stderr);assert.match(show.stdout,/runtimes_source: none/);
25
+ assert.deepEqual(fs.readdirSync(root),[]);
26
+ for(const preset of ['codex-only','claude-only','codex-codes','claude-codes']){
27
+ const result=run('set','--user',preset);assert.equal(result.status,0,result.stderr);
28
+ const config=loadConfig({projectRoot:root});assert.equal(runtimesSource(config),'user');
29
+ assert.equal(config.roles.coder.adapter,runtimePreset(preset).roles.coder.adapter);
30
+ }
31
+ const diagnostic=showRuntime(root,{probe:wanted=>wanted.map(runtime=>({runtime,available:false}))});
32
+ assert.match(diagnostic,/preset: claude-codes/);assert.match(diagnostic,/WARN: .*codex CLI/);assert.match(diagnostic,/WARN: .*claude CLI/);
33
+ const set=run('set','codex-only','--project',root);assert.equal(set.status,0,set.stderr);
34
+ assert.equal(runtimesSource(loadConfig({projectRoot:root})),'project');
35
+ assert.match(run('show','--project',root).stdout,/preset: codex-only/);
36
+ assert.equal(run('unset','--user').status,0);assert.equal(run('unset','--user').status,0);
37
+ assert(!fs.existsSync(path.join(env.CM_WORKFLOW_HOME,'runtimes.yml')));
38
+ assert.equal(runtimesSource(loadConfig({projectRoot:root})),'project');
39
+ const logs=fs.readdirSync(path.join(root,'logs','runs'),{recursive:true}).filter(file=>file.endsWith('.jsonl'));
40
+ const events=logs.flatMap(file=>fs.readFileSync(path.join(root,'logs','runs',file),'utf8').trim().split('\n').map(JSON.parse));
41
+ assert.equal(events.length,5);assert(events.every(event=>event.event==='decision'&&event.phase==='route'&&event.project_path===root));
42
+ assert(events.every(event=>Object.keys(event).sort().join(',')===['schema_version','run_id','at','workflow','event','runtime','project','detail','phase','project_path','preset','source','event_id'].sort().join(',')));
43
+ assert(!fs.existsSync(path.join(root,'.cm-run.json')));
44
+ }));
45
+
46
+ test('lossless edits retain comments, BOM, CRLF, quoted keys, models and unrelated raw bytes',()=>fixture(root=>{
47
+ const text='\ufeff# header\r\nversion: 1\r\n"runtimes": {available: codex} # declaration\r\nroles:\r\n coder: {adapter: codex-cli, model: "special", source: subscription} # coder\r\n reviewer:\r\n adapter: codex-cli # review\r\n source: subscription\r\n model: default\r\npolicies: {tests: [commands], auto_fix: never} # tail';
48
+ const file=path.join(root,'.cm-workflow.yml');fs.writeFileSync(file,text);
49
+ setProjectRuntime(root,'claude-codes');
50
+ const expected=text.replace('available: codex','available: both').replace('coder: {adapter: codex-cli','coder: {adapter: claude-cli');
51
+ assert.equal(fs.readFileSync(file,'utf8'),expected);
52
+ assert.equal(loadConfig({projectRoot:root}).roles.coder.model,'special');
53
+ const again=fs.readFileSync(file);setProjectRuntime(root,'claude-codes');assert.deepEqual(fs.readFileSync(file),again);
54
+ }));
55
+
56
+ test('insertion preserves all original bytes for missing nested fields and supported JSON/YAML mappings',()=>fixture(root=>{
57
+ for(const [file,text] of [
58
+ ['x.yml','version: 1'],
59
+ ['x.yml','version: 1\nroles:\n coder:\n model: custom # keep\n# final\n'],
60
+ ['x.yml',"version: 1\nroles: {'coder': {model: 'it''s-safe'}, reviewer: {}}\n".replace("it''s-safe",'safe')],
61
+ ['x.yml','version: 1\nruntimes: {}\nroles: {}\n'],
62
+ ['x.json','{ "version" : 1, "roles": { "coder": {"model":"custom"} } }\n'],
63
+ ['x.yml','version: 1\rroles:\r coder: {model: custom}\r'],
64
+ ]){
65
+ const changed=editRuntimeDeclaration(text,file,runtimePreset('claude-codes'));
66
+ const config=loadConfig({projectRoot:root,configPath:file,text:changed});
67
+ assert.equal(config.roles.coder.adapter,'claude-cli',changed);assert.equal(config.roles.reviewer.source,'subscription');
68
+ // With no existing target scalars, changes consist solely of inserted bytes.
69
+ let cursor=0;for(const character of text){cursor=changed.indexOf(character,cursor);assert(cursor>=0,`${file}: deleted original bytes`);cursor++;}
70
+ }
71
+ }));
72
+
73
+ test('invalid preset/config/conflicts are rejected before writing; symlinks and directories are preserved',()=>fixture((root,run)=>{
74
+ const file=path.join(root,'.cm-workflow.yml');
75
+ fs.writeFileSync(file,'version: 1\nroles:\n analyst: {adapter: claude-cli}\n');
76
+ const original=fs.readFileSync(file);
77
+ assert.notEqual(run('set','wrong').status,0);assert.deepEqual(fs.readFileSync(file),original);
78
+ assert.throws(()=>setProjectRuntime(root,'codex-only'),/roles.analyst.adapter/);assert.deepEqual(fs.readFileSync(file),original);
79
+ fs.writeFileSync(file,'version: 1\nunknown: true\n');assert.throws(()=>setProjectRuntime(root,'codex-codes'),/unknown/);
80
+ fs.unlinkSync(file);fs.symlinkSync(path.join(root,'external.yml'),file);
81
+ assert.throws(()=>setProjectRuntime(root,'codex-codes'),/symlink/);assert(!fs.existsSync(path.join(root,'external.yml')));
82
+ fs.unlinkSync(file);fs.mkdirSync(file);assert.throws(()=>setProjectRuntime(root,'codex-codes'),/non-file/);
83
+ const user=process.env.CM_WORKFLOW_HOME;fs.symlinkSync(root,user);
84
+ assert.throws(()=>writeUserRuntime('codex-only'),/symlink/);assert(!fs.existsSync(path.join(root,'runtimes.yml')));
85
+ for(const args of [['show','--user'],['unset'],['set','codex-only','--user','--project',root],['show','extra']])assert.notEqual(run(...args).status,0);
86
+ }));
87
+
88
+ test('installer helper skips redirected input and --yes with no file writes',()=>fixture((root,run,env)=>{
89
+ for(const args of [[],['--yes']]){
90
+ const result=spawnSync(process.execPath,[path.join(scripts,'cm-runtime-install.mjs'),...args],{env,encoding:'utf8',input:'3\n1\n'});
91
+ assert.equal(result.status,0,result.stderr);assert.equal(result.stdout,'');assert.deepEqual(fs.readdirSync(root),[]);
92
+ }
93
+ writeUserRuntime('claude-only');const file=path.join(env.CM_WORKFLOW_HOME,'runtimes.yml'),before=fs.readFileSync(file);
94
+ const result=spawnSync(process.execPath,[path.join(scripts,'cm-runtime-install.mjs')],{env,encoding:'utf8'});
95
+ assert.equal(result.status,0);assert.deepEqual(fs.readFileSync(file),before);
96
+ }));
97
+
98
+
99
+ test('source metadata never changes strict host JSON, role routes or persisted config fields',()=>fixture(root=>{
100
+ for(const preset of ['codex-only','claude-codes']){
101
+ writeUserRuntime(preset);const config=loadConfig({projectRoot:root});
102
+ assert.equal(runtimesSource(config),'user');
103
+ assert.deepEqual(strictJson(config),config);
104
+ const role=resolveRole(config,'coder','codex');assert.deepEqual(strictJson(role),role);
105
+ assert(!Reflect.ownKeys(config).includes('runtimes_source'));
106
+ assert(!Reflect.ownKeys(role).includes('runtimes_source'));
107
+ }
108
+ }));
109
+
110
+
111
+ test('candidate over the shared file size limit is rejected before atomic replacement',()=>fixture(root=>{
112
+ const file=path.join(root,'.cm-workflow.yml');
113
+ const original='version: 1\n#'+'x'.repeat(MAX_CONFIG_BYTES-12);
114
+ fs.writeFileSync(file,original);assert.equal(loadConfig({projectRoot:root}).version,1);
115
+ assert.throws(()=>setProjectRuntime(root,'codex-codes'),/exceeds/);
116
+ assert.equal(fs.readFileSync(file,'utf8'),original);
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
+ }));