@aibyzero/cm-workflow 0.11.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 (130) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +3 -0
  3. package/CHANGELOG.md +64 -3
  4. package/README.md +45 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/compat/claude-commands/cm-security.md +3 -0
  8. package/docs/architecture.md +22 -0
  9. package/docs/installation.md +56 -2
  10. package/docs/js-workflow-control.md +63 -6
  11. package/docs/runtime-failover.md +97 -0
  12. package/docs/user-guide.md +60 -3
  13. package/install-codex.sh +5 -0
  14. package/install.ps1 +10 -2
  15. package/install.sh +5 -0
  16. package/package.json +3 -1
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  18. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  19. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  23. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  24. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  25. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  27. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  28. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  29. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  30. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  31. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  32. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  33. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  34. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  35. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  36. package/runtime/js/cm-ai/host.mjs +1 -1
  37. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  38. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  39. package/runtime/js/cm-ai/review-package.mjs +76 -18
  40. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  41. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  42. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  43. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  44. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  45. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  46. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  47. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  48. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  49. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  50. package/runtime/js/cm-prd/session.mjs +19 -2
  51. package/runtime/js/cm-prd/summary.mjs +46 -20
  52. package/runtime/js/cm-security/scan.mjs +263 -0
  53. package/runtime/js/cm-test/branch-impact.mjs +8 -2
  54. package/runtime/review.md +11 -1
  55. package/runtime/workflow-config.md +39 -2
  56. package/runtime/workflow-routing.md +6 -1
  57. package/scripts/cm-ai-admission.test.mjs +99 -0
  58. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  59. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  60. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  61. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  62. package/scripts/cm-ai-host.mjs +81 -12
  63. package/scripts/cm-ai-host.test.mjs +520 -5
  64. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  65. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  66. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  67. package/scripts/cm-ai-run.mjs +40 -13
  68. package/scripts/cm-ai-run.test.mjs +45 -9
  69. package/scripts/cm-check-host.test.mjs +1 -1
  70. package/scripts/cm-check-runtime.sh +56 -1
  71. package/scripts/cm-check-update.mjs +200 -0
  72. package/scripts/cm-check-update.test.mjs +186 -0
  73. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  74. package/scripts/cm-claude-probe.test.mjs +64 -1
  75. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  76. package/scripts/cm-claude-worker.test.mjs +110 -1
  77. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  78. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  79. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  80. package/scripts/cm-failover.mjs +288 -0
  81. package/scripts/cm-failover.test.mjs +184 -0
  82. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  83. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  84. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  85. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  86. package/scripts/cm-init-host.mjs +4 -4
  87. package/scripts/cm-init-host.test.mjs +12 -7
  88. package/scripts/cm-init-session.test.mjs +50 -0
  89. package/scripts/cm-log-event.mjs +34 -5
  90. package/scripts/cm-prd-completion.test.mjs +2 -2
  91. package/scripts/cm-prd-host.mjs +39 -3
  92. package/scripts/cm-prd-host.test.mjs +52 -0
  93. package/scripts/cm-prd-review-gate.mjs +11 -2
  94. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  95. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  96. package/scripts/cm-prd-summary.test.mjs +147 -0
  97. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  98. package/scripts/cm-review-inventory.test.mjs +189 -0
  99. package/scripts/cm-review-schema.test.mjs +35 -1
  100. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  101. package/scripts/cm-runtime-edit.mjs +104 -0
  102. package/scripts/cm-runtime-failover.test.mjs +130 -0
  103. package/scripts/cm-runtime-install.mjs +42 -0
  104. package/scripts/cm-runtime.mjs +113 -0
  105. package/scripts/cm-runtime.test.mjs +117 -0
  106. package/scripts/cm-security.mjs +32 -0
  107. package/scripts/cm-security.test.mjs +203 -0
  108. package/scripts/cm-spec-manifest.mjs +24 -21
  109. package/scripts/cm-spec-manifest.test.mjs +19 -0
  110. package/scripts/cm-workflow-config.mjs +113 -5
  111. package/scripts/cm-workflow-config.test.mjs +124 -1
  112. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  113. package/scripts/test-cm-prd-review-gate.py +30 -0
  114. package/scripts/test-shell-compat.sh +34 -0
  115. package/scripts/validate-public-repo.py +7 -1
  116. package/skills/cm-ai/references/N4-review.md +5 -4
  117. package/skills/cm-ai/references/js-host.md +36 -2
  118. package/skills/cm-check/SKILL.md +49 -8
  119. package/skills/cm-check/references/js-host.md +4 -1
  120. package/skills/cm-init/SKILL.md +4 -0
  121. package/skills/cm-init/references/js-host.md +2 -0
  122. package/skills/cm-init/references/runtime-declaration.md +26 -0
  123. package/skills/cm-prd/SKILL.md +3 -3
  124. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  125. package/skills/cm-prd/references/summary-card.md +7 -0
  126. package/skills/cm-runtime/SKILL.md +32 -0
  127. package/skills/cm-security/SKILL.md +55 -0
  128. package/skills/cm-security/references/scan-contract.md +43 -0
  129. package/templates/auto-update/cm-update.sh +1 -1
  130. package/templates/cm-workflow.yml +16 -0
@@ -1,7 +1,7 @@
1
1
  # CM Workflow 项目配置合同
2
2
 
3
3
  CM 支持一个可选的项目根配置文件:`.cm-workflow.yml`、`.cm-workflow.yaml` 或
4
- `.cm-workflow.json`。配置缺失时使用内置默认值,旧项目不需要修改即可继续执行。
4
+ `.cm-workflow.json`。项目缺少运行时声明时读取用户级默认,两级均缺失才使用内置默认值。
5
5
 
6
6
  ## 配置边界
7
7
 
@@ -11,7 +11,7 @@ CM 支持一个可选的项目根配置文件:`.cm-workflow.yml`、`.cm-workfl
11
11
  - `source` 表示订阅、API、本地或浏览器等执行来源;它不等于模型身份。
12
12
  - `model` 是用户可读的模型别名。CM 不根据订阅名推断后端模型版本。
13
13
  - 外部专家的项目级 `activation` 只能是 `explicit`;`AUTO` 仍是单次调用的显式选择,不能由仓库配置永久打开。
14
- - 第一版只读取显式 `--config` 或项目根配置,不读取隐式用户级配置。
14
+ - 显式 `--config` 或项目根配置优先;仅缺少 `runtimes.available` 时回退用户级 `~/.cm-workflow/runtimes.yml`(`CM_WORKFLOW_HOME` 覆盖目录)。
15
15
 
16
16
  ## 角色
17
17
 
@@ -27,6 +27,23 @@ CM 支持一个可选的项目根配置文件:`.cm-workflow.yml`、`.cm-workfl
27
27
 
28
28
  角色配置只改变“谁负责、用哪个适配器和模型别名”,不改变 N1–N8 顺序。未配置角色继续使用当前 AI 和既有默认行为。
29
29
 
30
+ ## 运行时声明
31
+
32
+ `runtimes.available` 记录用户自报的可用运行时:`codex`、`claude` 或 `both`。缺省为
33
+ `unknown`(两级均未声明,不做交叉检查)。安装器可写用户默认,`cm-init` 优先继承且不再询问;`cm-runtime` 随时切换。
34
+
35
+ | 预设 | `runtimes.available` | `roles.coder.adapter` | `roles.reviewer.adapter` |
36
+ | --- | --- | --- | --- |
37
+ | `codex-only` | `codex` | `codex-cli` | `codex-cli`(全新上下文,仍是独立审查) |
38
+ | `claude-only` | `claude` | `claude-cli` | `claude-cli`(同上) |
39
+ | `codex-codes` | `both` | `codex-cli` | `claude-cli` |
40
+ | `claude-codes` | `both` | `claude-cli` | `codex-cli` |
41
+
42
+ 校验规则:单家声明时任何角色不得指向另一家;`both` 时 `coder` 与 `reviewer` 不得同家。
43
+ `current-ai` 表示「当前所在工具」,不参与判定。**声明不等于派发**:与当前运行时不同的
44
+ adapter 仍解析为 `declared-adapter`,只记录、不调用;`cm-check --project` 会把这类角色标为
45
+ 「已声明未派发」。声明也不拦用户在任一工具里交互式执行。
46
+
30
47
  ## 有限 Workflow Profile
31
48
 
32
49
  | Profile | 适用项目 | 额外策略 |
@@ -116,3 +133,23 @@ node {CM_WORKFLOW_ROOT}/scripts/cm-workflow-config.mjs --project {CODE_PROJECT}
116
133
  node {CM_WORKFLOW_ROOT}/scripts/cm-workflow-config.mjs \
117
134
  --project {CODE_PROJECT} --role coder --runtime codex --print-role
118
135
  ```
136
+
137
+ ## 用户默认与切换
138
+
139
+ ```yaml
140
+ # 用 cm-runtime set --user <preset> 修改用户级默认。
141
+ runtimes: {available: both}
142
+ preset: codex-codes
143
+ ```
144
+
145
+ 只接受上述两个字段;预设与 available 必须一致。优先级为项目 > 用户 > 未声明;
146
+ 项目已声明时完全不读用户文件。用户预设给 coder/reviewer 的 adapter/source 提供默认值,
147
+ 显式项目角色字段继续优先,模型和其他字段保留;合并结果仍须通过同一校验。
148
+ 生效的用户文件非法时报告字段路径并阻断。`--print-effective` / `--print-role` 包含
149
+ `runtimes_source: project|user|none`,不将这个诊断字段写回项目配置。
150
+
151
+ `cm-runtime show [--project PATH]` 只读;`set <preset> [--project PATH]` 原子改项目;
152
+ `set --user <preset>` 改用户默认;`unset --user` 删除用户默认但不删除项目声明。
153
+ 新建项目配置使用模板,已有配置只改五个字段,其余原文保留。已创建的 run 绑定原配置,切换不改 run。
154
+ `set` 通过 cm-log-event.mjs 的 Python 锁适配器写独立的 `decision/route` 全局日志,
155
+ 仅附 preset、source、项目路径;没有 specs 指针或业务任务状态写入。日志失败明确报告配置已保存。
@@ -41,7 +41,7 @@ N1–N8, mark tasks complete, approve specs, or replace the independent N4 gate.
41
41
 
42
42
  ## Route states
43
43
 
44
- The resolver reports a conservative state:
44
+ The resolver reports a conservative state; only the protected host can record actual CLI dispatch:
45
45
 
46
46
  - `current-runtime`: the active Codex/Claude runtime or `current-ai` owns the
47
47
  step;
@@ -55,6 +55,11 @@ The resolver reports a conservative state:
55
55
  cannot satisfy the N4 independent-review evidence contract;
56
56
  - `disabled`: the project explicitly disabled this role; do not invoke it and
57
57
  record the local skip/degrade outcome;
58
+ - `cli-dispatch`: the adapter is `codex-cli` or `claude-cli`, differs from the
59
+ active runtime, and the protected host actually created that provider process.
60
+ The host writes this state in the route `decision` event after spawn;
61
+ `resolveRole` remains pure and never infers dispatch from declarations.
62
+ This proves dispatch only, not quota availability, success or independent review;
58
63
  - `declared-adapter`: the project requested an adapter that this runtime did
59
64
  not observe. CM records the requested route, but must not claim that model or
60
65
  provider actually ran. Adapter-specific invocation remains an integration
@@ -5,6 +5,7 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
+ import {parseFeatureTaskText,validDependencies} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
8
9
 
9
10
  const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
10
11
  function fixture(run){
@@ -36,3 +37,101 @@ test('product admission reports generic continuation without approving or writin
36
37
  assert.deepEqual(fs.readFileSync(path.join(specs,'.cm-specs-status')),before);
37
38
  assert.equal(fs.readdirSync(root).length,2);
38
39
  }));
40
+
41
+ function writeFeature(specs,name,source){
42
+ const target=path.join(specs,name);fs.mkdirSync(target,{recursive:true});
43
+ for(const file of ['requirements.md','design.md'])fs.writeFileSync(path.join(target,file),'# Fixture\n');
44
+ fs.writeFileSync(path.join(target,'tasks.md'),source);
45
+ }
46
+
47
+ function admission(specs,code,names,exitCode=0){
48
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:names,testCases:[]}));
49
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code],{encoding:'utf8'});
50
+ assert.equal(result.status,exitCode,result.stderr||result.stdout);
51
+ return JSON.parse(result.stdout);
52
+ }
53
+
54
+ const threeTasks='- [x] T-001: first\n- [ ] T-002: second\n- [ ] T-003: third\n';
55
+
56
+ test('dependency parser accepts sentence punctuation per ID and preserves internal ID characters',()=>{
57
+ for(const suffix of ['。','.','.',';',';','、',' 。 ..;;、 \t']){
58
+ const parsed=parseFeatureTaskText(threeTasks+`- T-002 依赖 T-001${suffix}\n- T-003 依赖 T-001${suffix},T-002${suffix}\n`,
59
+ {allowDependencyPunctuation:true});
60
+ assert.equal(parsed.error,undefined);
61
+ assert.deepEqual([...parsed.dependencies],[['T-002',['T-001']],['T-003',['T-001','T-002']]]);
62
+ assert.equal(validDependencies(parsed.tasks,parsed.dependencies),true);
63
+ }
64
+ const parsed=parseFeatureTaskText('- [x] T-api.v1_beta-2: first\n- [ ] T-next: next\n- T-next 依赖 T-api.v1_beta-2。\n',
65
+ {allowDependencyPunctuation:true});
66
+ assert.deepEqual(parsed.dependencies.get('T-next'),['T-api.v1_beta-2']);
67
+ assert.equal(validDependencies(parsed.tasks,parsed.dependencies),true);
68
+ });
69
+
70
+ test('shared parser defaults preserve cm-prd strict dependency validation',()=>{
71
+ const source=threeTasks+'- T-002 依赖 T-001。\n';
72
+ assert.equal(parseFeatureTaskText(source).error,'dependencies_invalid');
73
+ const parsed=parseFeatureTaskText(source.replace('T-001。','T-001'));
74
+ assert.equal(parsed.error,undefined);assert.equal(validDependencies(parsed.tasks,parsed.dependencies),true);
75
+ });
76
+
77
+ test('product admission selects the same task with single and multiple punctuated dependencies',()=>fixture(({specs,code})=>{
78
+ const source=threeTasks+'- T-002 依赖 T-001。\n- T-003 依赖 T-001,T-002。\n';
79
+ writeFeature(specs,'1.login',source);
80
+ let result=admission(specs,code,['1.login']);
81
+ assert.equal(result.state,'ready');assert.equal(result.nextTask.id,'T-002');
82
+ writeFeature(specs,'1.login',source.replace('[ ] T-002','[x] T-002'));
83
+ result=admission(specs,code,['1.login']);
84
+ assert.equal(result.state,'ready');assert.equal(result.nextTask.id,'T-003');
85
+ }));
86
+
87
+ for(const [label,source,reason,line] of [
88
+ ['internal punctuation',threeTasks+'- T-002 依赖 T-001。T-003\n','dependencies_invalid',4],
89
+ ['punctuation only',threeTasks+'- T-002 依赖 。;\n','dependencies_invalid',4],
90
+ ['punctuation-only second ID',threeTasks+'- T-002 依赖 T-001,。\n','dependencies_invalid',4],
91
+ ['duplicate dependency',threeTasks+'- T-002 依赖 T-001。\n- T-002 依赖 T-003。\n','dependencies_invalid',5],
92
+ ['unknown dependency',threeTasks+'- T-002 依赖 T-999。\n','dependencies_invalid',4],
93
+ ['unknown dependent',threeTasks+'- T-999 依赖 T-001。\n','dependencies_invalid',4],
94
+ ['self dependency',threeTasks+'- T-002 依赖 T-002。\n','dependencies_invalid',4],
95
+ ['cycle',threeTasks+'- T-002 依赖 T-003。\n- T-003 依赖 T-002。\n','dependencies_invalid',4],
96
+ ['duplicate task',threeTasks+`- [ ] T-002: ${'重复'.repeat(100)}\n`,'tasks_invalid',4],
97
+ ['no tasks','\n# Empty task list\n','tasks_invalid',2],
98
+ ['empty file','','tasks_invalid',1],
99
+ ])test(`product admission locates ${label} and preserves earlier feature summaries`,()=>fixture(({specs,code})=>{
100
+ writeFeature(specs,'1.login','- [x] T-001: historical completion\n');
101
+ writeFeature(specs,'2.broken',source.replace(/\n/g,'\r\n'));
102
+ writeFeature(specs,'3.later','- [ ] T-001: must not skip broken feature\n');
103
+ const result=admission(specs,code,['1.login','2.broken','3.later'],1);
104
+ assert.equal(result.state,'blocked');assert.equal(result.reason,reason);assert.equal(result.nextTask,null);
105
+ assert.deepEqual(result.detail,{feature:'2.broken',line,text:source.split('\n')[line-1].slice(0,120)});
106
+ assert(result.detail.text.length<=120);
107
+ assert.deepEqual(result.features,[{name:'1.login',total:1,completed:1,dropped:0,pending:0}]);
108
+ assert.equal(result.warnings.length,1);
109
+ }));
110
+
111
+ for(const source of [threeTasks+'- T-002 依赖 T-001。T-003\n',threeTasks+'- [ ] T-002: duplicate\n'])
112
+ test('bootstrap parse failures keep their diagnostic location in a non-empty project',()=>fixture(({specs,code})=>{
113
+ writeFeature(specs,'0.bootstrap',source);
114
+ const result=admission(specs,code,['0.bootstrap','1.login'],1);
115
+ assert.equal(result.state,'blocked');assert.equal(result.nextTask,null);
116
+ assert.equal(result.reason,source.includes('依赖')?'dependencies_invalid':'tasks_invalid');
117
+ assert.deepEqual(result.detail,{feature:'0.bootstrap',line:4,text:source.split('\n')[3]});
118
+ }));
119
+
120
+ test('three punctuated historical features admit the new feature without changing selection order',()=>fixture(({specs,code})=>{
121
+ const names=['1.login','2.profile','3.settings','4.todo-priority'];
122
+ const historical='- [x] T-001: first\n- [x] T-002: second\n- [x] T-003: third\n'
123
+ +'- T-002 依赖 T-001。\n- T-003 依赖 T-001,T-002。\n';
124
+ for(const name of names.slice(0,3))writeFeature(specs,name,historical);
125
+ writeFeature(specs,names[3],'- [ ] ~~T-000: removed~~ [DROPPED v2]\n'+threeTasks
126
+ +'- T-002 依赖 T-001\n- T-003 依赖 T-001,T-002\n');
127
+ let result=admission(specs,code,names);
128
+ assert.equal(result.state,'ready');
129
+ assert.deepEqual(result.nextTask,{feature:'4.todo-priority',id:'T-002',description:'second'});
130
+ assert.deepEqual(result.features.map(item=>item.name),names);
131
+ assert.equal(result.features[3].dropped,1);
132
+ writeFeature(specs,'2.profile',historical.replace('[x] T-002','[ ] T-002'));
133
+ result=admission(specs,code,names);
134
+ assert.equal(result.state,'ready');
135
+ assert.deepEqual(result.nextTask,{feature:'2.profile',id:'T-002',description:'second'});
136
+ assert.deepEqual(result.features.map(item=>item.name),names.slice(0,2));
137
+ }));
@@ -7,6 +7,7 @@ import {spawn,spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
9
9
  import {claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
11
 
11
12
  const cli=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
12
13
  function fixture(runtime='codex'){
@@ -15,7 +16,7 @@ function fixture(runtime='codex'){
15
16
  fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);fs.mkdirSync(bin);
16
17
  for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Synthetic batch\n');
17
18
  fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n');
18
- fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature]}));
19
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
19
20
  fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Two synthetic exports and README\n');
20
21
  const batch={version:1,repositoryId:'batch-host',batchId:'batch-host-run',specsDir,codeProject,
21
22
  tasks:[1,2].map(n=>({feature,taskId:`T-00${n}`,scope:[`task${n}.mjs`,...(n===2?['README.md']:[])],requirements:['requirements.md']}))};
@@ -59,6 +60,8 @@ function execute(f,approvals,{cancel=false}={}){
59
60
  assert.equal(payload.request.provider,f.runtime);
60
61
  const n=Number(identity.taskId.slice(-1));
61
62
  assert.deepEqual(payload.request.payload.scope,f.batch.tasks[n-1].scope);
63
+ assert.equal(payload.request.payload.specification.task.id,identity.taskId);
64
+ assert.deepEqual(payload.request.payload.specification.sources,buildManifest(f.specsDir));
62
65
  const content=`export const value = ${40+n};\n`;
63
66
  if(!f.protected)fs.writeFileSync(path.join(f.codeProject,`task${n}.mjs`),content);
64
67
  respond(row,{status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
@@ -1,3 +1,4 @@
1
+ import {buildManifest} from './cm-spec-manifest.mjs';
1
2
  import test from 'node:test';
2
3
  import assert from 'node:assert/strict';
3
4
  import fs from 'node:fs';
@@ -18,7 +19,7 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
18
19
  fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
19
20
  for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
20
21
  fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n');
21
- fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature]}));
22
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
22
23
  fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
23
24
  const config={version:1,repositoryId:'batch-fixture',batchId:'batch-fixture',specsDir,codeProject,
24
25
  tasks:['T-001','T-002'].map((taskId,index)=>({feature,taskId,scope:[`file${index}.js`],requirements:['requirements.md']}))};
@@ -28,6 +29,9 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
28
29
  excludedContexts:['host'],hostDecision:{status:'approved'},applicableAgentFiles:[],
29
30
  developer:{provider:'codex',requestedModel:'fixture',contextId:'author',run:createCodexDeveloperRun({requestedModel:'fixture',
30
31
  worker:async({prompt},{signal})=>{
32
+ const material=JSON.parse(prompt.split('<cm-developer-data-json>\n')[1]).specification;
33
+ assert.equal(material.task.id,definition.identity.taskId);
34
+ assert.deepEqual(material.sources,buildManifest(specsDir));
31
35
  calls.push(definition.identity.taskId);fs.writeFileSync(path.join(codeProject,definition.scope[0]),'implemented\n');
32
36
  if(mode==='cancel'){started();await new Promise(resolve=>signal.addEventListener('abort',resolve,{once:true}));}
33
37
  const application={status:'no_relevant_lesson',note:null};
@@ -46,6 +50,8 @@ test(`real multi-task runner keeps QA and recovery authoritative: ${mode}`,async
46
50
  check:async()=>[{id:'fixture',command:['fixture'],outcome:'passed',exitCode:0,evidence:'Synthetic task check'}],
47
51
  reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
48
52
  contexts:['review-1','review-2'],run:(request,{onEvent})=>{
53
+ assert.equal(request.payload.reviewPackage.specification.task.id,definition.identity.taskId);
54
+ assert.deepEqual(request.payload.reviewPackage.specification.sources,buildManifest(specsDir));
49
55
  if(mode==='learning'&&request.identity.taskId==='T-001')
50
56
  assert(request.payload.reviewPackage.changes.some(change=>change.path==='AGENTS.md'));
51
57
  for(const event of [{event:'thread.started',provider_thread:`review-${request.identity.taskId}`},
@@ -1,3 +1,4 @@
1
+ import {buildManifest} from './cm-spec-manifest.mjs';
1
2
  import test from 'node:test';
2
3
  import assert from 'node:assert/strict';
3
4
  import fs from 'node:fs';
@@ -28,7 +29,7 @@ function fixture(t){
28
29
  fs.writeFileSync(path.join(specsDir,'0.bootstrap','requirements.md'),'# Requirements\nSynthetic approved scaffold and project instructions.\n');
29
30
  fs.writeFileSync(path.join(specsDir,'0.bootstrap','design.md'),'# Design\nJavaScript; no Git; frontend module.\n');
30
31
  fs.writeFileSync(path.join(specsDir,'0.bootstrap','tasks.md'),'- [ ] T-001: 生成项目骨架 scaffold\n- [ ] T-002: 生成 .claude/ 规范(cm-init)\n');
31
- fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['0.bootstrap']}));
32
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['0.bootstrap'],specFiles:buildManifest(specsDir)}));
32
33
  return {root,codeProject,specsDir,calls:[],reviews:[],businessCalls:0};
33
34
  }
34
35
  function definition(f,taskId){
@@ -1,3 +1,4 @@
1
+ import {buildManifest} from './cm-spec-manifest.mjs';
1
2
  import test from 'node:test';
2
3
  import assert from 'node:assert/strict';
3
4
  import fs from 'node:fs';
@@ -34,7 +35,7 @@ for(const mode of ['history','retest','unknown','failed-retest','double-pass','d
34
35
  ...(automatic?{auto_fix:mode==='automatic-explicit'?'explicit':'auto'}:{})}}));
35
36
  for(const name of ['requirements','design'])fs.writeFileSync(path.join(specsDir,feature,`${name}.md`),'# Synthetic fixture');
36
37
  fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement value\n');
37
- fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature]}));
38
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
38
39
  let developers=0,parentReviews=0,childReviews=0,repairs=0,qaRuns=0,parent=null,serial=null;
39
40
  const events=(onEvent,thread)=>{
40
41
  for(const event of [{event:'thread.started',provider_thread:thread},{event:'turn.started',item_type:null},
@@ -12,6 +12,7 @@ import {createQaFixOwnerHost} from '../runtime/js/cm-ai/host-qa-fix-owner.mjs';
12
12
  import {createFixLearningPreparation} from '../runtime/js/cm-fix/learning.mjs';
13
13
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
14
14
  import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
15
+ import {loadConfig,declaredRuntimes,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
15
16
  import {readHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
16
17
  import {digest,json,need,shape} from '../runtime/js/cm-ai/effect-contract.mjs';
17
18
  export {executionFor as createConversationExecution,reviewConfiguration as readConversationReviewConfiguration};
@@ -28,7 +29,7 @@ const fixLocalPermissions=new Map(['red-test','baseline','regression','learning-
28
29
  'test-author','repair','cause-review','final-review']
29
30
  .map(name=>[`--allow-qa-fix-${name}`,`--allow-${name}`]));
30
31
 
31
- const usage='cm-ai-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-development [--runtime codex|claude] [--review-config PATH] [--allow-review-attempt 1|2] [--workflow-config PATH] [--allow-qa]\ncm-ai-host.mjs preflight --config PATH --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
32
+ const usage='cm-ai-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-development [--runtime codex|claude] [--failover] [--review-config PATH] [--allow-review-attempt 1|2] [--workflow-config PATH] [--allow-qa]\ncm-ai-host.mjs preflight --config PATH --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
32
33
 
33
34
  function reviewConfiguration(file){
34
35
  const info=fs.lstatSync(file);
@@ -43,6 +44,30 @@ function reviewConfiguration(file){
43
44
  }
44
45
 
45
46
  async function protectedExecutionFor(definition,hostContextId,extra,review,mode,workflow,bridge,bootstrap=null){
47
+ const runtime=extra.get('--runtime')??'codex';
48
+ const selected=resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime);
49
+ need(review!==null,'review_configuration_required');
50
+ need(['1','2'].includes(extra.get('--allow-provider-development-attempt')),'provider_development_authorization_required');
51
+ const attempt=Number(extra.get('--allow-provider-development-attempt'));
52
+ need(mode!=='create'||attempt===1,'invalid_development_attempt');
53
+ // Child fix configuration is checked before opening the parent store below.
54
+ const file=extra.get('--protected-config'),info=fs.lstatSync(file);
55
+ need(info.isFile()&&!info.isSymbolicLink()&&info.size<=64*1024,'invalid_protected_config');
56
+ const config=json(JSON.parse(fs.readFileSync(file,'utf8')));shape(config,['model','checkCommands','timeoutMs']);
57
+ return executionFor(definition,hostContextId,bridge,review,
58
+ extra.has('--allow-review-attempt')?Number(extra.get('--allow-review-attempt')):null,
59
+ workflow,extra.has('--allow-qa'),runtime,{
60
+ protection:{checkCommands:config.checkCommands,timeoutMs:config.timeoutMs},
61
+ providerDevelopment:{model:config.model,attempt,...selected},
62
+ ...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{}),
63
+ });
64
+ }
65
+
66
+
67
+ // Existing Codex-only runs retain their exact configuration/context identities.
68
+ // A successful original fingerprint check is the sole authority for this path;
69
+ // no migration, journal rewrite, or in-flight provider switch is permitted.
70
+ async function legacyProtectedExecutionFor(definition,hostContextId,extra,review,mode,workflow,bridge,bootstrap=null){
46
71
  need((extra.get('--runtime')??'codex')==='codex','protected_runtime_unsupported');
47
72
  need(review!==null,'review_configuration_required');
48
73
  need(['1','2'].includes(extra.get('--allow-provider-development-attempt')),'provider_development_authorization_required');
@@ -66,18 +91,27 @@ async function protectedExecutionFor(definition,hostContextId,extra,review,mode,
66
91
  authorizeDevelopment:request=>({status:request.identity.attempt===attempt
67
92
  &&digest({...request.identity,attempt:1})===digest(definition.identity)?'approved':'denied'})});
68
93
  }
69
-
94
+ function canResumeLegacyProtected(definition,runtime){
95
+ if(runtime!=='codex')return false;
96
+ const config=loadConfig({projectRoot:definition.codeProject});
97
+ return ['unknown','codex'].includes(declaredRuntimes(config).available)
98
+ &&['coder','reviewer'].every(role=>['current-ai','codex-cli'].includes(config.roles[role].adapter));
99
+ }
70
100
 
71
101
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
72
102
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Approved 0.bootstrap only: --bootstrap-config PATH {selection:null for scaffold, or original cm-init selection for rules} and --allow-bootstrap-write. Original scope must include fixed instruction targets; they are host-written inside the original task effect, checked/reviewed and reloaded. No Git/install/network grant. Optional codeProjects selects disjoint real roots below codeProject; prefix scope/requirements and use protected current-session checks with a declared codeProject per command.\n');
73
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session mode (Codex or Claude; also batch): --protected-conversation-config PATH with {checkCommands,timeoutMs}. No extra model call. The current host returns scoped UTF-8 edits; native Codex sandbox applies them and runs the declared checks. Original author runtime, per-attempt Review and QA permissions remain required. Do not combine with --protected-config. Same original 64KiB transport limit; unavailable/binary changes stop, never switch to direct writes.\n');
74
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected single-task Codex mode: add --protected-config PATH --allow-provider-development-attempt 1|2 and --review-config PATH. Protected config is {model,checkCommands,timeoutMs}; roots and host identity come from the original run definition and launch. This explicitly permits one task attempt of real developer execution and its declared native-sandbox checks; --allow-development alone does not. Review separately requires --allow-review-attempt 1|2. Diagnostics are required but are not review authorization. Optional original --workflow-config PATH and --allow-qa connect protected QA commands and documentation within the same developer invocation before Review; host semantic/browser/inspection requests retain their original contracts, not arbitrary writes. Default current-session mode is unchanged. Protected parent mode rejects Claude; original QA-fix options require child configuration.protectSpecs=true and all original child action permissions. Protected fix writes use text proposals, not direct host edits. The original QA/documentation/finalizer gates remain required. No installation or Git authority.\n');
103
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session mode (Codex or Claude; also batch): --protected-conversation-config PATH with {checkCommands,timeoutMs}; timeoutMs bounds both check commands and the reviewer process. A review transport timeout with no result can resume once per attempt with fresh review authorization; a result-bearing timeout still requires reconciliation. No extra model call. The current host returns scoped UTF-8 edits; native Codex sandbox applies them and runs the declared checks. Original author runtime, per-attempt Review and QA permissions remain required. Do not combine with --protected-config. Same original 64KiB transport limit; unavailable/binary changes stop, never switch to direct writes.\n');
104
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected single-task CLI mode: add --protected-config PATH --allow-provider-development-attempt 1|2 and --review-config PATH. Protected config is {model,checkCommands,timeoutMs}; roots and host identity come from the original run definition and launch. This explicitly permits one task attempt of real developer execution and its declared native-sandbox checks; --allow-development alone does not. Review separately requires --allow-review-attempt 1|2. Diagnostics are required but are not review authorization. Optional original --workflow-config PATH and --allow-qa connect protected QA commands and documentation within the same developer invocation before Review; host semantic/browser/inspection requests retain their original contracts, not arbitrary writes. Default current-session mode is unchanged. Protected parent mode selects coder/reviewer CLIs from the project declaration; Claude returns protected-text-v1 proposals for host validation and sandbox application; original QA-fix options require child configuration.protectSpecs=true and all original child action permissions. Protected fix writes use text proposals, not direct host edits. The original QA/documentation/finalizer gates remain required. No installation or Git authority.\n');
75
105
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--auto-qa-fix optionally connects parent advance -> fix_run -> re-QA. Requires --qa-fix-template-config, --allow-qa-fix-start, original action permissions and project policies.auto_fix=auto. Explicit/never policies stop. Unknown, blocked or incomplete repair stops; status/cancel remain available and no fourth QA round is dispatched.\n');
76
106
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--qa-fix-template-config PATH is an alternative to --qa-fix-owner-config. Supply {specsRoot, feature, identity: parent identity, configuration: original fix configuration without qaSource}. Each fix request binds it to the latest completed QA failure; identity/digests are generated, commands/scope/permissions are not. Existing child configuration remains immutable.\n');
77
107
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('fix_run continuously executes normal stages of the fixed QA child using the same binding as fix_advance. Requires --allow-qa-fix-start and every original per-action permission/configuration. Stops on unknown, blocked, observation, revision-required or unchanged state. It does not auto-switch child configuration or run parent QA.\n');
78
108
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('fix_action delegates to the shared original cm-fix dispatcher. Local flags: --allow-qa-fix-red-test, --allow-qa-fix-baseline, --allow-qa-fix-regression, --allow-qa-fix-learning-writeback, --allow-qa-fix-walkthrough, --allow-qa-fix-finish. Adapter flags: --allow-qa-fix-test-author, --allow-qa-fix-repair, --allow-qa-fix-cause-review, --allow-qa-fix-final-review, with separate --qa-fix-review-config PATH and matching original child reviewer metadata. All require --allow-qa-fix-start and the original action configuration/gates. Parent --review-config/--allow-review-attempt do not grant child review permission.\n');
79
109
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-qa-fix-start additionally permits fix_advance to create or resume the fixed QA child and run only its original Learning/reproduction/diagnosis stages. Child hostContextId and runtime must match this host. It does not authorize test authoring, repair, independent provider Review, finish, Git or re-QA. Active child status/cancel use the original child owner; repeated advance never resets an unknown or completed step.\n');
80
110
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--qa-fix-owner-config PATH enables read-only fix_status. The file contains the existing fix owner definition {specsRoot, identity, configuration}, including its exact original qaSource and immutable configuration, not provider grants. fix_status binds the parent identity/packageDigest/testRunId, serially closes the parent writer, opens only an existing child, reads its original completion evidence, closes it and resumes the same parent. It does not create/execute repairs, rerun QA or clear correction gates.\n');
111
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session invalid_result means local value/Learning validation failed before file writes. Fix the reply, keep the same configuration, host identity and runId, restart with --mode resume and advance: blocked/developer_result_invalid retries develop at the same attempt. no_new_lesson requires reason:null (dogfood incident: nonempty reason previously wrote files then stranded the run as unknown). Already-applied proposals must match expected disk hashes; conflicts block as protected_edit_stale. Worker exceptions/timeouts and old unknown history are not retryable.\n');
112
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('New cm-ai runs carry approved specification data in developer requests and review packages: task/verification, all AC lines, design (64 KiB UTF-8 maximum, truncated:true above it), task-related test cases and manifest hashes. Sources must match .cm-specs-status.specFiles or spec_drift blocks. requirements may be [] or additional code-project files; specs never become writable scope. Legacy runs/packages retain their original representation. Dogfood: separate specs/code roots previously left developers and reviewers without task/interface contracts.\n');
113
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Completed fixture_completed runs originally without QA may explicitly attach N6 once on --mode resume with --workflow-config (non-null qa) and --allow-qa. Original definition, scope, requirements, identity and non-workflow configuration must match. The immutable qa-attached journal record binds the full resumed config fingerprint; later resumes require that same configuration and fresh --allow-qa. qa still requests qa_assess; no automatic decision or repeated development/Review. Dogfood: missing workflow at create previously stranded mandatory feature QA.\n');
114
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated.\n');
81
115
  if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\n');return 0;}
82
116
  let run,bridge;
83
117
  try{
@@ -105,8 +139,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
105
139
  const extra=new Map();
106
140
  for(let index=8;index<argv.length;index++){
107
141
  const name=argv[index];need(!extra.has(name),'invalid_arguments');
108
- need(['--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--workflow-config','--allow-qa','--runtime','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments');
109
- if(['--allow-bootstrap-write','--allow-qa','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
142
+ need(['--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--workflow-config','--allow-qa','--rerun-unknown-qa','--runtime','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments');
143
+ if(['--allow-bootstrap-write','--allow-qa','--rerun-unknown-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
110
144
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(name,argv[++index]);}
111
145
  }
112
146
  const review=extra.has('--review-config')?reviewConfiguration(extra.get('--review-config')):null;
@@ -114,6 +148,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
114
148
  let allowedAttempt=null;
115
149
  if(extra.has('--allow-review-attempt')){need(['1','2'].includes(extra.get('--allow-review-attempt')),'invalid_arguments');allowedAttempt=Number(extra.get('--allow-review-attempt'));}
116
150
  need(!extra.has('--allow-qa')||workflow?.qa!=null,'invalid_arguments');
151
+ need(!extra.has('--rerun-unknown-qa')||(argv[4]==='resume'&&extra.has('--allow-qa')),'qa_recovery_authorization_required');
117
152
  const hasFix=extra.has('--qa-fix-owner-config')||extra.has('--qa-fix-template-config');
118
153
  need(!(extra.has('--qa-fix-owner-config')&&extra.has('--qa-fix-template-config')),'invalid_fix_config');
119
154
  need(!extra.has('--allow-qa-fix-start')||hasFix,'qa_fix_source_required');
@@ -125,7 +160,28 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
125
160
  const protection=extra.has('--protected-conversation-config')?readConversationProtection(extra.get('--protected-conversation-config')):null;
126
161
  const bootstrap=extra.has('--bootstrap-config')?readBootstrapConfiguration(extra.get('--bootstrap-config')):null;
127
162
  need(!extra.has('--allow-bootstrap-write')||bootstrap!==null,'bootstrap_configuration_required');
163
+ // Checked before the definition is read so the conflict is reported on its own.
164
+ need(!(extra.has('--failover')&&extra.has('--protected-config')),'failover_unsupported_in_protected_mode');
128
165
  const definition=readRunDefinition(argv[2]);bridge=createHostToolBridge();
166
+ // Startup-only role failover. The project's runtimes.available declaration is
167
+ // primary: it fixes which runtimes may be chosen and, via roles.coder, the
168
+ // requested start runtime. The CLI probe only confirms reachability. It never
169
+ // switches an in-flight task; a switch is always announced, never silent.
170
+ // Protected mode binds both roles before dispatch; startup failover remains a separate path.
171
+ let runtime=extra.get('--runtime')??'codex';
172
+ if(extra.has('--failover')){
173
+ const {selectRuntime,describeSelection}=await import('../runtime/js/cm-ai/runtime-failover.mjs');
174
+ const {probeRuntimes}=await import('./cm-failover.mjs');
175
+ const {loadConfig,declaredRuntimes,runtimeForAdapter}=await import('./cm-workflow-config.mjs');
176
+ const config=loadConfig({projectRoot:definition.codeProject}),declared=declaredRuntimes(config);
177
+ const requested=extra.get('--runtime')??runtimeForAdapter(config.roles.coder.adapter);
178
+ const reach=new Map(probeRuntimes().map(result=>[result.runtime,result.available]));
179
+ const selection=selectRuntime({role:'developer',requested,allowed:[...declared.allowed],
180
+ probe:(candidate)=>reach.get(candidate)===true});
181
+ runtime=selection.runtime;
182
+ error.write(`cm-ai-host failover: 声明 runtimes.available=${declared.available}; ${describeSelection(selection)}\n`);
183
+ if(selection.switched)error.write('cm-ai-host failover: CLI 可解析不等于配额可用;本次切换只决定起跑运行时。\n');
184
+ }
129
185
  const templated=extra.has('--qa-fix-template-config');let fix=null;
130
186
  if(hasFix){
131
187
  const file=extra.get(templated?'--qa-fix-template-config':'--qa-fix-owner-config'),info=fs.lstatSync(file);
@@ -133,11 +189,24 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
133
189
  fix=json(JSON.parse(fs.readFileSync(file,'utf8')),64*1024);
134
190
  if(extra.has('--protected-config')||protection)need(fix.configuration?.protectSpecs===true,'protected_fix_required');
135
191
  }
136
- const execution=extra.has('--protected-config')
137
- ?await protectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap)
138
- :executionFor(definition,argv[6],bridge,review,allowedAttempt,workflow,extra.has('--allow-qa'),extra.get('--runtime')??'codex',
139
- {...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
140
- run=await openControlRun(definition,argv[4],execution);
192
+ let execution;
193
+ if(argv[4]==='resume'&&extra.has('--protected-config')&&canResumeLegacyProtected(definition,runtime)){
194
+ try{
195
+ execution=await legacyProtectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap);
196
+ run=await openControlRun(definition,argv[4],execution,{rerunUnknownQa:extra.has('--rerun-unknown-qa')});
197
+ error.write('cm-ai-host: resumed original Codex protected execution after exact fingerprint validation.\n');
198
+ }catch(cause){
199
+ if(!['fingerprint_mismatch','tool_preflight_missing'].includes(cause.code))throw cause;
200
+ execution=undefined;
201
+ }
202
+ }
203
+ if(!run){
204
+ execution=extra.has('--protected-config')
205
+ ?await protectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap)
206
+ :executionFor(definition,argv[6],bridge,review,allowedAttempt,workflow,extra.has('--allow-qa'),runtime,
207
+ {...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
208
+ run=await openControlRun(definition,argv[4],execution,{rerunUnknownQa:extra.has('--rerun-unknown-qa')});
209
+ }
141
210
  if(run.blocked){output.write(JSON.stringify({outcome:'blocked',admission:run.blocked})+'\n');return 1;}
142
211
  if(hasFix){
143
212
  need(fs.realpathSync(fix.specsRoot)===fs.realpathSync(definition.specsDir)
@@ -145,7 +214,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
145
214
  &&(templated?fix.feature:fix.configuration.qaSource.feature)===definition.feature,'qa_fix_source_mismatch');
146
215
  if(templated)need(digest(fix.identity)===digest(definition.identity),'qa_fix_source_mismatch');
147
216
  if(extra.has('--allow-qa-fix-start'))need(fix.configuration.hostContextId===argv[6]
148
- &&(fix.configuration.runtime??'codex')===(extra.get('--runtime')??'codex'),'qa_fix_host_mismatch');
217
+ &&(fix.configuration.runtime??'codex')===runtime,'qa_fix_host_mismatch');
149
218
  const fixPermissions=[...fixLocalPermissions].filter(([flag])=>extra.has(flag)).map(([,permission])=>permission);
150
219
  const fixReview=extra.has('--qa-fix-review-config')?reviewConfiguration(extra.get('--qa-fix-review-config')):null;
151
220
  need(!fixPermissions.includes('--allow-test-author')||(fix.configuration.testAuthor&&fixReview),'test_author_configuration_required');