@aibyzero/cm-workflow 0.12.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +55 -1
  4. package/README.md +31 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/docs/installation.md +43 -1
  8. package/docs/js-workflow-control.md +63 -6
  9. package/docs/runtime-failover.md +97 -0
  10. package/docs/user-guide.md +37 -1
  11. package/install-codex.sh +5 -0
  12. package/install.ps1 +10 -2
  13. package/install.sh +5 -0
  14. package/package.json +2 -1
  15. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  17. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  20. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  21. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  25. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  26. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  28. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  29. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  31. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  32. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  33. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  34. package/runtime/js/cm-ai/host.mjs +1 -1
  35. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  36. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  37. package/runtime/js/cm-ai/review-package.mjs +76 -18
  38. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  39. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  40. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  41. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  42. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  43. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  44. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  45. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  46. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  47. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  48. package/runtime/js/cm-prd/session.mjs +19 -2
  49. package/runtime/js/cm-prd/summary.mjs +46 -20
  50. package/runtime/review.md +11 -1
  51. package/runtime/workflow-config.md +39 -2
  52. package/runtime/workflow-routing.md +6 -1
  53. package/scripts/cm-ai-admission.test.mjs +99 -0
  54. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  55. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  56. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  57. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  58. package/scripts/cm-ai-host.mjs +81 -12
  59. package/scripts/cm-ai-host.test.mjs +520 -5
  60. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  61. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  62. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  63. package/scripts/cm-ai-run.mjs +40 -13
  64. package/scripts/cm-ai-run.test.mjs +45 -9
  65. package/scripts/cm-check-host.test.mjs +1 -1
  66. package/scripts/cm-check-runtime.sh +51 -1
  67. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  68. package/scripts/cm-claude-probe.test.mjs +64 -1
  69. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  70. package/scripts/cm-claude-worker.test.mjs +110 -1
  71. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  72. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  73. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  74. package/scripts/cm-failover.mjs +288 -0
  75. package/scripts/cm-failover.test.mjs +184 -0
  76. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  77. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  78. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  79. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  80. package/scripts/cm-init-host.mjs +4 -4
  81. package/scripts/cm-init-host.test.mjs +12 -7
  82. package/scripts/cm-init-session.test.mjs +50 -0
  83. package/scripts/cm-log-event.mjs +34 -5
  84. package/scripts/cm-prd-completion.test.mjs +2 -2
  85. package/scripts/cm-prd-host.mjs +39 -3
  86. package/scripts/cm-prd-host.test.mjs +52 -0
  87. package/scripts/cm-prd-review-gate.mjs +11 -2
  88. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  89. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  90. package/scripts/cm-prd-summary.test.mjs +147 -0
  91. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  92. package/scripts/cm-review-inventory.test.mjs +189 -0
  93. package/scripts/cm-review-schema.test.mjs +35 -1
  94. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  95. package/scripts/cm-runtime-edit.mjs +104 -0
  96. package/scripts/cm-runtime-failover.test.mjs +130 -0
  97. package/scripts/cm-runtime-install.mjs +42 -0
  98. package/scripts/cm-runtime.mjs +113 -0
  99. package/scripts/cm-runtime.test.mjs +117 -0
  100. package/scripts/cm-spec-manifest.mjs +24 -21
  101. package/scripts/cm-spec-manifest.test.mjs +19 -0
  102. package/scripts/cm-workflow-config.mjs +113 -5
  103. package/scripts/cm-workflow-config.test.mjs +124 -1
  104. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  105. package/scripts/test-cm-prd-review-gate.py +30 -0
  106. package/scripts/test-shell-compat.sh +34 -0
  107. package/scripts/validate-public-repo.py +5 -0
  108. package/skills/cm-ai/references/N4-review.md +5 -4
  109. package/skills/cm-ai/references/js-host.md +36 -2
  110. package/skills/cm-check/SKILL.md +7 -3
  111. package/skills/cm-init/SKILL.md +4 -0
  112. package/skills/cm-init/references/js-host.md +2 -0
  113. package/skills/cm-init/references/runtime-declaration.md +26 -0
  114. package/skills/cm-prd/SKILL.md +3 -3
  115. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  116. package/skills/cm-prd/references/summary-card.md +7 -0
  117. package/skills/cm-runtime/SKILL.md +32 -0
  118. package/templates/auto-update/cm-update.sh +1 -1
  119. package/templates/cm-workflow.yml +16 -0
@@ -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,42 @@
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/promises';
7
+ import {userRuntimesPath,readConfigText,parseUserRuntimes} from './cm-workflow-config.mjs';
8
+ import {writeUserRuntime} from './cm-runtime.mjs';
9
+
10
+ export async function promptRuntime(argv=process.argv.slice(2),input=process.stdin,output=process.stdout){
11
+ if(argv.some(arg=>arg!=='--yes'))throw new Error('usage: cm-runtime-install.mjs [--yes]');
12
+ if(argv.includes('--yes')||!input.isTTY||!output.isTTY)return;
13
+ const rl=createInterface({input,output});let closed=false;
14
+ rl.on('close',()=>{closed=true;});
15
+ const ask=async question=>{
16
+ if(closed)throw new Error('输入已关闭,未修改运行时声明');
17
+ return (await rl.question(question)).trim();
18
+ };
19
+ try{
20
+ const file=userRuntimesPath();
21
+ if(fs.existsSync(file)){
22
+ try{
23
+ const current=parseUserRuntimes(readConfigText(file));
24
+ output.write(`当前用户级默认: ${current.runtimes.available} / ${current.preset}\n`);
25
+ }catch(error){output.write(`当前用户级默认无效: ${error.message}\n`);}
26
+ const keep=await ask('保留?[Y/n] ');
27
+ if(keep!=='n'&&keep!=='N')return;
28
+ }
29
+ let choice;
30
+ do{choice=await ask('你手上有哪个 AI 工具?[1] 只有 Codex [2] 只有 Claude [3] 两个都有: ');}while(!['1','2','3'].includes(choice));
31
+ let preset=choice==='1'?'codex-only':'claude-only';
32
+ if(choice==='3'){
33
+ let coder;
34
+ do{coder=await ask('谁写代码?[1] Codex(Claude 审,推荐) [2] Claude(Codex 审): ');}while(!['','1','2'].includes(coder));
35
+ preset=coder==='2'?'claude-codes':'codex-codes';
36
+ }
37
+ output.write(`✓ 用户级运行时默认已写入 ${writeUserRuntime(preset)} (${preset})\n`);
38
+ }finally{rl.close();}
39
+ }
40
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
41
+ try{await promptRuntime();}catch(error){console.error(`运行时声明未完成: ${error.message}`);process.exitCode=1;}
42
+ }
@@ -0,0 +1,113 @@
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 {probeRuntimes} from './cm-failover.mjs';
12
+
13
+ const scripts=path.dirname(fileURLToPath(import.meta.url));
14
+ function stat(file){try{return fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}}
15
+ function safeTarget(file){
16
+ const parent=path.dirname(file),dir=stat(parent),target=stat(file);
17
+ if(dir&&(dir.isSymbolicLink()||!dir.isDirectory()))throw new ConfigError(`refusing non-directory or symlink parent: ${parent}`);
18
+ if(target&&(target.isSymbolicLink()||!target.isFile()))throw new ConfigError(`refusing non-file or symlink target: ${file}`);
19
+ }
20
+ export function atomicRuntimeWrite(file,text,{before=null,privateFile=false}={}){
21
+ safeTarget(file);
22
+ fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
23
+ const temporary=path.join(path.dirname(file),`.runtimes-${randomUUID()}.tmp`);
24
+ try{
25
+ fs.writeFileSync(temporary,text,{flag:'wx',mode:privateFile?0o600:(stat(file)?.mode??0o644)&0o777});
26
+ safeTarget(file);
27
+ const current=stat(file)?fs.readFileSync(file):null;
28
+ if(before===null?current!==null:current===null||!current.equals(before))throw new ConfigError('configuration changed during edit; retry from current file');
29
+ fs.renameSync(temporary,file);
30
+ }finally{if(stat(temporary))fs.unlinkSync(temporary);}
31
+ }
32
+ export function writeUserRuntime(preset){
33
+ const declaration=runtimePreset(preset),file=userRuntimesPath();
34
+ safeTarget(file);
35
+ const text=`# 用 cm-runtime set --user <preset> 修改用户级默认。\nruntimes: {available: ${declaration.runtimes.available}}\npreset: ${preset}\n`;
36
+ parseUserRuntimes(text);
37
+ atomicRuntimeWrite(file,text,{before:stat(file)?fs.readFileSync(file):null,privateFile:true});
38
+ return file;
39
+ }
40
+ function projectDirectory(raw){
41
+ const root=fs.realpathSync(path.resolve(raw));
42
+ if(!fs.statSync(root).isDirectory())throw new ConfigError('project must be a directory');
43
+ return root;
44
+ }
45
+ export function setProjectRuntime(project,preset){
46
+ const root=projectDirectory(project),declaration=runtimePreset(preset);
47
+ // Reject broken links/directories too, even though findConfig only finds files.
48
+ for(const name of ['.cm-workflow.yml','.cm-workflow.yaml','.cm-workflow.json'])safeTarget(path.join(root,name));
49
+ const existing=findConfig(root),file=existing??path.join(root,'.cm-workflow.yml');
50
+ const before=existing?fs.readFileSync(file):null;
51
+ const original=readConfigText(existing??path.join(scripts,'../templates/cm-workflow.yml'));
52
+ loadConfig({projectRoot:root,configPath:file,text:original});
53
+ const text=editRuntimeDeclaration(original,file,declaration);
54
+ loadConfig({projectRoot:root,configPath:file,text});
55
+ atomicRuntimeWrite(file,text,{before});return file;
56
+ }
57
+ export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',probe=probeRuntimes}={}){
58
+ const config=loadConfig({projectRoot:project});
59
+ const preset=Object.keys(RUNTIME_PRESETS).find(name=>{
60
+ const value=runtimePreset(name);
61
+ return config.runtimes.available===value.runtimes.available
62
+ &&['coder','reviewer'].every(role=>['adapter','source'].every(field=>config.roles[role][field]===value.roles[role][field]));
63
+ })??(runtimesSource(config)==='none'?'none':'custom');
64
+ const lines=[`runtimes.available: ${config.runtimes.available}`,`preset: ${preset}`,`runtimes_source: ${runtimesSource(config)}`];
65
+ for(const role of ['coder','reviewer']){
66
+ 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'?'(已声明未派发)':''}`);
68
+ }
69
+ const wanted=config.runtimes.available==='both'?['codex','claude']:config.runtimes.available==='unknown'?[]:[config.runtimes.available];
70
+ for(const result of probe(wanted))lines.push(result.available
71
+ ?`${result.runtime} CLI: 可解析(可解析≠配额可用)`
72
+ :`WARN: runtimes.available 声明 ${config.runtimes.available},但本机 ${result.runtime} CLI 不可解析(可解析≠配额可用)`);
73
+ return lines.join('\n');
74
+ }
75
+ function logSet(preset,source,project){
76
+ // Reuse cm-log-event.mjs through its required Python platform lock adapter.
77
+ // No specs/run pointer: this decision is independent of any in-flight run.
78
+ const args=[path.join(scripts,'cm-log-event.py'),'--workflow','cm-runtime','--event','decision','--phase','route',
79
+ '--runtime','local','--project-root',project,'--detail','runtime preference set',
80
+ '--data-json',JSON.stringify({preset,source})];
81
+ for(const python of process.env.CM_PYTHON_BIN?[process.env.CM_PYTHON_BIN]:['python3','python']){
82
+ const result=spawnSync(python,args,{encoding:'utf8',timeout:30000,env:{...process.env,
83
+ CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME||path.join(path.dirname(userRuntimesPath()),'logs')}});
84
+ if(result.error?.code==='ENOENT')continue;
85
+ if(result.status===0)return;
86
+ throw new ConfigError(`preference saved, decision log failed: ${result.stderr?.trim()||result.error?.message||result.status}`);
87
+ }
88
+ throw new ConfigError('preference saved, decision log failed: Python 3.9+ lock adapter unavailable');
89
+ }
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)){
92
+ 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;
95
+ for(let i=0;i<args.length;i++){
96
+ if(args[i]==='--user'&&!user){user=true;continue;}
97
+ if(args[i]==='--project'&&!projectSeen&&args[i+1]&&!args[i+1].startsWith('--')){project=args[++i];projectSeen=true;continue;}
98
+ if(command==='set'&&!preset&&!args[i].startsWith('--')){preset=args[i];continue;}
99
+ throw new ConfigError(USAGE);
100
+ }
101
+ if(user&&projectSeen)throw new ConfigError('--user cannot be combined with --project');
102
+ if(command==='show'&&!user){console.log(showRuntime(project));return 0;}
103
+ 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;
108
+ }
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;}
110
+ throw new ConfigError(USAGE);
111
+ }catch(error){console.error(`cm-runtime: ${error.message}`);return 1;}
112
+ }
113
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
@@ -0,0 +1,117 @@
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
+ }));
@@ -15,28 +15,31 @@ const record=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
15
15
  const compare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
16
16
  const exists=p=>{try{fs.statSync(p);return true;}catch(e){if(['ENOENT','ENOTDIR'].includes(e.code))return false;throw e;}};
17
17
 
18
+ // Only actual task/AC declarations are runtime state; other files and code stay exact.
19
+ export function normalizeRuntimeMarks(text,name){
20
+ if(!['tasks.md','requirements.md'].includes(name))return text;
21
+ const marker=name==='tasks.md'?/^([ ]{0,3}-[ \t]+)\[[xX]\]([ \t]+T-[A-Za-z0-9][A-Za-z0-9._-]*[ \t]*:)/
22
+ :/^([ ]{0,3}-[ \t]+)\[[xX]\]([ \t]+\[AC-[A-Za-z0-9][A-Za-z0-9._-]*\])/;
23
+ let fenceChar=null,width=0;
24
+ const lines=text.match(/[^\r\n]*(?:\r\n|\r|\n|$)/g)??[];
25
+ return lines.map(line=>{
26
+ const fence=/^[ ]{0,3}(`{3,}|~{3,})/.exec(line);
27
+ if(fenceChar!==null){
28
+ if(fence&&fence[1][0]===fenceChar&&fence[1].length>=width
29
+ &&/^[\t\n\v\f\r ]*$/.test(line.slice(fence[0].length))){fenceChar=null;width=0;}
30
+ return line;
31
+ }
32
+ if(fence){fenceChar=fence[1][0];width=fence[1].length;return line;}
33
+ if(line.startsWith(' ')||line.startsWith('\t'))return line;
34
+ return line.replace(marker,'$1[ ]$2');
35
+ }).join('');
36
+ }
37
+
18
38
  export function semanticDigest(file){
19
- let bytes=fs.readFileSync(file);
20
- const name=path.basename(file);
21
- if(['tasks.md','requirements.md'].includes(name)){
22
- const marker=name==='tasks.md'?/^([ ]{0,3}-[ \t]+)\[[xX]\]([ \t]+T-[A-Za-z0-9][A-Za-z0-9._-]*[ \t]*:)/
23
- :/^([ ]{0,3}-[ \t]+)\[[xX]\]([ \t]+\[AC-[A-Za-z0-9][A-Za-z0-9._-]*\])/;
24
- let fenceChar=null,width=0;
25
- // Latin-1 is a reversible byte view, including invalid UTF-8 and CRLF.
26
- const lines=bytes.toString('latin1').match(/[^\r\n]*(?:\r\n|\r|\n|$)/g)??[];
27
- bytes=Buffer.from(lines.map(line=>{
28
- const fence=/^[ ]{0,3}(`{3,}|~{3,})/.exec(line);
29
- if(fenceChar!==null){
30
- if(fence&&fence[1][0]===fenceChar&&fence[1].length>=width
31
- &&/^[\t\n\v\f\r ]*$/.test(line.slice(fence[0].length))){fenceChar=null;width=0;}
32
- return line;
33
- }
34
- if(fence){fenceChar=fence[1][0];width=fence[1].length;return line;}
35
- if(line.startsWith(' ')||line.startsWith('\t'))return line;
36
- return line.replace(marker,'$1[ ]$2');
37
- }).join(''),'latin1');
38
- }
39
- return createHash('sha256').update(bytes).digest('hex');
39
+ const bytes=fs.readFileSync(file);
40
+ // Latin-1 is a reversible byte view, including invalid UTF-8 and CRLF.
41
+ const normalized=Buffer.from(normalizeRuntimeMarks(bytes.toString('latin1'),path.basename(file)),'latin1');
42
+ return createHash('sha256').update(normalized).digest('hex');
40
43
  }
41
44
 
42
45
  export function buildManifest(specsDir){
@@ -0,0 +1,19 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {normalizeRuntimeMarks} from './cm-spec-manifest.mjs';
4
+ test('shared normalization preserves declaration, filename, fence and byte boundaries',()=>{
5
+ for(const [name,declaration,other] of [['tasks.md','T-A.1:','[AC-001]'],['requirements.md','[AC-A.1]','T-001:']]){
6
+ const lines=[`- [x] ${declaration} 中文`,` -\t[X]\t${declaration} [CHANGED]`,
7
+ `- [DROPPED] ${declaration} old`,`- [CHANGED] ${declaration} changed`,
8
+ `text - [x] ${declaration} prose`,`- [x] ${other} wrong file`,'- [x] ordinary',
9
+ ` - [x] ${declaration} code`,`\t- [x] ${declaration} code`,
10
+ '```md',`- [x] ${declaration} fenced`,'```',
11
+ '~~~~',`- [X] ${declaration} fenced`,'~~~~',`- [X] ${declaration} final`];
12
+ for(const ending of ['\n','\r\n','\r']){
13
+ const text=lines.join(ending),expected=[...lines];
14
+ for(const i of [0,1,15])expected[i]=expected[i].replace(/\[[xX]\]/,'[ ]');
15
+ assert.equal(normalizeRuntimeMarks(text,name),expected.join(ending));
16
+ for(const otherName of ['design.md','test-cases.json','notes.md'])assert.equal(normalizeRuntimeMarks(text,otherName),text);
17
+ }
18
+ }
19
+ });